import { IPSControl, IPSDEToolbar, IPSDEToolbarItem } from '@ibiz/dynamic-model-api';
import { AppVisualSheet } from 'app-visual-sheet';
import { AppServiceBase, throttle } from 'ibiz-core';
import { Component } from 'vue-property-decorator';
import { AppDefaultViewLayout } from "../app-default-view-layout/app-default-view-layout";
import './app-default-mdview-layout.less';

/**
 * 视图基础布局
 *
 * @export
 * @class AppDefaultViewLayout
 * @extends {Vue}
 */
@Component({})
export class AppDefaultMDViewLayout extends AppDefaultViewLayout {

    /**
     * 实际是否展开搜索表单
     *
     * @type {boolean}
     * @memberof AppDefaultMDViewLayout
     */
    public isExpandSearchForm: boolean = false;

    /**
     * 初始化视图特有数据
     *
     * @memberof AppDefaultMDViewLayout
     */
    public initViewSpecificData() {
        this.isExpandSearchForm = this.viewInstance?.expandSearchForm ? true : false;
    }

    /**
     * 计算目标部件所需参数
     *
     * @param controlInstance 部件模型
     * @param args 额外参数 {staticProps:{xxx},dynamicProps:{xxx},customEvent:{xxx}}
     * @memberof AppDefaultMDViewLayout
     */
    public computeTargetCtrlData(controlInstance: any, args?: any) {
        let targetCtrlName: string = `app-control-shell`;
        let targetCtrlParam: any = {
            staticProps: {
                containerInstance: this.containerModel,
                modelData: controlInstance,
                ref: controlInstance.name,
                viewLoadingService: this.viewLoadingService,
                layoutLoadingService: this.layoutLoadingService
            },
            dynamicProps: {
                viewparams: this.viewparams,
                context: this.context,
                viewCtx: this.viewCtx
            }
        };
        if (!Object.is(controlInstance?.controlType, 'SEARCHFORM') &&
            !Object.is(controlInstance?.controlType, 'FORM') &&
            !Object.is(controlInstance?.controlType, 'TOOLBAR') &&
            !Object.is(controlInstance?.controlType, 'SEARCHBAR')) {
            Object.assign(targetCtrlParam.staticProps, {
                opendata: this.opendata,
                newdata: this.newdata,
            });
        }
        Object.defineProperty(targetCtrlParam.staticProps, 'containerInstance', { enumerable: false, writable: true });
        Object.defineProperty(targetCtrlParam.staticProps, 'modelData', { enumerable: false, writable: true });
        let targetCtrlEvent: any = {
            'ctrl-event': ({ controlname, action, data }: { controlname: string, action: string, data: any }) => {
                this.onCtrlEvent(controlname, action, data);
            }
        }
        // 合并视图级参数
        Object.assign(targetCtrlParam.staticProps, { viewState: this.viewState, viewtag: this.viewtag, viewIsProxyMode: this.viewProxyMode });
        Object.assign(targetCtrlEvent, {
            closeView: ($event: any) => {
                this.$emit('view-event', { viewName: this.viewInstance.codeName, action: 'viewClosed', data: $event });
            }
        })
        // 合并多数据视图级参数
        if (Object.is(controlInstance.controlType, 'SEARCHFORM') || Object.is(controlInstance.controlType, 'SEARCHBAR')) {
            Object.assign(targetCtrlParam.dynamicProps, {
                isExpandSearchForm: this.isExpandSearchForm
            });
        } else {
            Object.assign(targetCtrlParam.staticProps, {
                mDCtrlActiveMode: (this.viewInstance as any).mDCtrlActiveMode,
            });
        }
        // 合并传入自定义参数
        if (args && args.staticProps && Object.keys(args.staticProps).length > 0) {
            Object.assign(targetCtrlParam.staticProps, args.staticProps);
        }
        if (args && args.dynamicProps && Object.keys(args.dynamicProps).length > 0) {
            Object.assign(targetCtrlParam.dynamicProps, args.dynamicProps);
        }
        if (args && args.customEvent && Object.keys(args.customEvent).length > 0) {
            Object.assign(targetCtrlEvent, args.customEvent);
        }
        return { targetCtrlName: targetCtrlName, targetCtrlParam: targetCtrlParam, targetCtrlEvent: targetCtrlEvent };
    }

    /**
     * 渲染目标部件
     *
     * @param {IPSControl} control
     * @param {boolean} [slotMode=true]
     * @return {*} 
     * @memberof AppDefaultMDViewLayout
     */
    public renderTargetControl(control: IPSControl, slotMode: boolean = true, args?: any) {
        if (Object.is(control.controlType, 'TOOLBAR')) {
            if (Object.is(control.name, 'toolbar')) {
                return this.renderToolBar();
            } else {
                const viewToolBar: IPSDEToolbar = control as IPSDEToolbar;
                const targetViewToolbarItems: any[] = [];
                if (viewToolBar && viewToolBar.getPSDEToolbarItems()) {
                    viewToolBar.getPSDEToolbarItems()?.forEach((toolbarItem: IPSDEToolbarItem) => {
                        targetViewToolbarItems.push(this.initToolBarItems(toolbarItem));
                    });
                }
                return (
                    <view-toolbar
                        slot={`layout-${control.name}`}
                        mode={'DEFAULT'}
                        counterServiceArray={this.counterServiceArray}
                        isViewLoading={this.layoutLoadingService?.isLoading}
                        toolbarModels={targetViewToolbarItems}
                        on-item-click={(data: any, $event: any) => {
                            throttle(this.handleItemClick, [data, $event], this);
                        }}
                    ></view-toolbar>
                );
            }
        } else {
            let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(control, args);
            if (slotMode) {
                return this.$createElement(targetCtrlName, { slot: `layout-${control.name}`, props: targetCtrlParam, ref: control?.name, on: targetCtrlEvent });
            } else {
                return this.$createElement(targetCtrlName, { props: targetCtrlParam, ref: control?.name, on: targetCtrlEvent });
            }
        }
    }

    /**
     * 渲染快速搜索
     *
     * @return {*} 
     * @memberof AppDefaultMDViewLayout
     */
    public renderQuickSearch() {
        if (this.viewInstance.enableQuickSearch && !this.viewInstance.expandSearchForm) {
            const content = this.$scopedSlots.quickSearchFilter?.(this.$slots.searchForm ? this.$slots.searchForm : this.$slots.searchBar ? this.$slots.searchBar : null);
            return content;
        } else {
            return this.$slots.quickSearch;
        }
    }

    /**
     * 绘制头部内容
     * 
     * @memberof AppDefaultGridViewLayout
     */
    public renderViewHeader() {
        return [
            <div class="caption-container">
                {this.showCaption ? <span class='caption-info'>{this.$slots.captionInfo ? this.$slots.captionInfo : this.model.srfCaption}</span> : null}
                {this.$slots.quickGroupSearch}
            </div>,
            this.$slots.quickSearch || (this.viewIsshowToolbar && this.$slots.toolbar) ?
                <div class="bar-container">
                    {this.renderQuickSearch()}
                    {this.viewIsshowToolbar ? this.$slots.toolbar : null}
                </div> : null
        ]
    }

    /**
     * 绘制主体内容
     *
     * @return {*} 
     * @memberof AppDefaultViewLayout
     */
    public renderMainContent() {
        const isRenderVisualCtrl = false;
        if (isRenderVisualCtrl) {
            const appService = AppServiceBase.getInstance();
            const store = appService.getAppStore();
            const i18n = appService.getI18n();
            const router = appService.getRouter();
            return this.$createElement(AppVisualSheet as any, {
                props: { viewInstance: this.viewInstance, store: store, i18n: i18n, router: router }
            }, [
                this.$slots.default
            ])
        } else {
            return this.$slots.default;
        }
    }


    /**
    * 绘制内容
    * 
    * @memberof AppDefaultGridViewLayout
    */
    public renderContent() {
        const noHeader = !this.showCaption && !this.viewIsshowToolbar && !this.$slots.quickGroupSearch && !this.$slots.quickSearch
        let cardClass = {
            'view-card': true,
            'mdview-card': true,
            'view-no-caption': !this.showCaption,
            'view-no-toolbar': !this.viewIsshowToolbar,
            'view-no-header': noHeader
        };
        return (
            <card class={cardClass} disHover={true} bordered={false}>
                {!noHeader ? <div slot='title' class='header-container' key='view-header'>
                    {this.renderViewHeader()}
                </div> : null}
                {this.$slots.topMessage}
                {this.viewInstance.enableQuickSearch && !this.viewInstance.expandSearchForm ? null : this.$slots.searchForm}
                <div class='content-container'>
                    {this.$slots.bodyMessage}
                    {this.renderMainContent()}
                </div>
                {this.$slots.bottomMessage}
            </card>
        );
    }
}