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

/**
 * 设计视图基础
 *
 * @author chitanda
 * @date 2021-04-14 11:04:33
 * @export
 * @class DesignViewBase
 * @extends {Vue}
 */
export class DesignViewBase2 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;

    /**
     * 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) {
        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')) {
            await 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',
                };
                let 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) {
                this.$success({
                    content: '保存成功',
                });
                loading.close();
                return true;
            } else {
                this.$throw(res);
            }
        } catch (error) {
            this.$throw(error);
        }
        loading.close();
        return false;
    }

    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 {}

    render(h: CreateElement): any {
        return (
            <div class='design-view2'>
                <div class='design-view-header'>
                    <div class='title'>{this.ctx.mainInfo || this.viewModel?.title}</div>
                    <div class='home'>{this.renderHome()}</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.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}
                        </template>
                    </design-container>
                </div>
            </div>
        );
    }
}
