import { AppServiceBase, LogUtil, ModelTool, Util } from '@ibizstudio/runtime';
import { UtilServiceRegister } from '@ibizstudio/runtime';
import { MainControlBase } from "./main-control-base";
/**
 * 数据看板部件基类
 *
 * @export
 * @class ControlBase
 * @extends {DashboardControlBase}
 */
export class DashboardControlBase extends MainControlBase {
    constructor() {
        super(...arguments);
        /**
         * 看板定制状态描述
         *
         * @type {string} unknown 未确定， default 默认， custom 自定义
         * @memberof DashboardControlBase
         */
        this.dashboardType = 'unknown';
        /**
         * modleId
         *
         * @type {string}
         * @memberof DashboardControlBase
         */
        this.modelId = "";
        /**
         * 功能服务名称
         *
         * @type {string}
         * @memberof DashboardControlBase
         */
        this.utilServiceName = "dynadashboard";
        /**
         * 动态设计水平列数
         *
         *  @memberof DashboardControlBase
         */
        this.layoutColNum = 12;
        /**
         * 动态设计单元格高度，80px
         *
         *  @memberof DashboardControlBase
         */
        this.layoutRowH = 80;
        /**
         * 所有的门户部件实例集合
         *
         * @type {*}
         * @memberof DashboardControlBase
         */
        this.portletList = [];
    }
    /**
     * 看板初始化时
     *
     * @memberof DashboardControlBase
     */
    initMountedMap() {
        this.mountedMap.set('self', false);
    }
    /**
     * 初始化挂载状态集合(默认看板时)
     *
     * @memberof ControlBase
     */
    initStaticMountedMap() {
        let controls = ModelTool.getAllPortlets(this.controlInstance);
        controls === null || controls === void 0 ? void 0 : controls.forEach((item) => {
            if (!(item.controlType == "PORTLET" && item.portletType == "CONTAINER")) {
                this.mountedMap.set(item.name, false);
            }
        });
    }
    /**
     * 初始化挂载状态集合(自定义动态看板时)
     *
     * @memberof ControlBase
     */
    initDynamicMountedMap() {
        this.mountedMap.clear();
        this.customModelData.forEach((item) => {
            let portlet = item.modelData;
            this.mountedMap.set(portlet.name, false);
        });
    }
    /**
     * 设置已经绘制完成状态
     *
     * @memberof ControlBase
     */
    setIsMounted(name = 'self') {
        super.setIsMounted(name);
        if ([...this.mountedMap.values()].indexOf(false) == -1) {
            // 执行通知方法
            this.$nextTick(() => {
                this.notifyState();
            });
        }
    }
    /**
     * 初始化数据看板部件实例
     *
     * @memberof AppDefaultDashboard
     */
    async ctrlModelInit(opts) {
        await super.ctrlModelInit();
        this.isEnableCustomized = this.controlInstance.enableCustomized;
        const { codeName } = this.controlInstance;
        this.modelId = `dashboard_${this.appDeCodeName.toLowerCase() || 'app'}_${codeName === null || codeName === void 0 ? void 0 : codeName.toLowerCase()}`;
        if (this.isEnableCustomized) {
            await this.loadPortletList();
        }
    }
    /**
     * 加载门户部件集合
     *
     * @memberof AppDashboardDesignService
     */
    async loadPortletList() {
        var _a, _b;
        const app = AppServiceBase.getInstance().getAppModelDataObject();
        let list = [];
        if ((_b = (_a = app.getAllPSAppPortlets) === null || _a === void 0 ? void 0 : _a.call(app)) === null || _b === void 0 ? void 0 : _b.length) {
            for (const portlet of app.getAllPSAppPortlets()) {
                // 门户部件实例
                const portletInstance = portlet.getPSControl();
                let temp = {
                    portletCodeName: portlet.codeName,
                    modelData: portletInstance,
                };
                list.push(temp);
            }
        }
        this.portletList = list;
    }
    /**
     * 获取门户部件实例
     *
     * @param {*} layoutModel
     * @returns
     * @memberof DashboardControlBase
     */
    getPortletInstance(layoutModel) {
        var _a;
        return (_a = this.portletList.find((item) => { return layoutModel.i === item.portletCodeName; })) === null || _a === void 0 ? void 0 : _a.modelData;
    }
    /**
     * 部件初始化
     *
     * @param {*} [args]
     * @memberof DashboardControlBase
     */
    ctrlInit(args) {
        super.ctrlInit(args);
    }
    viewStateAction(tag, action, data) {
        if (!Object.is(tag, this.name)) {
            return;
        }
        super.viewStateAction(tag, action, data);
        if (Object.is('load', action)) {
            this.loadModel();
        }
    }
    /**
     * 部件挂载
     *
     * @memberof DashboardControlBase
     */
    ctrlMounted(args) {
        super.ctrlMounted(args);
        // 不支持自定义时为默认看板
        if (!this.isEnableCustomized) {
            this.dashboardType = 'default';
        }
    }
    /**
     *  通知状态
     *
     *  @memberof DashboardControlBase
     */
    notifyState() {
        setTimeout(() => {
            if (this.viewState) {
                const refs = this.$refs;
                Object.keys(refs).forEach((name) => {
                    this.viewState.next({
                        tag: name,
                        action: "load",
                        data: JSON.parse(JSON.stringify(this.viewparams))
                    });
                });
            }
        }, 0);
    }
    /**
     * 加载布局与数据模型
     *
     * @memberof DashboardControlBase
     */
    async loadModel() {
        try {
            if (this.isEnableCustomized) {
                let service = await UtilServiceRegister.getService(this.context, this.utilServiceName);
                let res = await service.loadModelData(JSON.parse(JSON.stringify(this.context)), { modelid: this.modelId, utilServiceName: this.utilServiceName });
                if (res && res.status == 200) {
                    const data = res.data;
                    if (data && data.length > 0) {
                        for (const model of data) {
                            model.modelData = this.getPortletInstance(model);
                        }
                        this.customModelData = data;
                        this.initDynamicMountedMap();
                        this.dashboardType = 'custom';
                        this.$forceUpdate();
                    }
                    else {
                        throw new Error(this.$t('app.dashboard.dataerror'));
                    }
                }
                else {
                    throw new Error(this.$t('app.dashboard.serviceerror'));
                }
            }
        }
        catch (error) {
            LogUtil.warn(this.$t('app.dashboard.loaderror') + error);
            this.initStaticMountedMap();
            this.dashboardType = "default";
        }
    }
    /**
     * 处理私人定制按钮
     *
     * @memberof DashboardControlBase
     */
    handleClick() {
        var _a, _b;
        const view = {
            viewname: 'app-portal-design',
            title: (this.$t('app.dashboard.handleclick.title')),
            width: 1600,
            placement: 'DRAWER_RIGHT'
        };
        const viewparams = {
            modelid: this.modelId,
            utilServiceName: this.utilServiceName,
            appdeNamePath: ((_b = (_a = this.controlInstance) === null || _a === void 0 ? void 0 : _a.getPSAppDataEntity()) === null || _b === void 0 ? void 0 : _b.codeName) || 'app',
        };
        const dynamicProps = Object.assign({ customModel: this.customModelData }, Util.getViewProps(this.context, viewparams));
        const appdrawer = this.$appdrawer.openDrawer(view, dynamicProps);
        appdrawer.subscribe((result) => {
            if (Object.is(result.ret, 'OK')) {
                if ((result === null || result === void 0 ? void 0 : result.datas.length) > 0) {
                    for (const model of result.datas) {
                        model.modelData = this.getPortletInstance(model);
                    }
                    this.customModelData = [...result.datas];
                    this.initDynamicMountedMap();
                    this.dashboardType = 'custom';
                }
                else {
                    this.initStaticMountedMap();
                    this.dashboardType = "default";
                }
                this.$forceUpdate();
            }
        });
    }
    /**
     * 部件事件
     *
     * @param {string} controlname
     * @param {string} action
     * @param {*} data
     * @memberof KanbanControlBase
     */
    onCtrlEvent(controlname, action, data) {
        if (action == 'refreshAll') {
            this.viewState.next({
                tag: 'all-portlet',
                action: "refreshAll",
                data: data
            });
            this.ctrlEvent({ controlname: this.controlInstance.name, action: 'refreshAll', data: data });
        }
        else {
            super.onCtrlEvent(controlname, action, data);
        }
    }
}
