import { getControl, getPSUIActionByModelObject, IPSAppDEEditView, IPSDEToolbar } from '@ibizstudio-ex/runtime';
import { CreateElement } from 'vue';
import { Vue, Prop } from 'vue-property-decorator';
import { DesignContext } from '../../entities';
import { Util } from '@ibizstudio-ex/runtime';
import { NoticeHandler } from '@ibizstudio-ex/template-vue';
import './design-view-base.less';

/**
 * 设计视图基础
 *
 * @author chitanda
 * @date 2021-04-14 11:04:33
 * @export
 * @class DesignViewBase
 * @extends {Vue}
 */
export class DesignViewBase extends Vue {
    /**
     * 数据上下文
     *
     * @type {*}
     * @memberof FormDesign
     */
    @Prop()
    context: any;

    @Prop()
    params: any;

    /**
     * 视图模型
     *
     * @type {*}
     * @memberof FormDesign
     */
    @Prop()
    viewModel!: IPSAppDEEditView;

    /**
     * 设计上下文
     *
     * @author chitanda
     * @date 2021-04-14 11:04:01
     * @type {DesignContext}
     */
    @Prop()
    ctx!: DesignContext;

    /**
     * 属性视图
     *
     * @author chitanda
     * @date 2021-04-14 11:04:30
     * @type {IPSAppDEEditView}
     */
    propertyView?: IPSAppDEEditView;

    /**
     * 工具栏模型
     *
     * @author chitanda
     * @date 2021-04-14 11:04:29
     * @type {IPSDEToolbar}
     */
    toolBarModel?: IPSDEToolbar;

    /**
     * 显示素材区
     *
     * @type {boolean}
     * @memberof DesignViewBase
     */
    showMaterial: boolean = true;

    /**
     * 素材区搜索内容
     *
     * @type {string}
     * @memberof FormDesign
     */
     materialSearch: string = '';

     /**
      * 结构区搜索内容
      *
      * @type {string}
      * @memberof FormDesign
      */
     structureSearch: string = '';

    /**
     * 设计
     *
     * @type {string}
     * @memberof DesignViewBase
     */
    viewClassName:any[] = ['design-view'];

    /**
     * 是否显示预览按钮
     *
     * @type {boolean}
     * @memberof DesignViewBase
     */
    previewVisible: boolean = false;

    /**
     * Vue生命周期，实例创建完成
     *
     * @memberof FormDesign
     */
    created() {
        this.fillCtx();
        this.toolBarModel = getControl(this.viewModel, 'toolbar') as IPSDEToolbar;
        this.propertyView = this.viewModel.findPSAppViewRef('PROPERTYVIEW')?.getRefPSAppView() as IPSAppDEEditView;
    }

    /**
     * 填充设计上下文
     *
     * @memberof FormDesign
     */
    fillCtx() {
        if (this.context) {
            Object.assign(this.ctx.context, this.context);
            delete this.ctx.context.srfsessionid;
        }
    }

    async save(): Promise<any> {}

    /**
     * 工具栏点击
     *
     * @memberof FormDesign
     */
    async handleItemClick(data: any, _event: any): Promise<any> {
        const targetViewLogic: any = this.viewModel.findPSAppViewLogic(`toolbar_${data.tag}_click`);
        const action = targetViewLogic.getPSAppViewUIAction();
        const uIAction = await getPSUIActionByModelObject(action);
        const tag = uIAction.uIActionTag.toLowerCase();
        if (Object.is(tag, 'save')) {
            return this.saveAction();
        } else if (tag?.indexOf('modeledit') > -1) {
            if (await this.saveAction()) {
                await this.viewModel.fill(true);
                const entity = this.viewModel.getPSAppDataEntity();
                this.context.viewpath = 'PSSYSAPPS/FormDesign/PSAPPDEVIEWS/PSSystemModelEdit.json';
                this.context.srfdename = entity?.codeName.toLowerCase();
                const view: any = {
                    viewname: 'app-view-shell',
                    title: this.viewModel.caption,
                    placement: 'DRAWER_TOP',
                };
                const container: any = this.$appdrawer.openDrawer(view, Util.getViewProps(this.context, data));
                container.subscribe(async (result: any) => {
                    if (!result || !Object.is(result.ret, 'OK')) {
                        return;
                    }
                    await this.ctx.ctrl.reload();
                    this.ctx.evt.emit('reload');
                });
            }
        } else {
            // AppViewLogicService.getInstance().executeViewLogic(
            //     `${data.tag}_click`,
            //     null,
            //     this.ctx.context,
            //     {},
            //     viewlogicData.getPSAppViewLogics!,
            // );
        }
    }

    async saveAction(): Promise<boolean> {
        const loading = (this as any).$loading({
            lock: true,
            text: '保存中...',
            background: '#ffffffe6',
        });
        try {
            const res = await this.save();
            if (res.status === 200) {
                NoticeHandler.successHandler('保存成功');
                loading.close();
                return true;
            } else {
                NoticeHandler.errorHandler(res);
            }
        } catch (error) {
            this.$throw(error);
        }
        loading.close();
        return false;
    }

    /**
     * 绘制素材区搜索框
     *
     * @return {*}
     * @memberof DesignViewBase
     */
    renderMaterialSearch() {
        return (
            <div class='design-search' key='search'>
                <el-input
                    prefix-icon='el-icon-search'
                    size='small'
                    placeHolder="输入关键词进行过滤"
                    spellcheck={false}
                    clearable
                    v-model={this.materialSearch}
                ></el-input>
            </div>
        );
    }

    /**
     * 绘制结构区搜索框
     *
     * @return {*}
     * @memberof DesignViewBase
     */
    renderStructureSearch() {
        return (
            <div class='design-search' key='search'>
                <el-input
                    prefix-icon='el-icon-search'
                    size='small'
                    spellcheck={false}
                    clearable
                    v-model={this.structureSearch}
                ></el-input>
            </div>
        );
    }

    renderToolBar() {
        if (!this.toolBarModel) {
            return null;
        }
        return (
            <design-view-toolbar
                slot='toolbar'
                mode={this.viewModel?.viewStyle || 'DEFAULT'}
                toolbarModels={this.toolBarModel.getPSDEToolbarItems()}
                on-item-click={(data: any, $event: any) => {
                    this.handleItemClick(data, $event);
                }}
            ></design-view-toolbar>
        );
    }

    /**
     * 绘制素材区
     *
     * @author chitanda
     * @date 2021-04-14 11:04:26
     * @return {*}  {*}
     */
    renderMaterial(): any {}

    /**
     * 绘制结构树
     *
     * @author chitanda
     * @date 2021-04-14 11:04:31
     * @return {*}  {*}
     */
    renderStructureTree(): any {
        return <ibz-design-structure-tree ctx={this.ctx} />;
    }

    /**
     * 绘制内容区
     *
     * @author chitanda
     * @date 2021-04-14 11:04:37
     * @return {*}  {*}
     */
    renderContent(): any {
        return <ibz-design-default-content ctx={this.ctx} childComponent='ibz-design-page' />;
    }

    renderHome(): any {}

    /**
     * 绘制预览按钮
     *
     * @return {*}  {*}
     * @memberof DesignViewBase
     */
    renderPreview(): any {
        return this.previewVisible ? (
            <icon
                class={{ disabled: this.ctx?.previewPSpfService.previewLoading }}
                title='预览'
                type='ios-eye'
                on-click={() => this.preview()}
            />
        ) : null;
    }

    /**
     * 预览
     *
     * @return {*}
     * @memberof DesignViewBase
     */
    preview() {
        const { context, ctrl } = this.ctx;
        const srfdename = ctrl.data?.srfdename;
        if (!srfdename) {
            return;
        }
        this.ctx.previewPSpfService.preview(
            context[srfdename.toLowerCase()],
            context.dynainst || context.srfcontainer,
            srfdename,
        );
    }

    /**
     * 绘制属性视图
     *
     * @param {CreateElement} h
     * @return {*}
     * @memberof DesignViewBase
     */
    renderPropertyView(h: CreateElement) {
        return this.propertyView
            ? h('app-view-shell', {
                  props: {
                      staticProps: {
                          designCtx: this.ctx,
                          viewDefaultUsage: false,
                      },
                      dynamicProps: {
                          viewparam: {},
                          viewdata: JSON.stringify({
                            ...this.ctx.context,
                            viewpath: this.propertyView.modelFilePath,
                          }),
                      },
                  },
              })
            : null;
    }

    render(h: CreateElement): any {
        if (!this.ctx.ctrl.modelInit) {
            return null;
        }
        return (
            <div class={this.viewClassName}>
                <div class='design-view-header'>
                    <div class='title'>{this.ctx.mainInfo || this.viewModel?.title}</div>
                    <div class='action-bar'>
                        {this.renderHome()}
                        {this.renderPreview()}
                    </div>
                    {this.renderToolBar()}
                </div>
                <div class='design-view-content'>
                    <design-container showMaterial={this.showMaterial}>
                        <template slot='material'>{this.renderMaterial()}</template>
                        <template slot='structureTree'>{this.renderStructureTree()}</template>
                        <template slot='content'>{this.renderContent()}</template>
                        <template slot='attributes'>{this.renderPropertyView(h)}</template>
                    </design-container>
                </div>
            </div>
        );
    }
}
