import { EditFormControlBase } from './editform-control-base';
import moment from 'moment';
import { GetModelService, LogUtil, Util } from '@ibizstudio/runtime';
import { CodeListTranslator } from '../app-service';
/**
 * 搜索表单部件基类
 *
 * @export
 * @class SearchFormControlBase
 * @extends {EditFormControlBase}
 */
export class SearchFormControlBase extends EditFormControlBase {
    constructor() {
        super(...arguments);
        /**
         * 代码表翻译器实例
         *
         * @typedef {CodeListTranslator}
         * @memberof SearchFormControlBase
         */
        this.codeListTranslator = new CodeListTranslator();
        /**
         * 是否展开搜索表单
         *
         * @type {*}
         * @memberof SearchFormControlBase
         */
        this.isExpandSearchForm = false;
        /**
         * 存储项名称
         *
         * @type {string}
         * @memberof SearchFormControlBase
         */
        this.saveItemName = '';
        /**
         * 历史记录
         *
         * @type {any[]}
         * @memberof SearchFormControlBase
         */
        this.historyItems = [];
        /**
         * 选中记录
         *
         * @type {any}
         * @memberof SearchFormControlBase
         */
        this.selectItem = null;
        /**
         * 模型id
         *
         * @type {any}
         * @memberof SearchFormControlBase
         */
        this.modelId = "";
        /**
         * 功能服务名称
         *
         * @type {any}
         * @memberof SearchFormControlBase
         */
        this.utilServiceName = "";
        /**
         * 是否开启保存查询条件
         *
         * @type {any}
         * @memberof SearchFormControlBase
         */
        this.enableSaveFilter = true;
    }
    /**
     * 监听静态参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof SearchFormControlBase
     */
    onStaticPropsChange(newVal, oldVal) {
        this.enableSaveFilter = newVal.enableSaveFilter === false ? false : true;
        super.onStaticPropsChange(newVal, oldVal);
    }
    /**
     * 监听动态参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof SearchFormControlBase
     */
    onDynamicPropsChange(newVal, oldVal) {
        this.isExpandSearchForm = newVal === null || newVal === void 0 ? void 0 : newVal.isExpandSearchForm;
        //搜索表单绘制之后关闭清空数据
        if (!this.isExpandSearchForm && this.controlIsLoaded) {
            Object.keys(this.data).forEach((key) => {
                this.data[key] = null;
            });
        }
        super.onDynamicPropsChange(newVal, oldVal);
    }
    /**
     * 初始化搜索表单模型
     *
     * @memberof SearchFormControlBase
     */
    async ctrlModelInit() {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        await super.ctrlModelInit();
        this.loaddraftAction = ((_d = (_c = (_b = (_a = this.controlInstance.getPSControlHandler()) === null || _a === void 0 ? void 0 : _a.findPSControlHandlerAction('loaddraft')) === null || _b === void 0 ? void 0 : _b.getPSAppDEMethod) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.codeName) || 'GetDraft';
        this.loadAction = ((_h = (_g = (_f = (_e = this.controlInstance.getPSControlHandler()) === null || _e === void 0 ? void 0 : _e.findPSControlHandlerAction('load')) === null || _f === void 0 ? void 0 : _f.getPSAppDEMethod) === null || _g === void 0 ? void 0 : _g.call(_f)) === null || _h === void 0 ? void 0 : _h.codeName) || 'Load';
        this.modelId = `searchform_${this.appDeCodeName ? this.appDeCodeName.toLowerCase() : 'app'}_${this.controlInstance.codeName.toLowerCase()}`;
        await this.initUtilService();
    }
    /**
     * 初始化功能服务名称
     *
     * @memberof SearchFormControlBase
     */
    async initUtilService() {
        var _a, _b;
        const appUtil = ((await ((_a = (await GetModelService(this.context))) === null || _a === void 0 ? void 0 : _a.app)).getAllPSAppUtils() || []).find((util) => {
            return util.utilType == 'FILTERSTORAGE';
        });
        if (appUtil) {
            this.utilServiceName = (_b = appUtil.codeName) === null || _b === void 0 ? void 0 : _b.toLowerCase();
        }
        this.utilServiceName = "dynafilter";
    }
    /**
     * 部件创建完毕
     *
     * @memberof SearchFormControlBase
     */
    ctrlInit() {
        super.ctrlInit();
        this.loadModel();
    }
    loadModel() {
        let param = {};
        Object.assign(param, Object.assign({ appdeName: this.appDeCodeName, modelid: this.modelId, utilServiceName: this.utilServiceName }, this.viewparams));
        let tempContext = JSON.parse(JSON.stringify(this.context));
        this.onControlRequset('load', tempContext, param);
        let post = this.service.loadModel(this.utilServiceName, tempContext, param);
        post.then((response) => {
            this.onControlResponse('load', response);
            if (response.status == 200 && response.data) {
                this.historyItems = response.data;
            }
        }).catch((response) => {
            this.onControlResponse('load', response);
            LogUtil.log(response);
        });
    }
    /**
     * 处理dataChang下发的事件
     *
     * @memberof SearchFormControlBase
     */
    handleDataChange() {
        if (this.isAutoSave) {
            this.ctrlEvent({
                controlname: this.name,
                action: 'load',
                data: this.data,
            });
        }
    }
    /**
     * 加载草稿
     *
     * @param {*} opt 额外参数
     * @memberof SearchFormControlBase
     */
    loadDraft(opt = {}, mode) {
        if (!this.loaddraftAction) {
            this.$throw('视图' + this.$t('app.searchform.notconfig.loaddraftaction'), 'loadDraft');
            return;
        }
        const arg = Object.assign({}, opt);
        Object.assign(arg, { viewparams: this.viewparams });
        let tempContext = JSON.parse(JSON.stringify(this.context));
        this.onControlRequset('loadDraft', tempContext, arg);
        let post = this.service.loadDraft(this.loaddraftAction, tempContext, arg, this.showBusyIndicator);
        post.then((response) => {
            this.onControlResponse('loadDraft', response);
            if (!response.status || response.status !== 200) {
                this.$throw(response, 'loadDraft');
                return;
            }
            const data = response.data;
            this.resetDraftFormStates();
            this.onFormLoad(data, 'loadDraft');
            setTimeout(() => {
                const form = this.$refs[this.name];
                if (form) {
                    form.fields.forEach((field) => {
                        field.validateMessage = "";
                        field.validateState = "";
                        field.validateStatus = false;
                    });
                }
            });
            if (Object.is(mode, 'RESET')) {
                if (!this.formValidateStatus()) {
                    return;
                }
            }
            this.ctrlEvent({
                controlname: this.name,
                action: 'load',
                data: data,
            });
            this.$nextTick(() => {
                this.formState.next({ type: 'load', data: data });
            });
        }).catch((response) => {
            this.onControlResponse('loadDraft', response);
            this.$throw(response, 'loadDraft');
        });
    }
    /**
     * 表单值变化
     *
     * @param {{ name: string, newVal: any, oldVal: any }} param
     * @memberof SearchFormControlBase
     */
    formDataChange(param) {
        super.formDataChange(param);
        this.ctrlEvent({
            controlname: this.name,
            action: 'valuechange',
            data: this.data,
        });
    }
    /**
     * 表单加载完成
     *
     * @param {*} [data={}]
     * @param {string} action
     * @memberof SearchFormControlBase
     */
    onFormLoad(data = {}, action) {
        this.setFormEnableCond(data);
        this.fillForm(data, action);
        this.formLogic({ name: '' });
    }
    /**
     * 回车事件
     *
     * @param {*} $event
     * @memberof SearchFormControlBase
     */
    onEnter($event) {
        this.ctrlEvent({
            controlname: this.name,
            action: 'search',
            data: this.data,
        });
    }
    /**
     * 搜索
     *
     * @memberof SearchFormControlBase
     */
    onSearch() {
        this.ctrlEvent({
            controlname: this.name,
            action: 'search',
            data: this.data,
        });
    }
    /**
     * 确定
     *
     * @return {*}
     * @memberof SearchFormControlBase
     */
    onOk() {
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        let propip = this.$refs.propip;
        propip.handleMouseleave();
        this.onSave(this.saveItemName);
    }
    /**
     * 取消设置
     *
     * @return {*}
     * @memberof SearchFormControlBase
     */
    onCancel() {
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        let propip = this.$refs.propip;
        propip.handleMouseleave();
        // this.onSave();
    }
    /**
     * 删除记录
     *
     * @return {*}
     * @memberof SearchFormControlBase
     */
    removeHistoryItem(event, item) {
        event.stopPropagation();
        if (!(item && item.name && item.value)) {
            return;
        }
        const index = this.historyItems.findIndex((_item) => {
            return _item.name == item.name && _item.value == _item.value;
        });
        if (index !== -1) {
            this.historyItems.splice(index, 1);
            if (this.selectItem == item.value) {
                if (this.historyItems.length > 0) {
                    this.selectItem = this.historyItems[0].value;
                    this.data = JSON.parse(JSON.stringify(this.historyItems[0].data));
                }
                else {
                    this.selectItem = null;
                    Object.keys(this.data).forEach((key) => {
                        this.data[key] = null;
                    });
                }
            }
            let param = {};
            Object.assign(param, Object.assign({ model: JSON.parse(JSON.stringify(this.historyItems)), appdeName: this.appDeCodeName, modelid: this.modelId, utilServiceName: this.utilServiceName }, this.viewparams));
            let post = this.service.saveModel(this.utilServiceName, this.context, param);
            post.then((response) => {
                this.ctrlEvent({ controlname: this.controlInstance.name, action: "save", data: response.data });
            }).catch((response) => {
                LogUtil.log(response);
            });
        }
    }
    /**
     * 保存
     *
     * @return {*}
     * @memberof SearchFormControlBase
     */
    async onSave(name) {
        if (Util.isEmptyObject(this.data)) {
            LogUtil.warn(this.$t('app.searchform.nosearchparam'));
            return;
        }
        let time = moment();
        this.historyItems.push({
            name: await this.getSaveName(name),
            value: time.unix().toString(),
            data: JSON.parse(JSON.stringify(this.data))
        });
        this.selectItem = time.unix().toString();
        let param = {};
        Object.assign(param, Object.assign({ model: JSON.parse(JSON.stringify(this.historyItems)), appdeName: this.appDeCodeName, modelid: this.modelId, utilServiceName: this.utilServiceName }, this.viewparams));
        try {
            const response = await this.service.saveModel(this.utilServiceName, this.context, param);
            this.ctrlEvent({ controlname: this.controlInstance.name, action: "save", data: response.data });
        }
        catch (error) {
            LogUtil.error(error);
        }
    }
    /**
     * 改变过滤条件
     *
     * @return {*}
     * @memberof SearchFormControlBase
     */
    onFilterChange(evt) {
        let item = this.historyItems.find((item) => Object.is(evt, item.value));
        if (item) {
            this.selectItem = item.value;
            this.data = JSON.parse(JSON.stringify(item.data));
        }
    }
    /**
     * 重置
     *
     * @memberof SearchFormControlBase
     */
    onReset() {
        this.loadDraft({}, 'RESET');
    }
    /**
     * 开启自动搜索时，值变更触发搜索
     *
     * @param $event
     * @memberof SearchFormControlBase
     */
    onFormItemValueChange($event) {
        super.onFormItemValueChange($event);
        //  自动搜索
        if (this.controlInstance.enableAutoSearch) {
            this.onSearch();
        }
    }
    /**
     * 监听回车事件
     *
     * @memberof SearchFormControlBase
     */
    onKeyUp(event) {
        const e = event || window.event;
        //  回车触发搜索
        if (e && e.keyCode == '13') {
            setTimeout(() => {
                this.onSearch();
            }, 200);
        }
    }
    /**
     * 保存查询条件时获取保存名称
     *
     * @memberof SearchFormControlBase
     */
    async getSaveName(name) {
        var _a, _b;
        if (name) {
            return name;
        }
        for (const key of Object.keys(this.data)) {
            if (key.search(/n_\\S*_\\S*/) && Util.isExistAndNotEmpty(this.data[key])) {
                const field = (_b = (_a = this.controlInstance.findPSDEFormItem(key)) === null || _a === void 0 ? void 0 : _a.getPSAppDEField) === null || _b === void 0 ? void 0 : _b.call(_a);
                if (field) {
                    const editItem = this.findFormItemByField(field.name);
                    let value = await this.formatCodelistValue(this.data[key], editItem);
                    if (editItem) {
                        name += `${name == '' ? '' : ', '}${field.logicName}: ${value}`;
                    }
                }
            }
        }
        return name || moment().unix().toString();
    }
    /**
     * 转化代码表值
     *
     * @memberof SearchFormControlBase
     */
    async formatCodelistValue(value, item) {
        var _a, _b, _c;
        const codeList = (_c = (_b = (_a = item.getPSEditor) === null || _a === void 0 ? void 0 : _a.call(item)) === null || _b === void 0 ? void 0 : _b.getPSAppCodeList) === null || _c === void 0 ? void 0 : _c.call(_b);
        if (codeList) {
            try {
                let response = await this.codeListTranslator.getCodeListText(value, codeList, this, Util.deepCopy(this.context), Util.deepCopy(this.viewparams));
                if (response) {
                    return response;
                }
            }
            catch (_d) {
                return value;
            }
        }
        return value;
    }
}
