import { GetModelService, LogUtil, Util } from '@ibizstudio/runtime';
import moment from 'moment';
import { AppSearchBarService } from '../ctrl-service/app-searchbar-service';
import { MDControlBase } from './md-control-base';
export class SearchBarControlBase extends MDControlBase {
    constructor() {
        super(...arguments);
        /**
         * 是否展开搜索栏部件
         *
         * @type {boolean}
         * @memberof SearchBarControlBase
         */
        this.isExpandSearchForm = false;
        /**
         * 过滤属性模型集合
         *
         * @type {any}
         * @memberof SearchBarControlBase
         */
        this.detailsModel = {};
        /**
         * 过滤项集合
         *
         * @type {any[]}
         * @memberof SearchBarControlBase
         */
        this.filterItems = [];
        /**
         * 应用实体名称
         *
         * @type {string}
         * @memberof SearchBarControlBase
         */
        this.appdeName = "";
        /**
         * modelid
         *
         * @type {string}
         * @memberof SearchBarControlBase
         */
        this.modelId = "";
        /**
         * 功能服务名称
         *
         * @type {string}
         * @memberof SearchBarControlBase
         */
        this.utilServiceName = "";
        /**
         * 历史记录
         *
         * @type {any[]}
         * @memberof SearchBarControlBase
         */
        this.historyItems = [];
        /**
         * 选中记录
         *
         * @type {any}
         * @memberof SearchBarControlBase
         */
        this.selectItem = null;
        /**
         * 存储项名称
         *
         * @type {string}
         * @memberof SearchBarControlBase
         */
        this.saveItemName = "";
    }
    /**
     * 过滤属性集合
     *
     * @memberof SearchBarControlBase
     */
    get filterFields() {
        return Object.values(this.detailsModel);
    }
    /**
     * 监听动态参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof SearchBarControlBase
     */
    onDynamicPropsChange(newVal, oldVal) {
        this.isExpandSearchForm = newVal.isExpandSearchForm;
        //搜索栏绘制之后关闭清空数据
        if (!this.isExpandSearchForm && this.controlIsLoaded) {
            this.filterItems = [];
        }
        super.onDynamicPropsChange(newVal, oldVal);
    }
    /**
     * 部件模型数据初始化
     *
     * @memberof SearchBarControlBase
     */
    async ctrlModelInit() {
        await super.ctrlModelInit();
        this.service = new AppSearchBarService();
        this.modelId = `searchbar_${this.appDeCodeName ? this.appDeCodeName.toLowerCase() : 'app'}_${this.controlInstance.codeName.toLowerCase()}`;
        await this.initUtilService();
    }
    /**
     * 初始化功能服务名称
     *
     * @memberof SearchBarControlBase
     */
    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();
        }
    }
    /**
     * 部件初始化
     *
     * @memberof SearchBarControlBase
     */
    ctrlInit() {
        super.ctrlInit();
        this.initDetailsModel();
        this.load();
    }
    /**
     * 初始化过滤属性模型集合
     *
     * @memberof SearchBarControlBase
     */
    initDetailsModel() {
        const barFilters = this.controlInstance.getPSSearchBarFilters() || [];
        if (barFilters.length === 0) {
            return;
        }
        barFilters.forEach((filter) => {
            var _a;
            const appDeField = filter.getPSAppDEField();
            let tempModel = {
                label: appDeField === null || appDeField === void 0 ? void 0 : appDeField.logicName,
                localtag: "",
                name: filter.name,
                prop: ((_a = appDeField === null || appDeField === void 0 ? void 0 : appDeField.codeName) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || filter.name,
                disabled: false
            };
            const searchMode = filter.getPSDEFSearchMode();
            if (searchMode && searchMode.valueOP) {
                Object.assign(tempModel, { mode: searchMode.valueOP });
            }
            Object.assign(this.detailsModel, { [filter.name]: tempModel });
        });
    }
    /**
     * 删除过滤项
     *
     * @param {number} index 索引
     * @memberof SearchBarControlBase
     */
    onRemove(index) {
        this.filterItems.splice(index, 1);
    }
    /**
     * 搜索
     *
     * @return {*}
     * @memberof SearchBarControlBase
     */
    onSearch() {
        this.ctrlEvent({
            controlname: this.controlInstance.name,
            action: "search",
            data: this.getData()
        });
    }
    /**
     * 保存
     *
     * @param {string} [name] 名称
     * @memberof SearchBarControlBase
     */
    onSave(name) {
        let time = moment();
        this.historyItems.push({
            name: (name ? name : time.format('YYYY-MM-DD HH:mm:ss')),
            value: time.unix().toString(),
            data: Util.deepCopy(this.filterItems)
        });
        this.selectItem = time.unix().toString();
        let param = {};
        Object.assign(param, Object.assign({ model: Util.deepCopy(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 SearchBarControlBase
     */
    onReset() {
        this.filterItems = [];
    }
    /**
     * 加载
     *
     * @return {*}
     * @memberof SearchBarControlBase
     */
    load() {
        let param = {};
        Object.assign(param, Object.assign({ appdeName: this.appDeCodeName, modelid: this.modelId, utilServiceName: this.utilServiceName }, this.viewparams));
        let tempContext = Util.deepCopy(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) {
                this.historyItems = response.data;
            }
            this.ctrlEvent({ controlname: this.controlInstance.name, action: "load", data: this.historyItems });
        }).catch((response) => {
            this.onControlResponse('load', response);
            LogUtil.log(response);
        });
    }
    /**
     * 改变过滤条件
     *
     * @param {*} evt
     * @memberof SearchBarControlBase
     */
    onFilterChange(evt) {
        let item = this.historyItems.find((item) => Object.is(evt, item.value));
        if (item) {
            this.selectItem = item.value;
            this.filterItems = Util.deepCopy(item.data);
        }
    }
    /**
     * 打开弹框
     *
     * @return {*}
     * @memberof SearchBarControlBase
     */
    openPoper() {
        this.saveItemName = '';
    }
    /**
     * 确定
     *
     * @return {*}
     * @memberof SearchBarControlBase
     */
    onOk() {
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        let propip = this.$refs.propip;
        propip.handleMouseleave();
        this.onSave(this.saveItemName);
    }
    /**
     * 取消设置
     *
     * @return {*}
     * @memberof SearchBarControlBase
     */
    onCancel() {
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        let propip = this.$refs.propip;
        propip.handleMouseleave();
        // this.onSave();
    }
    /**
     * 获取数据集
     *
     * @memberof SearchBarControlBase
     */
    getDatas() {
        return [];
    }
    /**
     * 获取单项数据
     *
     * @memberof SearchBarControlBase
     */
    getData() {
        let data = {};
        if (this.filterFields.length > 0) {
            let filter = this.getFilter();
            Object.assign(data, { filter: filter ? filter : null });
        }
        return data;
    }
    /**
     * 获取过滤树
     *
     * @memberof SearchBarControlBase
     */
    getFilter() {
        if (this.filterItems.length === 0) {
            return null;
        }
        let ands = this.transformAnd(this.filterItems);
        this.transformResult(ands, '$and');
        if (ands.length === 0) {
            return null;
        }
        return { '$and': ands };
    }
    /**
     * 处理结果集
     *
     * @param {any[]} datas 数据
     * @param {string} pName
     * @memberof SearchBarControlBase
     */
    transformResult(datas, pName) {
        let items = [];
        for (let i = datas.length - 1; i >= 0; i--) {
            let data = datas[i];
            let field = Object.is(pName, '$and') ? '$or' : '$and';
            if (data.hasOwnProperty(field)) {
                items.push(data);
                datas.splice(i, 1);
                this.transformResult(data[field], field);
            }
        }
        if (items.length > 0) {
            let item = {};
            item[pName] = items;
            datas.push(item);
        }
    }
    /**
     * 处理并且逻辑
     *
     * @param {any[]} datas 数据
     * @return {*}  {*}
     * @memberof SearchBarControlBase
     */
    transformAnd(datas) {
        let result = [];
        datas.forEach((data) => {
            let item = {};
            if (data.field && data.mode) {
                item[data.field] = {};
                let valField = data.editor ? data.editor : data.field;
                item[data.field][data.mode] = (data[valField] == null ? '' : data[valField]);
                result.push(item);
            }
            else if (Object.is(data.label, '$and')) {
                let items = this.transformAnd(data.children);
                result = [...result, ...items];
            }
            else if (Object.is(data.label, '$or')) {
                item[data.label] = this.transformOr(data.children);
                result.push(item);
            }
        });
        return result;
    }
    /**
     * 处理或逻辑
     *
     * @param {any[]} datas 数据
     * @return {*}
     * @memberof SearchBarControlBase
     */
    transformOr(datas) {
        let result = [];
        datas.forEach((data) => {
            let item = {};
            if (data.field && data.mode) {
                item[data.field] = {};
                let valField = data.editor ? data.editor : data.field;
                item[data.field][data.mode] = (data[valField] == null ? '' : data[valField]);
                result.push(item);
            }
            else if (Object.is(data.label, '$and')) {
                item[data.label] = this.transformAnd(data.children);
                result.push(item);
            }
            else if (Object.is(data.label, '$or')) {
                item[data.label] = this.transformOr(data.children);
                result.push(item);
            }
        });
        return result;
    }
}
