import { CodeListServiceBase, throttle, LogUtil, ModelTool, Util } from '@ibizstudio/runtime';
import { AppLayoutService } from '../app-service';
import { AppGlobalService } from '../app-service/logic-service/app-global-action-service';
import { MainViewBase } from './mainview-base';
/**
 * 多数据视图基类
 *
 * @export
 * @class MDViewBase
 * @extends {MainViewBase}
 * @implements {MDViewInterface}
 */
export class MDViewBase extends MainViewBase {
    constructor() {
        super(...arguments);
        /**
         * 快速搜索值
         *
         * @type {string}
         * @memberof MDViewBase
         */
        this.query = '';
        /**
         * 是否展开搜索表单（接收参数）
         *
         * @type {boolean}
         * @memberof MDViewBase
         */
        this.expandSearchForm = false;
        /**
         * 实际是否展开搜索表单
         *
         * @type {boolean}
         * @memberof MDViewBase
         */
        this.isExpandSearchForm = false;
        /**
         * 快速分组是否有抛值
         *
         * @memberof MDViewBase
         */
        this.isEmitQuickGroupValue = false;
        /**
         * 快速分组模型数据
         *
         * @memberof MDViewBase
         */
        this.quickGroupModel = [];
        /**
         * 快速分组代码表
         *
         * @type {boolean}
         * @memberof MDViewBase
         */
        this.quickGroupCodeList = null;
        /**
         * 可搜索字段名称
         *
         * @type {(string)}
         * @memberof MDViewBase
         */
        this.placeholder = '';
        /**
         * 搜索栏显示
         *
         * @type {boolean}
         * @memberof MDViewBase
         */
        this.visible = false;
        /**
         * popover层级
         *
         * @type {number}
         * @memberof MDViewBase
         */
        this.zIndex = 0;
        /**
         * 唯一标识
         *
         * @type {string}
         * @memberof MDViewBase
         */
        this.uuid = Util.createUUID();
    }
    /**
     * 加载快速分组模型
     *
     * @memberof MDViewBase
     */
    async loadQuickGroupModel() {
        var _a, _b;
        try {
            await ((_b = (_a = this.quickGroupCodeList) === null || _a === void 0 ? void 0 : _a.fill) === null || _b === void 0 ? void 0 : _b.call(_a));
            if (!(this.quickGroupCodeList && this.quickGroupCodeList.codeName)) {
                return;
            }
            let res = await this.codeListService.getDataItems({
                tag: this.quickGroupCodeList.codeName,
                type: this.quickGroupCodeList.codeListType,
                data: this.quickGroupCodeList,
                context: this.context,
            });
            this.quickGroupModel = this.handleDynamicData(JSON.parse(JSON.stringify(res)));
        }
        catch (error) {
            LogUtil.log(`----${this.quickGroupCodeList.codeName}----${this.$t('app.commonwords.codenotexist')}`);
        }
    }
    /**
     * 处理快速分组模型动态数据部分(%xxx%)
     *
     * @memberof MDViewBase
     */
    handleDynamicData(inputArray) {
        if (inputArray.length > 0) {
            const defaultSelect = this.getQuickGroupDefaultSelect();
            if (defaultSelect) {
                let select = inputArray.find((item) => {
                    return item.value === defaultSelect.value;
                });
                if (select)
                    select.default = true;
            }
            inputArray.forEach((item) => {
                if (item.data && Object.keys(item.data).length > 0) {
                    Object.keys(item.data).forEach((name) => {
                        let value = item.data[name];
                        if (value && typeof value == 'string' && value.startsWith('%') && value.endsWith('%')) {
                            const key = value.substring(1, value.length - 1).toLowerCase();
                            if (this.context[key]) {
                                value = this.context[key];
                            }
                            else if (this.viewparams[key]) {
                                value = this.viewparams[key];
                            }
                        }
                        item.data[name] = value;
                    });
                }
            });
        }
        return inputArray;
    }
    /**
     * 获取快速分组默认选中项
     *
     * @memberof MDViewBase
     */
    getQuickGroupDefaultSelect() {
        var _a;
        let defaultSelect = null;
        const codeItems = this.quickGroupCodeList.getPSCodeItems() || [];
        if (codeItems.length > 0) {
            for (const item of codeItems) {
                const childItems = ((_a = item.getPSCodeItems) === null || _a === void 0 ? void 0 : _a.call(item)) || [];
                if (childItems.length > 0) {
                    defaultSelect = childItems.find((_item) => {
                        return _item.default;
                    });
                }
                if (item.default || defaultSelect) {
                    defaultSelect = item;
                    break;
                }
            }
        }
        return defaultSelect;
    }
    /**
     * 快速分组值变化
     *
     * @param {*} $event 事件源
     * @memberof MDViewBase
     */
    quickGroupValueChange($event) {
        if ($event) {
            this.quickGroupData = $event.data;
            if (this.isEmitQuickGroupValue) {
                this.onSearch($event);
            }
        }
        this.isEmitQuickGroupValue = true;
    }
    /**
     * 快速搜索
     *
     * @param {*} $event
     * @memberof MDViewBase
     */
    onSearch($event) { }
    /**
     * 初始化日历视图实例
     *
     * @param opts
     * @memberof MDViewBase
     */
    async viewModelInit() {
        var _a, _b, _c;
        await super.viewModelInit();
        this.searchFormInstance = ModelTool.findPSControlByName('searchform', this.viewInstance.getPSControls() || []);
        this.quickSearchFormInstance = ModelTool.findPSControlByName('quicksearchform', this.viewInstance.getPSControls() || []);
        this.searchBarInstance = ModelTool.findPSControlByType('SEARCHBAR', this.viewInstance.getPSControls() || []);
        this.isEnableQuickGroup = (_a = this.viewInstance) === null || _a === void 0 ? void 0 : _a.enableQuickGroup;
        this.quickGroupCodeList = (_c = (_b = this.viewInstance) === null || _b === void 0 ? void 0 : _b.getQuickGroupPSCodeList) === null || _c === void 0 ? void 0 : _c.call(_b);
        let _this = this;
        if (this.isEnableQuickGroup) {
            this.codeListService = new CodeListServiceBase({ $store: _this.$store });
            await this.loadQuickGroupModel();
        }
    }
    /**
     *  多数据视图初始化
     *
     * @memberof MDViewBase
     */
    viewInit() {
        var _a;
        super.viewInit();
        // 初始化属性值
        this.query = '';
        this.expandSearchForm = ((_a = this.viewInstance) === null || _a === void 0 ? void 0 : _a.expandSearchForm) ? true : false;
        this.initQuickSearchPlaceholder();
    }
    /**
     * 视图挂载
     *
     * @memberof MDViewBase
     */
    viewMounted() {
        super.viewMounted();
        this.handleDefaultExpandSearchForm();
        this.initPopoverZIndex();
        //点击搜索表单区域外
        this.onSearchFormClickOutSide = this.onSearchFormClickOutSide.bind(this);
        this.keyDown = this.keyDown.bind(this);
        window.addEventListener('click', this.onSearchFormClickOutSide);
        window.addEventListener('keydown', this.keyDown);
    }
    /**
     * 视图销毁
     *
     * @memberof MDViewBase
     */
    viewDestroyed() {
        super.viewDestroyed();
        window.removeEventListener('click', this.onSearchFormClickOutSide);
        window.removeEventListener('keydown', this.keyDown);
        const searchFormPopover = this.$el.querySelector(`.search-from-popover-${this.uuid}`);
        if (searchFormPopover) {
            this.$store.commit('downZIndex');
        }
    }
    /**
     * 初始化气泡打开层数
     *
     * @memberof MDViewBase
     */
    initPopoverZIndex() {
        const searchFormPopover = this.$el.querySelector(`.search-from-popover-${this.uuid}`);
        if (searchFormPopover) {
            this.$store.commit('upZIndex');
            this.zIndex = this.$store.getters.getZIndex();
        }
    }
    /**
     * 显示气泡
     *
     * @memberof MDViewBase
     */
    showPopover() {
        setTimeout(() => {
            const searchForm = document.body.getElementsByClassName(`search-from-popover-${this.uuid}`)[0];
            if (searchForm) {
                searchForm.style.zIndex = this.zIndex;
            }
        });
    }
    /**
     * 点击外部区域关闭搜索表单
     *
     * @param {*} $event
     * @memberof MDViewBase
     */
    onSearchFormClickOutSide($event) {
        var _a;
        const searchForm = document.body.querySelector(`.search-from-popover-${this.uuid} .app-search-form`);
        if (searchForm) {
            const modal = document.body.getElementsByClassName('app-modal')[0];
            if (!modal && ((_a = $event.target) === null || _a === void 0 ? void 0 : _a.className.indexOf('ivu-icon-ios-funnel')) == -1) {
                this.visible = false;
            }
        }
    }
    /**
     * 监听按键事件ESC
     *
     * @memberof MDViewBase
     */
    keyDown($event) {
        const searchForm = document.body.querySelector(`.search-from-popover-${this.uuid} .app-search-form`);
        if (searchForm && ($event.keyCode == 27 || $event.keyCode == 96)) {
            this.visible = false;
        }
    }
    /**
     * 处理默认展开搜索表单
     *
     * @memberof MDViewBase
     */
    handleDefaultExpandSearchForm() {
        var _a, _b;
        //  默认展开搜索表单
        if (this.expandSearchForm) {
            //  搜索表单以弹框展示
            if (((_a = this.viewInstance) === null || _a === void 0 ? void 0 : _a.viewStyle) == 'DEFAULT' && ((_b = this.viewInstance) === null || _b === void 0 ? void 0 : _b.enableQuickSearch)) {
                this.$nextTick(() => {
                    var _a;
                    const element = (_a = this.$refs['filterButton']) === null || _a === void 0 ? void 0 : _a.$el;
                    if (element) {
                        element.click();
                    }
                });
            }
            else {
                this.isExpandSearchForm = this.expandSearchForm;
            }
        }
    }
    /**
     *  初始化快速搜索栏空白填充内容
     *
     * @memberof MDViewBase
     */
    initQuickSearchPlaceholder() {
        var _a;
        const quickSearchFields = ((_a = this.viewInstance.getPSAppDataEntity()) === null || _a === void 0 ? void 0 : _a.getQuickSearchPSAppDEFields()) || [];
        if (quickSearchFields.length > 0) {
            quickSearchFields.forEach((field, index) => {
                var _a, _b;
                const _field = (_a = this.viewInstance.getPSAppDataEntity()) === null || _a === void 0 ? void 0 : _a.findPSAppDEField(field.codeName);
                if (_field) {
                    this.placeholder += this.$tl((_b = _field.getLNPSLanguageRes()) === null || _b === void 0 ? void 0 : _b.lanResTag, _field.logicName) + (index === quickSearchFields.length - 1 ? '' : ', ');
                }
            });
        }
    }
    /**
     * 快速搜索栏值变化
     *
     * @memberof MDViewBase
     */
    quickFormValueChange($event) {
        this.quickFormData = $event;
        this.onSearch($event);
    }
    /**
     * 渲染快速分组
     *
     * @memberof MDViewBase
     */
    renderQuickGroup() {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        if (!((_a = this.viewInstance) === null || _a === void 0 ? void 0 : _a.enableQuickGroup)) {
            return;
        }
        let counterService;
        if ((_d = (_c = (_b = this.viewInstance) === null || _b === void 0 ? void 0 : _b.getPSAppCounterRef) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.id) {
            counterService = (_h = Util.findElementByField(this.counterServiceArray, 'id', (_g = (_f = (_e = this.viewInstance) === null || _e === void 0 ? void 0 : _e.getPSAppCounterRef) === null || _f === void 0 ? void 0 : _f.call(_e)) === null || _g === void 0 ? void 0 : _g.id)) === null || _h === void 0 ? void 0 : _h.service;
        }
        return (<div class='quick-group-container' slot='quickGroupSearch'>
        <app-quick-group items={this.quickGroupModel} on-valuechange={this.quickGroupValueChange.bind(this)} counterService={counterService}></app-quick-group>
      </div>);
    }
    /**
     * 渲染快速搜索
     *
     * @memberof MDViewBase
     */
    renderQuickSearch() {
        var _a, _b;
        if (!((_a = this.viewInstance) === null || _a === void 0 ? void 0 : _a.enableQuickSearch)) {
            return;
        }
        if (((_b = this.viewInstance) === null || _b === void 0 ? void 0 : _b.viewStyle) == 'DEFAULT') {
            return this.renderDefaultQuickSearch();
        }
        else {
            return this.renderStyle2QuickSearch();
        }
    }
    /**
     * 渲染快速搜索(DEFAULT)
     *
     * @return {*}
     * @memberof MDViewBase
     */
    renderDefaultQuickSearch() {
        var _a, _b, _c;
        const barFilters = ((_a = this.searchBarInstance) === null || _a === void 0 ? void 0 : _a.getPSSearchBarFilters()) || [];
        const searchformItem = ((_b = this.searchFormInstance) === null || _b === void 0 ? void 0 : _b.getPSDEFormItems()) || [];
        let enableFilter = (((_c = this.viewInstance) === null || _c === void 0 ? void 0 : _c.enableFilter) === true && barFilters.length > 0) || searchformItem.length > 0;
        const popoverClass = this.searchFormInstance ? 'searchform-popover' : this.searchBarInstance ? 'searchbar-popover' : '';
        return (<template slot='quickSearch'>
        <i-input class={{ 'app-quick-search': true, 'width-filter': enableFilter }} style='max-width: 400px;margin-top:4px;padding-left: 24px' search on-on-search={($event) => this.onSearch($event)} v-model={this.query} placeholder={this.placeholder}/>
        {<el-popover placement='bottom' popper-class={`${popoverClass} search-from-popover-${this.uuid}`} trigger='manual' visible-arrow={false} on-show={() => this.showPopover()} on-hide={() => (this.isExpandSearchForm = !this.isExpandSearchForm)} v-model={this.visible}>
            <i-button slot='reference' ref='filterButton' class={{ filter: true, 'is-expand': this.isExpandSearchForm, 'hidden-searchbtn': !enableFilter }} icon='ios-funnel' on-click={(e) => {
                    setTimeout(() => {
                        this.visible = !this.visible;
                        if (!this.isExpandSearchForm) {
                            throttle(() => AppGlobalService.getInstance().executeGlobalAction('ToggleFilter', undefined, undefined, undefined, e, undefined, this, undefined), [], this);
                        }
                    });
                }}/>
            {popoverClass && popoverClass != '' ? (popoverClass == 'searchform-popover' ? this.renderSearchForm() : this.renderSearchBar()) : null}
          </el-popover>}
      </template>);
    }
    /**
     * 渲染快速搜索(STYLE2)
     *
     * @return {*}
     * @memberof MDViewBase
     */
    renderStyle2QuickSearch() {
        return (<i-input slot='quickSearch' className='app-quick-search' style='max-width: 400px;margin-top:6px;padding-left: 24px' search enter-button on-on-search={($event) => this.onSearch($event)} v-model={this.query} placeholder={this.placeholder}/>);
    }
    /**
     * 计算目标部件所需参数
     *
     * @param {string} [controlType]
     * @returns
     * @memberof GridViewBase
     */
    computeTargetCtrlData(controlInstance) {
        const { targetCtrlName, targetCtrlParam, targetCtrlEvent } = super.computeTargetCtrlData(controlInstance);
        if (controlInstance.controlType == 'SEARCHFORM') {
            Object.assign(targetCtrlParam.dynamicProps, {
                isExpandSearchForm: this.isExpandSearchForm,
            });
        }
        Object.assign(targetCtrlParam.staticProps, {
            mDCtrlActiveMode: this.viewInstance.mDCtrlActiveMode,
        });
        return { targetCtrlName: targetCtrlName, targetCtrlParam: targetCtrlParam, targetCtrlEvent: targetCtrlEvent };
    }
    /**
     * 渲染搜索表单
     *
     * @memberof MDViewBase
     */
    renderSearchForm() {
        var _a, _b, _c, _d;
        if (!this.searchFormInstance) {
            return;
        }
        let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.searchFormInstance);
        if (((_a = this.viewInstance) === null || _a === void 0 ? void 0 : _a.viewStyle) == 'DEFAULT' && ((_b = this.viewInstance) === null || _b === void 0 ? void 0 : _b.enableQuickSearch)) {
            return this.$createElement(targetCtrlName, { props: targetCtrlParam, ref: (_c = this.searchFormInstance) === null || _c === void 0 ? void 0 : _c.name, on: targetCtrlEvent });
        }
        else {
            return this.$createElement(targetCtrlName, { slot: 'searchForm', props: targetCtrlParam, ref: (_d = this.searchFormInstance) === null || _d === void 0 ? void 0 : _d.name, on: targetCtrlEvent });
        }
    }
    /**
     * 渲染快速搜索表单
     *
     * @memberof MDViewBase
     */
    renderQuickSearchForm() {
        var _a;
        if (!this.quickSearchFormInstance) {
            return;
        }
        let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.quickSearchFormInstance);
        return this.$createElement(targetCtrlName, { slot: 'quickSearchForm', props: targetCtrlParam, ref: (_a = this.quickSearchFormInstance) === null || _a === void 0 ? void 0 : _a.name, on: targetCtrlEvent });
    }
    /**
     * 渲染搜索栏
     *
     * @memberof MDViewBase
     */
    renderSearchBar() {
        var _a, _b, _c, _d;
        if (!this.searchBarInstance) {
            return;
        }
        let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.searchBarInstance);
        Object.assign(targetCtrlParam.dynamicProps, {
            isExpandSearchForm: this.isExpandSearchForm,
        });
        if (((_a = this.viewInstance) === null || _a === void 0 ? void 0 : _a.viewStyle) == 'DEFAULT' && ((_b = this.viewInstance) === null || _b === void 0 ? void 0 : _b.enableQuickSearch)) {
            return this.$createElement(targetCtrlName, { props: targetCtrlParam, ref: (_c = this.searchBarInstance) === null || _c === void 0 ? void 0 : _c.name, on: targetCtrlEvent });
        }
        else {
            return this.$createElement(targetCtrlName, { slot: 'searchBar', props: targetCtrlParam, ref: (_d = this.searchBarInstance) === null || _d === void 0 ? void 0 : _d.name, on: targetCtrlEvent });
        }
    }
    render(h) {
        var _a, _b, _c, _d;
        if (!this.viewIsLoaded) {
            return null;
        }
        const targetViewLayoutComponent = AppLayoutService.getLayoutComponent(`${(_a = this.viewInstance) === null || _a === void 0 ? void 0 : _a.viewType}-${(_b = this.viewInstance) === null || _b === void 0 ? void 0 : _b.viewStyle}`);
        return h(targetViewLayoutComponent, {
            props: { viewInstance: this.viewInstance, model: this.model, modelService: this.modelService, viewparams: this.viewparams, context: this.context },
        }, [
            this.renderTopMessage(),
            this.renderToolBar(),
            this.renderQuickGroup(),
            this.renderQuickSearch(),
            this.renderBodyMessage(),
            !(((_c = this.viewInstance) === null || _c === void 0 ? void 0 : _c.viewStyle) == 'DEFAULT' && ((_d = this.viewInstance) === null || _d === void 0 ? void 0 : _d.enableQuickSearch)) ? [this.renderSearchForm(), this.renderSearchBar()] : null,
            this.renderMainContent(),
            this.renderBottomMessage(),
        ]);
    }
    /**
     * 部件事件
     * @param ctrl 部件
     * @param action  行为
     * @param data 数据
     *
     * @memberof MDViewBase
     */
    onCtrlEvent(controlname, action, data) {
        super.onCtrlEvent(controlname, action, data);
        if (Object.is(controlname, 'quicksearchform') && Object.is(action, 'valuechange')) {
            this.quickFormValueChange(data);
        }
    }
}
