import { CodeListServiceBase, throttle, ModelTool, Util } from '@ibizstudio/runtime';
import { MainControlBase } from './main-control-base';
import { GlobalService } from '@ibizstudio/runtime';
import { AppCenterService, AppViewLogicService } from '../app-service';
/**
 * 多数据部件基类
 *
 * @export
 * @class MDControlBase
 * @extends {MainControlBase}
 */
export class MDControlBase extends MainControlBase {
    constructor() {
        super(...arguments);
        /**
         * 快速行为模型数据
         *
         * @protected
         * @type {[]}
         * @memberof MDControlBase
         */
        this.quickToolbarModels = [];
        /**
         * 批操作行为模型数据
         *
         * @protected
         * @type {[]}
         * @memberof MDControlBase
         */
        this.batchToolbarModels = [];
        /**
         * 选中行数据
         *
         * @type {any[]}
         * @memberof MDControlBase
         */
        this.selections = [];
        /**
         * 当前页
         *
         * @type {number}
         * @memberof MDControlBase
         */
        this.curPage = 1;
        /**
         * 多数据部件数据激活模式
         * 0 不激活
         * 1 单击激活
         * 2 双击激活
         *
         * @type {(number | 0 | 1 | 2)}
         * @memberof GridControlBase
         */
        this.mDCtrlActiveMode = 2;
        /**
         * 数据
         *
         * @type {any[]}
         * @memberof MDControlBase
         */
        this.items = [];
        /**
         * 是否支持分页
         *
         * @type {boolean}
         * @memberof MDControlBase
         */
        this.isEnablePagingBar = true;
        /**
         * 是否禁用排序
         *
         * @type {boolean}
         * @memberof MDControlBase
         */
        this.isNoSort = false;
        /**
         * 分页条数
         *
         * @type {number}
         * @memberof MDControlBase
         */
        this.limit = 20;
        /**
         * 总条数
         *
         * @type {number}
         * @memberof MDControlBase
         */
        this.totalRecord = 0;
        /**
         * 是否默认选中第一条数据
         *
         * @type {boolean}
         * @memberof MDControlBase
         */
        this.isSelectFirstDefault = false;
        /**
         * 排序方向
         *
         * @type {string}
         * @memberof MDControlBase
         */
        this.minorSortDir = "";
        /**
         * 排序字段
         *
         * @type {string}
         * @memberof MDControlBase
         */
        this.minorSortPSDEF = "";
        /**
         * 建立数据行为
         *
         * @readonly
         * @memberof MDControlBase
         */
        this.createAction = "";
        /**
         * 查询数据行为
         *
         * @readonly
         * @memberof MDControlBase
         */
        this.fetchAction = "";
        /**
         * 更新数据行为
         *
         * @readonly
         * @memberof MDControlBase
         */
        this.updateAction = "";
        /**
         * 删除数据行为
         *
         * @readonly
         * @memberof MDControlBase
         */
        this.removeAction = "";
        /**
         * 查询数据行为
         *
         * @readonly
         * @memberof MDControlBase
         */
        this.loadAction = "";
        /**
         * 获取草稿数据行为
         *
         * @readonly
         * @memberof MDControlBase
         */
        this.loaddraftAction = "";
        /**
         * 数据映射（数据项名称和UI名称的映射）
         *
         * @memberof MDControlBase
         */
        this.dataMap = new Map();
        /**
         * 分组模式
         *
         * @type {string}
         * @memberof MDControlBase
         */
        this.groupMode = '';
        /**
         * 是否开启分组
         *
         * @type {boolean}
         * @memberof MDControlBase
         */
        this.isEnableGroup = false;
        /**
         * 分组属性
         *
         * @type {string}
         * @memberof MDControlBase
         */
        this.groupField = '';
    }
    /**
     * 获取视图样式
     *
     * @readonly
     * @memberof MDControlBase
     */
    get viewStyle() {
        var _a, _b, _c, _d;
        const parentModel = (_b = (_a = this.controlInstance) === null || _a === void 0 ? void 0 : _a.getParentPSModelObject) === null || _b === void 0 ? void 0 : _b.call(_a);
        if (parentModel && parentModel.viewStyle) {
            return parentModel.viewStyle;
        }
        else {
            if (parentModel && parentModel.controlType) {
                return ((_d = (_c = parentModel.getParentPSModelObject) === null || _c === void 0 ? void 0 : _c.call(parentModel)) === null || _d === void 0 ? void 0 : _d.viewStyle) || 'DEFAULT';
            }
            return 'DEFAULT';
        }
    }
    /**
     * 监听静态参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof MDControlBase
     */
    onStaticPropsChange(newVal, oldVal) {
        this.isSingleSelect = newVal.isSingleSelect !== false;
        this.isSelectFirstDefault = newVal.isSelectFirstDefault === true;
        this.mDCtrlActiveMode = newVal.mDCtrlActiveMode;
        super.onStaticPropsChange(newVal, oldVal);
    }
    /**
     * 部件模型数据初始化
     *
     * @memberof MDControlBase
     */
    async ctrlModelInit(args) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12;
        await super.ctrlModelInit();
        const { name } = this.controlInstance;
        if (((_b = (_a = this.controlInstance) === null || _a === void 0 ? void 0 : _a.getPSAppDataEntity) === null || _b === void 0 ? void 0 : _b.call(_a)) && !(this.Environment && this.Environment.isPreviewMode)) {
            if (!((_d = (_c = this.controlInstance) === null || _c === void 0 ? void 0 : _c.getPSAppDataEntity()) === null || _d === void 0 ? void 0 : _d.isFill)) {
                await ((_e = this.controlInstance) === null || _e === void 0 ? void 0 : _e.getPSAppDataEntity().fill());
            }
            this.appEntityService = await new GlobalService().getService(this.controlInstance.getPSAppDataEntity().codeName, this.context);
        }
        this.loaddraftAction = ((_k = (_j = (_h = (_g = (_f = this.controlInstance) === null || _f === void 0 ? void 0 : _f.getGetDraftPSControlAction) === null || _g === void 0 ? void 0 : _g.call(_f)) === null || _h === void 0 ? void 0 : _h.getPSAppDEMethod) === null || _j === void 0 ? void 0 : _j.call(_h)) === null || _k === void 0 ? void 0 : _k.codeName) || "GetDraft";
        this.loadAction = ((_q = (_p = (_o = (_m = (_l = this.controlInstance) === null || _l === void 0 ? void 0 : _l.getGetPSControlAction) === null || _m === void 0 ? void 0 : _m.call(_l)) === null || _o === void 0 ? void 0 : _o.getPSAppDEMethod) === null || _p === void 0 ? void 0 : _p.call(_o)) === null || _q === void 0 ? void 0 : _q.codeName) || "Get";
        this.removeAction = ((_v = (_u = (_t = (_s = (_r = this.controlInstance) === null || _r === void 0 ? void 0 : _r.getRemovePSControlAction) === null || _s === void 0 ? void 0 : _s.call(_r)) === null || _t === void 0 ? void 0 : _t.getPSAppDEMethod) === null || _u === void 0 ? void 0 : _u.call(_t)) === null || _v === void 0 ? void 0 : _v.codeName) || "Remove";
        this.updateAction = ((_0 = (_z = (_y = (_x = (_w = this.controlInstance) === null || _w === void 0 ? void 0 : _w.getUpdatePSControlAction) === null || _x === void 0 ? void 0 : _x.call(_w)) === null || _y === void 0 ? void 0 : _y.getPSAppDEMethod) === null || _z === void 0 ? void 0 : _z.call(_y)) === null || _0 === void 0 ? void 0 : _0.codeName) || "Update";
        this.fetchAction = ((_5 = (_4 = (_3 = (_2 = (_1 = this.controlInstance) === null || _1 === void 0 ? void 0 : _1.getFetchPSControlAction) === null || _2 === void 0 ? void 0 : _2.call(_1)) === null || _3 === void 0 ? void 0 : _3.getPSAppDEMethod) === null || _4 === void 0 ? void 0 : _4.call(_3)) === null || _5 === void 0 ? void 0 : _5.codeName) || "FetchDefault";
        this.createAction = ((_10 = (_9 = (_8 = (_7 = (_6 = this.controlInstance) === null || _6 === void 0 ? void 0 : _6.getCreatePSControlAction) === null || _7 === void 0 ? void 0 : _7.call(_6)) === null || _8 === void 0 ? void 0 : _8.getPSAppDEMethod) === null || _9 === void 0 ? void 0 : _9.call(_8)) === null || _10 === void 0 ? void 0 : _10.codeName) || "Create";
        if ((_12 = (_11 = this.controlInstance) === null || _11 === void 0 ? void 0 : _11.getPSControls) === null || _12 === void 0 ? void 0 : _12.call(_11)) {
            this.quickToolbarInstance = ModelTool.findPSControlByName(`${name}_quicktoolbar`, this.controlInstance.getPSControls());
            this.batchToolbarInstance = ModelTool.findPSControlByName(`${name}_batchtoolbar`, this.controlInstance.getPSControls());
        }
        this.initToolBarModels();
        this.initDataMap();
        this.initGroupOptions();
    }
    /**
     * 初始化工具栏模型
     *
     * @memberof MDControlBase
     */
    initToolBarModels() {
        var _a, _b;
        const getModelData = (_item) => {
            var _a, _b, _c, _d;
            const item = _item;
            const uiAction = item.getPSUIAction ? item === null || item === void 0 ? void 0 : item.getPSUIAction() : null;
            return {
                name: item.name,
                showCaption: item.showCaption,
                showIcon: item.showIcon,
                tooltip: this.$tl((_a = item.getTooltipPSLanguageRes()) === null || _a === void 0 ? void 0 : _a.lanResTag, item.tooltip),
                iconcls: (_b = item.getPSSysImage()) === null || _b === void 0 ? void 0 : _b.cssClass,
                icon: (_c = item.getPSSysImage()) === null || _c === void 0 ? void 0 : _c.imagePath,
                actiontarget: item.uIActionTarget,
                caption: this.$tl((_d = item.getCapPSLanguageRes()) === null || _d === void 0 ? void 0 : _d.lanResTag, item.caption),
                disabled: false,
                itemType: item.itemType,
                visabled: true,
                noprivdisplaymode: uiAction === null || uiAction === void 0 ? void 0 : uiAction.noPrivDisplayMode,
                actionLevel: _item.actionLevel,
                dataaccaction: '',
                uiaction: {
                    tag: (uiAction === null || uiAction === void 0 ? void 0 : uiAction.uIActionTag) ? uiAction.uIActionTag : (uiAction === null || uiAction === void 0 ? void 0 : uiAction.id) ? uiAction.id : '',
                    target: uiAction === null || uiAction === void 0 ? void 0 : uiAction.actionTarget,
                },
            };
        };
        if (this.quickToolbarInstance) {
            let targetViewToolbarItems = [];
            (_a = this.quickToolbarInstance.getPSDEToolbarItems()) === null || _a === void 0 ? void 0 : _a.forEach((item) => {
                targetViewToolbarItems.push(getModelData(item));
            });
            this.quickToolbarModels = targetViewToolbarItems;
        }
        if (this.batchToolbarInstance) {
            let targetViewToolbarItems = [];
            (_b = this.batchToolbarInstance.getPSDEToolbarItems()) === null || _b === void 0 ? void 0 : _b.forEach((item) => {
                targetViewToolbarItems.push(getModelData(item));
            });
            this.batchToolbarModels = targetViewToolbarItems;
        }
    }
    /**
     * 多数据部件初始化
     *
     * @memberof MDControlBase
     */
    ctrlInit() {
        super.ctrlInit();
        let _this = this;
        // 全局刷新通知
        if (AppCenterService.getMessageCenter()) {
            _this.appStateEvent = AppCenterService.getMessageCenter().subscribe(({ name, action, data }) => {
                if (!_this.appDeCodeName || !Object.is(name, _this.appDeCodeName)) {
                    return;
                }
                if (Object.is(action, 'appRefresh')) {
                    _this.refresh(data);
                }
            });
        }
        _this.codeListService = new CodeListServiceBase({ $store: _this.$store });
    }
    /**
     * 执行destroyed后的逻辑
     *
     * @memberof MDControlBase
     */
    ctrlDestroyed() {
        super.ctrlDestroyed();
        if (this.appStateEvent) {
            this.appStateEvent.unsubscribe();
        }
    }
    /**
     * 部件工具栏点击
     *
     * @param ctrl 部件
     * @param data 工具栏回传数据
     * @param $event 事件源对象
     * @memberof MDControlBase
     */
    handleItemClick(ctrl, data, $event) {
        AppViewLogicService.getInstance().executeViewLogic(this.getViewLogicTag(this.controlInstance.name, ctrl, data.tag), $event, this, undefined, this.controlInstance.getPSAppViewLogics());
    }
    /**
     * 获取多项数据
     *
     * @returns {any[]}
     * @memberof MDControlBase
     */
    getDatas() {
        return this.selections;
    }
    /**
     * 获取单项数据
     *
     * @returns {*}
     * @memberof MDControlBase
     */
    getData() {
        return this.selections[0];
    }
    /**
      * 绘制加载数据提示信息
      *
      * @return {*}
      * @memberof MDControlBase
      */
    renderLoadDataTip() {
        return <div class="load-data-tip">
            <span class="tip-text">{this.$t('app.warn.load')}</span>
        </div>;
    }
    /**
     * 绘制无数据提示信息
     *
     * @return {*}
     * @memberof MDControlBase
     */
    renderEmptyDataTip() {
        return <div class="empty-data-tip">
            <span class="tip-text">{this.$t('app.warn.nofind')}</span>
            {this.renderQuickToolbar()}
        </div>;
    }
    /**
     * 绘制快速工具栏
     *
     * @return {*}
     * @memberof MDControlBase
     */
    renderQuickToolbar() {
        return <span class='quick-toolbar'>
            <view-toolbar toolbarModels={this.quickToolbarModels} on-item-click={(data, $event) => {
                throttle(this.handleItemClick, ['quicktoolbar', data, $event], this);
            }}></view-toolbar>
        </span>;
    }
    /**
     * 绘制批处理工具栏
     *
     * @return {*}
     * @memberof MDControlBase
     */
    renderBatchToolbar() {
        for (let index = 0; index < this.batchToolbarModels.length; index++) {
            this.batchToolbarModels[index].disabled = this.selections.length <= 0;
        }
        return <span v-show={this.selections.length > 0 || this.viewStyle == 'DEFAULT'} class="batch-toolbar">
            <view-toolbar toolbarModels={this.batchToolbarModels} on-item-click={(data, $event) => {
                throttle(this.handleItemClick, ['batchtoolbar', data, $event], this);
            }}></view-toolbar>
        </span>;
    }
    /**
     * 初始化数据映射
     *
     * @memberof MDControlBase
     */
    initDataMap() { }
    /**
     * 将数据项数据转化为UI数据
     *
     * @param data 源数据
     */
    dataItemTransition(data) {
        let _data = Util.deepCopy(data);
        if (data.length > 0) {
            data.forEach((item, index) => {
                for (const key in item) {
                    const itemUI = this.dataMap.get(key);
                    if (itemUI && !Object.is(itemUI.itemUIName, key)) {
                        delete _data[index][key];
                        Object.assign(_data[index], { [itemUI.itemUIName]: item[key] });
                    }
                    ;
                }
                ;
            });
        }
        ;
        return _data;
    }
    /**
     * 将项UI数据转为数据项数据
     *
     * @param data 多数据部件数据
     */
    itemUIDataTransition(data) {
        let _data = Util.deepCopy(data);
        let dataItems = [];
        if (_data) {
            for (const [dataItemName, itemUI] of this.dataMap) {
                if (!Object.is(dataItemName, itemUI.itemUIName)) {
                    dataItems.push(dataItemName);
                }
                ;
            }
            ;
            data.forEach((item, index) => {
                if (dataItems.length > 0) {
                    for (const key in item) {
                        dataItems.forEach((dataItemName) => {
                            const itemUI = this.dataMap.get(dataItemName);
                            if (itemUI && Object.is(itemUI.itemUIName, key)) {
                                delete _data[index][key];
                                Object.assign(_data[index], { [dataItemName]: item[key] });
                            }
                        });
                    }
                    ;
                }
                ;
            });
        }
        ;
        return _data;
    }
    /**
     * 初始化分组配置
     *
     * @memberof MDControlBase
     */
    initGroupOptions() {
        var _a, _b, _c, _d, _e;
        this.isEnableGroup = (this.controlInstance.enableGroup && ((_b = (_a = this.controlInstance).getGroupPSAppDEField) === null || _b === void 0 ? void 0 : _b.call(_a))) ? true : false;
        if (this.isEnableGroup) {
            this.groupMode = this.controlInstance.groupMode;
            this.groupField = (_c = this.controlInstance.getGroupPSAppDEField().codeName) === null || _c === void 0 ? void 0 : _c.toLowerCase();
            this.groupCodeList = (_e = (_d = this.controlInstance).getGroupPSCodeList) === null || _e === void 0 ? void 0 : _e.call(_d);
        }
    }
    /**
     * 分组
     *
     * @memberof MDControlBase
     */
    group() {
        if (Object.is(this.groupMode, "AUTO")) {
            this.drawGroup();
        }
        else if (Object.is(this.groupMode, "CODELIST")) {
            this.drawCodelistGroup();
        }
    }
    /**
     * 自动分组
     *
     * @memberof MDControlBase
     */
    drawGroup() { }
    /**
     * 代码表分组
     *
     * @memberof MDControlBase
     */
    drawCodelistGroup() { }
}
