import { WFDynaExpGridViewEngine, Util, ModelTool, throttle } from '@ibizstudio/runtime';
import { GlobalService } from '@ibizstudio/runtime';
import { AppGlobalService } from '../app-service/logic-service/app-global-action-service';
import { MainViewBase } from './mainview-base';
/**
 * 工作流动态导航表格视图基类
 *
 * @export
 * @class WfDynaExpGridViewBase
 * @extends {MainViewBase}
 * @implements {WFDynaExpGridInterface}
 */
export class WfDynaExpGridViewBase extends MainViewBase {
    constructor() {
        super(...arguments);
        /**
         * 视图引擎
         *
         * @public
         * @type {Engine}
         * @memberof WfDynaExpGridViewBase
         */
        this.engine = new WFDynaExpGridViewEngine();
        /**
         * 可搜索字段名称
         *
         * @type {(string)}
         * @memberof WfDynaExpGridViewBase
         */
        this.placeholder = "";
        /**
         * 分割宽度
         *
         * @type {number}
         * @memberof WfDynaExpGridViewBase
         */
        this.split = 0.2;
        /**
         * 视图引用数据
         *
         * @memberof WfDynaExpGridViewBase
         */
        this.viewRefData = {};
        /**
         * 树导航栏数据
         *
         * @type {any}
         * @memberof WfDynaExpGridViewBase
         */
        this.wfStepModel = [{ userTaskName: '我的处理', userTaskId: "all", children: [] }];
        /**
         * 快速搜索值
         *
         * @type {string}
         * @memberof WfDynaExpGridViewBase
         */
        this.query = '';
        /**
         * 是否展开搜索表单（接收参数）
         *
         * @type {boolean}
         * @memberof WfDynaExpGridViewBase
         */
        this.expandSearchForm = false;
        /**
         * 是否展开搜索表单
         *
         * @type {any}
         * @memberof  WfDynaExpGridViewBase
         */
        this.isExpandSearchForm = false;
        /**
         * 是否单选
         *
         * @type {any}
         * @memberof  WfDynaExpGridViewBase
         */
        this.isSingleSelect = false;
        /**
         * 工具栏模型数据
         *
         * @memberof WfDynaExpGridViewBase
         */
        this.linkModel = [];
        /**
         * 左侧树的默认配置
         *
         * @type {any}
         * @memberof  WfDynaExpGridViewBase
         */
        this.defaultProps = {
            children: 'children',
            label: 'userTaskName'
        };
    }
    /**
     * 引擎初始化
     *
     * @public
     * @memberof WfDynaExpGridViewBase
     */
    engineInit() {
        var _a;
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        let engineOpts = ({
            view: this,
            parentContainer: this.$parent,
            p2k: '0',
            grid: this.$refs[this.gridInstance.name].ctrl,
            opendata: (args, fullargs, params, $event, xData) => {
                this.opendata(args, fullargs, params, $event, xData);
            },
            newdata: (args, fullargs, params, $event, xData) => {
                this.newdata(args, fullargs, params, $event, xData);
            },
            keyPSDEField: this.appDeCodeName.toLowerCase(),
            majorPSDEField: this.appDeMajorFieldName.toLowerCase(),
            isLoadDefault: this.viewInstance.loadDefault,
        });
        if ((_a = this.searchFormInstance) === null || _a === void 0 ? void 0 : _a.name) {
            engineOpts.searchform = (this.$refs[this.searchFormInstance.name].ctrl);
        }
        this.engine.init(engineOpts);
    }
    /**
     * 初始化分页导航视图实例
     *
     * @memberof WfDynaExpGridViewBase
     */
    async viewModelInit() {
        await super.viewModelInit();
        this.gridInstance = ModelTool.findPSControlByName('grid', this.viewInstance.getPSControls());
        this.searchFormInstance = ModelTool.findPSControlByName('searchform', this.viewInstance.getPSControls());
        this.appEntityService = await new GlobalService().getService(this.appDeCodeName, this.context);
        this.viewRefData = await ModelTool.loadedAppViewRef(this.viewInstance);
    }
    /**
     * @description 视图初始化
     * @memberof WfDynaExpGridViewBase
     */
    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 WfDynaExpGridViewBase
     */
    viewMounted() {
        super.viewMounted();
        this.handleDefaultExpandSearchForm();
    }
    /**
     * 处理默认展开搜索表单
     *
     * @memberof WfDynaExpGridViewBase
     */
    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(() => {
                    const element = document.querySelector('button.filter');
                    debugger;
                    if (element) {
                        element.click();
                    }
                });
            }
            else {
                this.isExpandSearchForm = this.expandSearchForm;
            }
        }
    }
    /**
     *  初始化快速搜索栏空白填充内容
     *
     * @memberof WfDynaExpGridViewBase
     */
    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 WfDynaExpGridViewBase
     */
    renderToolBar() {
        return (<span slot='toolbar'>
            {this.linkModel.map((linkItem, index) => {
                return <tooltip transfer={true} max-width={600} key={linkItem.codeName}>
                        <i-button disabled={linkItem.disabled} on-click={($event) => { throttle(this.dynamic_toolbar_click, [linkItem, $event], this); }} loading={this.viewLoadingService.isLoading}>
                            <span class='caption'>{linkItem.sequenceFlowName}</span>
                        </i-button>
                        <div slot='content'>{linkItem.sequenceFlowName}</div>
                    </tooltip>;
            })}
        </span>);
    }
    /**
     * 渲染视图主题内容
     *
     * @memberof WfDynaExpGridViewBase
     */
    renderMainContent() {
        var _a, _b;
        const { codeName } = this.viewInstance;
        return <split id={codeName.toLowerCase()} v-model={this.split} mode="horizontal">
            <div slot='left'>
                <el-tree ref="tree" data={this.wfStepModel} default-expanded-keys={["all"]} node-key="userTaskId" highlight-current={true} props={this.defaultProps} on-node-click={(...params) => throttle(this.handleNodeClick, params, this)} scopedSlots={{
                default: ({ node, data }) => {
                    var _a;
                    let iconClass = "tree-node-icon";
                    iconClass += ((_a = data === null || data === void 0 ? void 0 : data.children) === null || _a === void 0 ? void 0 : _a.length) > 0 ? " fa fa-folder-open" : " fa fa-sitemap";
                    return <span class="custom-tree-node">
                            <i class={iconClass}/>
                            <span class="tree-node-label">{data.userTaskName}</span>
                            <span class="tree-node-count"><badge count={data.cnt}></badge></span>
                        </span>;
                }
            }}>
                </el-tree>
            </div>
            <div slot="right">
                <div class="content-container">
                    {!(((_a = this.viewInstance) === null || _a === void 0 ? void 0 : _a.viewStyle) == "DEFAULT" && ((_b = this.viewInstance) === null || _b === void 0 ? void 0 : _b.enableQuickSearch)) ? this.renderSearchForm() : null}
                    {this.rednderGrid()}
                </div>
            </div>
        </split>;
    }
    /**
     * 绘制搜索表单
     *
     * @returns
     * @memberof WfDynaExpGridViewBase
     */
    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 });
        }
    }
    /**
     * 绘制表格
     *
     * @returns
     * @memberof WfDynaExpGridViewBase
     */
    rednderGrid() {
        if (!this.gridInstance) {
            return;
        }
        let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.gridInstance);
        if (!targetCtrlParam.dynamicProps.viewparams.hasOwnProperty('srfwf')) {
            targetCtrlParam.dynamicProps.viewparams.srfwf = 'todo';
        }
        return this.$createElement(targetCtrlName, { props: targetCtrlParam, ref: this.gridInstance.name, on: targetCtrlEvent });
    }
    /**
     * 计算目标部件所需参数
     *
     * @param {string} [controlType]
     * @returns
     * @memberof WfDynaExpGridViewBase
     */
    computeTargetCtrlData(controlInstance) {
        const { targetCtrlName, targetCtrlParam, targetCtrlEvent } = super.computeTargetCtrlData(controlInstance);
        if (controlInstance.controlType == 'SEARCHFORM') {
            Object.assign(targetCtrlParam.dynamicProps, {
                isExpandSearchForm: this.isExpandSearchForm
            });
        }
        else {
            Object.assign(targetCtrlParam.staticProps, {
                opendata: this.opendata,
                newdata: this.newdata,
            });
        }
        return { targetCtrlName: targetCtrlName, targetCtrlParam: targetCtrlParam, targetCtrlEvent: targetCtrlEvent };
    }
    /**
     * 获取树导航栏数据
     *
     * @memberof  WfDynaExpGridViewBase
     */
    getWFStepModel() {
        return new Promise((resolve, reject) => {
            this.appEntityService.WFGetWFStep(Util.deepCopy(this.context), Util.deepCopy(this.viewparams)).then((response) => {
                if (response && response.status === 200) {
                    this.wfStepModel[0].children = [...response.data];
                    if (!this.curSelectedNode) {
                        this.curSelectedNode = this.wfStepModel[0];
                    }
                    else {
                        let tempCopySelectedNode = Util.deepCopy(this.curSelectedNode);
                        this.curSelectedNode = this.wfStepModel[0].children.find((item) => {
                            return item.userTaskId === tempCopySelectedNode.userTaskId && item.processDefinitionKey === tempCopySelectedNode.processDefinitionKey;
                        });
                    }
                    if (this.curSelectedNode) {
                        let userTaskId = this.curSelectedNode['userTaskId'] == "all" ? undefined : this.curSelectedNode['userTaskId'];
                        Object.assign(this.viewparams, { 'taskDefinitionKey': userTaskId, 'srfwfstep': userTaskId, 'processDefinitionKey': this.curSelectedNode['processDefinitionKey'] });
                        this.setTreeNodeHighLight(this.curSelectedNode);
                        this.getWFLinkModel({ 'taskDefinitionKey': userTaskId, 'processDefinitionKey': this.curSelectedNode['processDefinitionKey'] });
                    }
                    resolve(response.data);
                }
            }).catch((response) => {
                this.$throw(response, 'getWFStepModel');
            });
        });
    }
    /**
     * 获取工具栏按钮
     *
     * @param {*} data 请求参数
     * @memberof WfDynaExpGridViewBase
     */
    getWFLinkModel(data) {
        if (!data.taskDefinitionKey) {
            this.linkModel = [];
            return;
        }
        this.appEntityService.getWFLinks(JSON.parse(JSON.stringify(this.context)), data, true).then((response) => {
            if (response && response.status === 200) {
                this.linkModel = response.data;
                if (this.linkModel.length > 0) {
                    this.linkModel.forEach((item) => {
                        item.disabled = true;
                    });
                }
            }
        }).catch((response) => {
            this.$throw(response, 'getWFLinkModel');
        });
    }
    /**
     * 工具栏点击事件
     *
     * @param {*} linkItem 点击对象
     * @param {*} $event 事件源
     * @memberof WfDynaExpGridViewBase
     */
    dynamic_toolbar_click(linkItem, $event) {
        var _a;
        let datas = [];
        let xData = this.$refs[this.gridInstance.name].ctrl;
        if (xData.getDatas && xData.getDatas instanceof Function) {
            datas = [...xData.getDatas()];
        }
        const submitBatchData = (submitdata, linkItem) => {
            xData.submitbatch(submitdata, linkItem).then((response) => {
                if (!response || response.status !== 200) {
                    return;
                }
                const { data: _data } = response;
                this.engine.load();
                if (this.viewdata) {
                    this.$emit('viewdataschange', [Object.assign({}, _data)]);
                }
            });
        };
        if (linkItem && linkItem.sequenceflowview) {
            const targetView = this.viewRefData.find((item) => {
                return item.name === `WFACTION@${linkItem.sequenceflowview}`;
            });
            if (targetView) {
                let tempContext = Util.deepCopy(this.context);
                let tempViewParam = { actionView: linkItem.sequenceflowview, actionForm: linkItem.sequenceflowform };
                const appmodal = this.$appmodal.openModal({ viewname: Util.srfFilePath2(targetView.codeName), title: this.$tl((_a = targetView.getCapPSLanguageRes()) === null || _a === void 0 ? void 0 : _a.lanResTag, targetView.caption), height: targetView.height, width: targetView.width }, tempContext, tempViewParam);
                appmodal.subscribe((result) => {
                    if (!result || !Object.is(result.ret, 'OK')) {
                        return;
                    }
                    let tempSubmitData = Util.deepCopy(datas);
                    tempSubmitData.forEach((element) => {
                        element.viewparams = result.datas && result.datas[0];
                    });
                    submitBatchData(tempSubmitData, linkItem);
                });
            }
        }
        else {
            submitBatchData(datas, linkItem);
        }
    }
    /**
     * 左侧树选中节点
     *
     * @param {*} data 选择数据
     * @memberof WfDynaExpGridViewBase
     */
    handleNodeClick(data) {
        this.curSelectedNode = data;
        this.setTreeNodeHighLight(this.curSelectedNode);
        let userTaskId = data['userTaskId'] == "all" ? undefined : data['userTaskId'];
        Object.assign(this.viewparams, { 'taskDefinitionKey': userTaskId, 'srfwfstep': userTaskId, 'processDefinitionKey': data['processDefinitionKey'] });
        this.getWFLinkModel({ 'taskDefinitionKey': userTaskId, 'processDefinitionKey': this.curSelectedNode['processDefinitionKey'] });
        this.$refs[this.searchFormInstance.name].ctrl.onSearch();
    }
    /**
     * 设置选中高亮
     *
     * @param {*} data
     * @memberof WfDynaExpGridViewBase
     */
    setTreeNodeHighLight(data) {
        this.$nextTick(() => {
            const tree = this.$refs.tree;
            if (tree) {
                tree.setCurrentKey(data.userTaskId);
            }
        });
    }
    /**
     * @description 快速搜索点击事件
     * @param {*} $event
     * @memberof WfDynaExpGridViewBase
     */
    onQuickSearchClick($event) {
        var _a, _b;
        const refs = this.$refs;
        if (refs[(_a = this.gridInstance) === null || _a === void 0 ? void 0 : _a.name] && refs[this.gridInstance.name].ctrl) {
            refs[(_b = this.gridInstance) === null || _b === void 0 ? void 0 : _b.name].ctrl.load(this.context, true);
        }
    }
    /**
     * 渲染快速搜索(DEFAULT)
     *
     * @return {*}
     * @memberof WfDynaExpGridViewBase
     */
    renderQuickSearch() {
        var _a, _b;
        const searchformItem = ((_a = this.searchFormInstance) === null || _a === void 0 ? void 0 : _a.getPSDEFormItems()) || [];
        let enableFilter = ((_b = this.viewInstance) === null || _b === void 0 ? void 0 : _b.enableFilter) === true && searchformItem.length > 0;
        const popoverClass = this.searchFormInstance ? 'searchform-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.onQuickSearchClick($event)} v-model={this.query} placeholder={this.placeholder}/>
            {<el-popover placement="bottom" popper-class={popoverClass} trigger="click" visible-arrow={false} on-hide={() => this.isExpandSearchForm = !this.isExpandSearchForm}>
                <i-button slot="reference" class={{ 'filter': true, 'is-expand': this.isExpandSearchForm, 'hidden-searchbtn': !enableFilter }} icon="ios-funnel" on-click={(e) => {
                    if (!this.isExpandSearchForm) {
                        throttle(() => AppGlobalService.getInstance().executeGlobalAction('ToggleFilter', undefined, undefined, undefined, e, undefined, this, undefined), [], this);
                    }
                }}/>
                {popoverClass && popoverClass != '' ? this.renderSearchForm() : null}
            </el-popover>}
        </template>;
    }
}
