import { __decorate } from "tslib";
import { Component, Model, Prop, Vue, Inject } from 'vue-property-decorator';
import { CodeListService } from '@ibizstudio/runtime';
import { LogUtil, Util } from '@ibizstudio/runtime';
import { VueLifeCycleProcessing } from '../../../decorators';
import './tree-dropdown-list.less';
/**
 * 树形代码表插件类
 *
 * @export
 * @class TreeDropdownList
 * @extends {Vue}
 */
let TreeDropdownList = class TreeDropdownList extends Vue {
    constructor() {
        super(...arguments);
        /**
         * 代码表服务对象
         *
         * @type {CodeListService}
         * @memberof TreeDropdownList
         */
        this.codeListService = new CodeListService({ $store: this.$store });
        /**
         * 是否有子集
         * @type {boolean}
         * @memberof TreeDropdownList
         */
        this.hasChildren = false;
        /**
         * @description 过滤词
         * @memberof TreeDropdownList
         */
        this.searchValue = '';
        /**
         * @description 选中数据
         * @type {*}
         * @memberof TreeDropdownList
         */
        this.select = null;
        /**
         * 代码表
         *
         * @type {any[]}
         * @memberof TreeDropdownList
         */
        this.items = [];
        /**
         * @description 临时代码表
         * @type {any[]}
         * @memberof TreeDropdownList
         */
        this.codeListData = [];
        this.isSpread = false;
        /**
         * 选项行样式名
         *
         * @type {string}
         * @memberof DropDownList
         */
        this.itemClass = '';
        /**
         * 选项组样式名
         *
         * @type {string}
         * @memberof DropDownList
         */
        this.transferClass = 'transferDropdownWidthTreeDropdowmList';
    }
    /**
     * @description 获取值
     * @memberof TreeDropdownList
     */
    get currentVal() {
        if (this.itemValue) {
            return this.itemValue.split(this.valueSeparator);
        }
        else {
            return [];
        }
    }
    /**
     * @description 获取值
     * @memberof TreeDropdownList
     */
    set currentVal($event) {
        const string = $event.join(this.valueSeparator);
        this.$emit('change', string ? string : null);
    }
    /**
     * @description 当前单选输入值
     * @memberof TreeDropdownList
     */
    get curText() {
        if (this.select && Object.is(this.select.value, this.itemValue)) {
            return this.select.label;
        }
        else {
            const item = this.codeListData.find(data => Object.is(data.value, this.itemValue));
            if (item) {
                this.select = item;
                return item.label;
            }
            else {
                return this.searchValue;
            }
        }
    }
    /**
     * @description 当前单选输入值
     * @memberof TreeDropdownList
     */
    set curText(value) {
        var _a, _b, _c;
        const autoComplete = this.$refs.autoComplete;
        const el = (_c = (_b = (_a = autoComplete === null || autoComplete === void 0 ? void 0 : autoComplete.$refs) === null || _a === void 0 ? void 0 : _a.input) === null || _b === void 0 ? void 0 : _b.$refs) === null || _c === void 0 ? void 0 : _c.input;
        if (el && el === document.activeElement) {
            this.searchValue = value;
        }
        else {
            this.searchValue = '';
        }
        const item = this.codeListData.find(data => Object.is(data.label, value));
        if (item) {
            this.select = item;
            this.$emit('change', item.value);
        }
        else {
            this.$emit('change', value);
        }
    }
    /**
     * vue  生命周期
     *
     * @memberof TreeDropdownList
     */
    created() {
        if (this.formState) {
            this.formStateEvent = this.formState.subscribe(({ type, data }) => {
                if (Object.is('load', type)) {
                    this.handleCodeListItems();
                }
            });
        }
        if (this.itemValue || this.itemValue === 0 || this.itemValue === false) {
            this.handleCodeListItems();
        }
    }
    /**
     * @description 生命周期
     * @memberof TreeDropdownList
     */
    destroyed() {
        if (this.formStateEvent) {
            this.formStateEvent.unsubscribe();
        }
    }
    /**
     * @description 下拉显示控制
     * @param {boolean} visible
     * @memberof TreeDropdownList
     */
    visibleChange(visible) {
        this.isSpread = true;
        if (visible) {
            const dropdownSelect = this.$refs.dropdownSelect;
            if (dropdownSelect) {
                const popper = dropdownSelect.$refs.popper;
                if (popper) {
                    const popperEl = popper.$el;
                    const el = this.$el;
                    if (popperEl && el) {
                        popperEl.style.minWidth = `${el.offsetWidth}px`;
                        popperEl.style.maxWidth = `${el.offsetWidth > 700 ? el.offsetWidth : 700}px`;
                    }
                }
            }
            const autoComplete = this.$refs.autoComplete;
            if (autoComplete) {
                const select = autoComplete.$refs.select;
                if (select) {
                    const dropdown = select.$refs.dropdown;
                    if (dropdown) {
                        const dropdownEl = dropdown.$el;
                        const el = this.$el;
                        if (dropdownEl && el) {
                            dropdownEl.style.minWidth = `${el.offsetWidth}px`;
                            dropdownEl.style.maxWidth = `${el.offsetWidth > 700 ? el.offsetWidth : 700}px`;
                        }
                    }
                }
            }
            this.handleCodeListItems();
        }
    }
    /**
     * 处理代码表
     *
     * @memberof TreeDropdownList
     */
    handleCodeListItems() {
        if (this.tag && this.codelistType) {
            let data = {};
            this.handlePublicParams(data);
            // 参数处理
            let context = data.context;
            let viewparam = data.param;
            this.codeListService
                .getDataItems({ tag: this.tag, type: this.codelistType, data: this.codeList, context: context, viewparam: viewparam })
                .then((codelistItems) => {
                this.codeListData = codelistItems;
                this.formatCodeList(codelistItems);
            })
                .catch((error) => {
                LogUtil.log(`----${this.tag}----${this.$t('app.commonwords.codenotexist')}`);
            });
        }
    }
    /**
     * @description 公共参数处理
     * @param {*} arg
     * @memberof TreeDropdownList
     */
    handlePublicParams(arg) {
        // 合并表单参数
        arg.param = this.viewparams ? JSON.parse(JSON.stringify(this.viewparams)) : {};
        arg.context = this.context ? JSON.parse(JSON.stringify(this.context)) : {};
        // 附加参数处理
        if (this.localContext && Object.keys(this.localContext).length > 0) {
            let _context = this.$util.computedNavData(this.data, arg.context, arg.param, this.localContext);
            Object.assign(arg.context, _context);
        }
        if (this.localParam && Object.keys(this.localParam).length > 0) {
            let _param = this.$util.computedNavData(this.data, arg.context, arg.param, this.localParam);
            Object.assign(arg.param, _param);
        }
    }
    /**
     * 代码表类型和属性匹配
     *
     * @param {*} items
     * @memberof TreeDropdownList
     */
    formatCodeList(items) {
        let matching = false;
        this.items = [];
        try {
            items.forEach((item) => {
                const type = this.$util.typeOf(item.value);
                if (type != this.valueType) {
                    matching = true;
                    if (type === 'number') {
                        item.value = item.value.toString();
                    }
                    else {
                        if (type == 'null') {
                            this.valueType == 'number' ? (item.value = 0) : (item.value = '');
                        }
                        else if (item.value.indexOf('.') == -1) {
                            item.value = parseInt(item.value);
                        }
                        else {
                            item.value = parseFloat(item.value);
                        }
                    }
                }
                this.items.push(item);
            });
            if (matching) {
                LogUtil.warn(`${this.tag}${this.$t('app.commonwords.codelistwarn')}`);
            }
        }
        catch (error) {
            LogUtil.warn(this.$t('app.commonwords.codelistwarn'));
        }
        this.handleLevelCodeList(Util.deepCopy(this.items));
    }
    /**
     * 处理层级代码表
     *
     * @param {*} items
     * @memberof TreeDropdownList
     */
    handleLevelCodeList(items) {
        if (items && items.length > 0) {
            this.hasChildren = items.some((item) => {
                return item.pvalue;
            });
            if (this.hasChildren) {
                let list = [];
                items.forEach((codeItem) => {
                    if (!codeItem.pvalue) {
                        let valueField = codeItem.value;
                        this.setChildCodeItems(valueField, items, codeItem);
                        list.push(codeItem);
                    }
                });
                this.items = list;
            }
        }
    }
    /**
     * 计算子类代码表
     *
     * @param {*} items
     * @memberof TreeDropdownList
     */
    setChildCodeItems(pValue, result, codeItem) {
        result.forEach((item) => {
            if (item.pvalue == pValue) {
                let valueField = item.value;
                this.setChildCodeItems(valueField, result, item);
                if (!codeItem.children) {
                    codeItem.children = [];
                }
                codeItem.children.push(item);
            }
        });
    }
    /**
     * @description 对数据进行过滤,判断当前项是否显示
     * @param {*} data
     * @param {*} pItems
     * @return {*}
     * @memberof TreeDropdownList
     */
    isShow(data, pItem) {
        if (Object.is(this.searchValue, '')) {
            return true;
        }
        if (data.text.indexOf(this.searchValue) > -1) {
            return true;
        }
        else {
            if (data.children) {
                if (this.findChild(data.children)) {
                    return true;
                }
            }
            if (pItem.text && pItem.text.indexOf(this.searchValue) > -1) {
                return true;
            }
        }
        return false;
    }
    /**
     * @description 查看子项是否有符合项
     * @param {*} data
     * @param {*} codelistItems
     * @param {*} word
     * @return {*}
     * @memberof TreeDropdownList
     */
    findChild(data) {
        const index = data.findIndex((item) => {
            if (item.text.indexOf(this.searchValue) > -1) {
                return true;
            }
            else if (item.children) {
                return this.findChild(item.children);
            }
        });
        return Object.is(index, -1) ? false : true;
    }
    /**
     * @description 生成树形代码表-下拉单选
     * @param {*} items
     * @memberof TreeDropdownList
     */
    setTreeDropdownList(item, pItem = {}) {
        const isShow = this.isShow(item, pItem);
        if (item.children) {
            return isShow ? (<div>
          <div class='dropdowm-list-group'>
            <span>{item.label}</span>
          </div>
          <div class='tree-dropdowm-list-content'>
            {item.children.map((item) => {
                    return this.setTreeDropdownList(item, item);
                })}
          </div>
        </div>) : null;
        }
        else {
            return isShow ? (<i-option class={[{ 'option-active': Object.is(item.value, this.itemValue) }, this.itemClass]} key={item.value} value={item.label}>
          <span>{item.label}</span>
        </i-option>) : null;
        }
    }
    /**
     * @description 绘制多选下拉树形列表
     * @param {*} items
     * @return {*}
     * @memberof TreeDropdownList
     */
    setTreeDropdownListMultiple(item, pItem = {}) {
        const hidden = this.isShow(item, pItem);
        if (item.children) {
            return hidden ? (<el-option-group key={item.id} label={item.label}>
          {item.children.map((item) => {
                    return this.setTreeDropdownListMultiple(item, item);
                })}
        </el-option-group>) : null;
        }
        else {
            return hidden ? <el-option key={item.id} label={item.label} value={item.value}></el-option> : null;
        }
    }
    render() {
        if (this.isMultiple) {
            return (<div class='tree-dropdowm-list' ref='treeDropdownList'>
          <el-select ref='dropdownSelect' v-model={this.currentVal} size='small' popper-class='tree-dropdowm-list-option' multiple filterable allow-create on-visible-change={(visible) => this.visibleChange(visible)} default-first-option placeholder={this.placeholder}>
            {this.items.map((item) => {
                    return this.setTreeDropdownListMultiple(item);
                })}
          </el-select>
        </div>);
        }
        else {
            return (<div class='tree-dropdowm-list' ref='treeDropdownList'>
          <auto-complete ref='autoComplete' class={this.isSpread ? 'select-visible' : ''} v-model={this.curText} transfer={true} transfer-class-name={this.transferClass} on-on-focus={() => this.visibleChange(true)} icon='ios-arrow-down' on-on-blur={() => {
                    this.isSpread = false;
                }}>
            {this.items.map((item) => {
                    return this.setTreeDropdownList(item);
                })}
          </auto-complete>
        </div>);
        }
    }
};
__decorate([
    Model('change')
], TreeDropdownList.prototype, "itemValue", void 0);
__decorate([
    Prop()
], TreeDropdownList.prototype, "tag", void 0);
__decorate([
    Prop()
], TreeDropdownList.prototype, "codelistType", void 0);
__decorate([
    Prop()
], TreeDropdownList.prototype, "codeList", void 0);
__decorate([
    Prop()
], TreeDropdownList.prototype, "data", void 0);
__decorate([
    Inject('formState')
], TreeDropdownList.prototype, "formState", void 0);
__decorate([
    Prop()
], TreeDropdownList.prototype, "localContext", void 0);
__decorate([
    Prop()
], TreeDropdownList.prototype, "localParam", void 0);
__decorate([
    Prop()
], TreeDropdownList.prototype, "context", void 0);
__decorate([
    Prop()
], TreeDropdownList.prototype, "viewparams", void 0);
__decorate([
    Prop()
], TreeDropdownList.prototype, "disabled", void 0);
__decorate([
    Prop({ default: false })
], TreeDropdownList.prototype, "readonly", void 0);
__decorate([
    Prop()
], TreeDropdownList.prototype, "placeholder", void 0);
__decorate([
    Prop({ default: 'string' })
], TreeDropdownList.prototype, "valueType", void 0);
__decorate([
    Prop({ default: ',' })
], TreeDropdownList.prototype, "valueSeparator", void 0);
__decorate([
    Prop({ default: false })
], TreeDropdownList.prototype, "isMultiple", void 0);
TreeDropdownList = __decorate([
    Component({}),
    VueLifeCycleProcessing()
], TreeDropdownList);
export default TreeDropdownList;
