<template>
 <div v-show="myConfig.visible" :class="classes" >
    <template v-if="multiple">
        <div  ref="myControl" class="ivu-select-selection">
            <template  v-for="(item, index) in selectedMultiple" >
            <div
                class="ivu-tag ivu-tag-checked"
                :key="'tag_'+index"
                v-if="myConfig.maxTagCount === undefined || index < myConfig.maxTagCount">
                <span class="ivu-tag-text" >{{ item.label}}</span>
                <Icon type="ios-close" v-if="!myConfig.readOnly" @click.enter.stop="closeTag(item)"></Icon>
            </div>
            </template>
            <Tooltip  theme="light" :transfer="true">
                <div class="ivu-tag ivu-tag-checked" v-if="myConfig.maxTagCount !== undefined && selectedMultiple.length > myConfig.maxTagCount">
                    <span class="ivu-tag-text ivu-select-max-tag">
                        + {{ selectedMultiple.length - myConfig.maxTagCount }}...
                    </span>
                </div>
                <template #content>
                <Row type="flex">
                    <template v-for="(item, index) in selectedMultiple">
                    <Col
                        class="ivu-tag ivu-tag-checked"
                        :key="'tag_'+index"
                        v-if="myConfig.maxTagCount === undefined || index >= myConfig.maxTagCount">
                        <span class="ivu-tag-text" >{{ item.label}}</span>
                        <Icon type="ios-close" v-if="!myConfig.readOnly" @click.enter.stop="closeTag(item)"></Icon>
                    </Col>
                    </template>
                </Row>
                </template>
           </Tooltip>
           <Icon type="ios-search" class="ivu-select-arrow"    @click.enter.stop="click"></Icon>
        </div>
    </template>
    <template v-else>
          <Input  ref="myControl" v-model="text" icon="ios-search" :size="myConfig.size" type="text" :placeholder="myConfig.placeholder"  :disabled="myConfig.readOnly" :readonly="!myConfig.allowInput" :clearable="myConfig.clearable" @on-click="click"  @keydown.enter.stop="onEnter"  @on-blur="onEnter"  @on-clear="onEnter"/>
    </template>
    <Modal v-model="popShow" :styles="queryConfig.popStyle" :width="currentWidth" :title="modeTitle" :footer-hide="footerHide" :draggable="draggable" :closable="myConfig.closable" class="efuture-model" >
        <div>
        <component :is="pop" ref="popView" :config="queryConfig" :dictData="myConfig.dictData"  @conditionAction="conditionAction" :isPop="true" @dbclick="dbclick"/></div>
        <template #footer>
        <div>
             <Row type="flex" justify="end" align="middle"  :gutter="0">
                <Col>
                    <Button style="width:80px" @click="cancel" >取消</Button>
                </Col>
                <Col style="margin-left:20px">
                    <Button  type="info" style="width:80px" @click="ok" >确认</Button>
                </Col>
            </Row>
        </div>
        </template>

    </Modal>
</div>
</template>
<script>
    import Base from '@/components/base/controlbase.vue';
    export default {
        name: 'poptextbox',
        extends: Base,
        data () {
            return {
                myConfig: {
                    isTree:false,
                    textName:'',
                    selectkey:'',
                    searchBefore:'',
                    setDataBefore:'',
                    closable:true,
                    allowInput:true,
                    clearCondition:true,
                    multiple: false,
                    popControl:'',
                    maxTagCount: 2,
                    dictData:{}
                },
                selectedMultiple:[],
                queryConfig:{
                    popStyle:{
                        top:'20px'
                    }
                },
                multiple:false,
                popShow:false,
                footerHide:false,
                text:'',
                oldText:'',
                oldValue:'',
                data:[],
                selectTreeData:[],
                customRows:[],
                draggable:false
            };
        },
        props:{
            fatherValue: {
                type: [String,Array],
                default:''
            },
            fatherText: {
                type: [String,Array],
                default:''
            }
        } ,
        computed: {
            pop () {
                if (this.queryConfig.popControl) {
                    return this.queryConfig.popControl;
                } else {
                    if (this.queryConfig.isTree) {
                        return 'TreeBox';
                    } else {
                        return 'ViewGrid';
                    }
                }
            },
            classes () {
                if (!this.multiple) {
                    return '';
                } else {
                    if (!this.myConfig.readOnly) {
                        return 'vu-select ivu-select-multiple ivu-select-default';
                    } else {
                        return 'vu-select ivu-select-disabled ivu-select-multiple ivu-select-default';
                    }
                }
            },
            modeTitle() {
                let title = this.config.label;
                if (this.queryConfig.title) {
                    title = this.queryConfig.title;
                }
                if (this.myConfig.curlTitle) {
                    title = this.myConfig.curlTitle
                }
                return title;
            }
        },
        methods:{
            conditionAction(temp) {
                switch(temp.action) {
                    case 'condition_ok':
                        if (temp.rows) {
                            this.customRows = [];
                            let flag = true;
                            if (temp.rows.length === 0) {
                                this.$refs.popView.alert('请选择');
                                this.popShow = true;
                                return true;
                            }
                            if (this.queryConfig.isTree) {
                                let allowLastNode  = this.queryConfig.allowLastNode;
                                if (this.config.allowLastNode !== undefined) {
                                    allowLastNode  = this.config.allowLastNode;
                                }
                                if (allowLastNode) {
                                    temp.rows.some(el => {
                                        if (this.$refs.popView.isChildren(el)) {
                                            flag = false;
                                            return true;
                                        }
                                    });
                                }
                                if (!flag) {
                                    this.$refs.popView.alert('选中的节点存在非末级节点，请检查');
                                    this.popShow = true;
                                } else {
                                    if (allowLastNode === true) {
                                        let rows = [];
                                        temp.rows.forEach(el => {
                                            if (!el.children || el.children.length === 0) {
                                                rows.push(el);
                                            }
                                        });
                                        this.setCommmonValue(rows);
                                    } else {
                                        this.setCommmonValue(temp.rows);
                                    }
                                    this.popShow = false;
                                }
                            } else {
                                this.setCommmonValue(temp.rows);
                                this.popShow = false;
                            }
                        }

                        break;
                    case 'condition_cancel':
                        this.popShow = false;
                        break;
                }
                if (!this.popShow) {
                    document.querySelector('body').removeAttribute("style");
                }
            },
            overrideSearchParam (param) {
                if (this.myConfig.overrideSearchParam) {
                    return this.myConfig.overrideSearchParam(param);
                } else {
                    return param;
                }
            },
            setCommmonValue(rows,isnull) {
                let flag = true;
                //对象转数组
                if (!Array.isArray(rows)) {
                    let data = [];
                    data.push(rows);
                    rows = data;
                }
                if (this.myConfig.setDataBefore) {
                    if (isnull === 'Y') {
                        flag = this.myConfig.setDataBefore(null,this);
                    } else {
                        flag = this.myConfig.setDataBefore(rows,this);
                    }
                }
                if (flag) {
                    if (this.multiple) {
                        let value = [];
                        let text = [];
                        rows.forEach(el => {
                            let temp = this.getCodeName(el);
                            el.label = temp.name;
                            value.push(el[this.queryConfig.responseId]);
                            text.push(temp.name);
                        });
                        this.value = value;
                        this.text = text;
                        this.oldValue = this.$Method.copy(value);
                        this.oldText = this.$Method.copy(text);
                    } else {
                        //多选自定义设置
                        if (this.customRows && this.customRows.length > 0) {
                            rows = this.customRows;
                        }
                        let temp = this.getCodeName(rows[0]);
                        if (rows[0][this.queryConfig.responseId]) {
                            this.value = rows[0][this.queryConfig.responseId];
                            this.text = temp.name;
                        } else {
                            this.value ='';
                            this.text = '';

                        }
                        this.oldValue = this.value;
                        this.oldText = this.text;
                    }
                    this.setFatherValue();
                } else {
                    if (this.multiple) {
                        this.value =this.$Method.copy(this.oldValue);
                        this.text = this.$Method.copy(this.oldText);
                    } else {
                        this.value = this.oldText;
                        this.text = this.oldText;
                    }
                }
            },
            getCodeName(row) {
                let code = row[this.queryConfig.responseCode];
                let name = row[this.queryConfig.responseName];
                if (this.queryConfig.showCodeWithName !== false) {
                    if (this.queryConfig.responseCode != this.queryConfig.responseName) {
                        if (code) {
                            if (name) {
                                name =  '[' + code +']' + name;
                            } else {
                                name = code;
                            }
                        } else {
                            name = '';
                        }
                    }
                } else {
                    if (code) {
                        if (!name) {
                            name = code;
                        }
                    } else {
                        name = '';
                    }
                }
                let obj = {};
                obj.code = code;
                obj.name = name;
                return obj;
            },
            setFatherValue() {
                let para = this.valueToFatherValue();
                para.name = this.myConfig.name;
                if (this.myConfig.textName !== undefined) {
                    para.textName = this.myConfig.textName;
                }
                if (!this.multiple) {
                    if (this.customRows && this.customRows.length > 0) {
                        para.customRows = this.customRows;
                    }
                }
                this.$emit('inputValue', para);
            },
            closeTag(item) {
                let index = this.value.findIndex(el => el === item[this.queryConfig.responseId]);
                let flag = true;
                let that = this;
                if (this.myConfig.onDelTag) {
                    let temp = {};
                    temp.delIndex = index;
                    temp.data = this.$Method.copy(this.value);
                    temp.control = that;
                    temp.name =  this.myConfig.name;
                    flag = this.myConfig.onDelTag(temp);
                }
                if (flag) {
                    if (index > -1) {
                        this.value.splice(index, 1);
                        this.text.splice(index, 1);
                        this.selectedMultiple.splice(index,1);
                        this.setFatherValue();
                        this.oldValue = this.$Method.copy(this.value);
                        this.oldText = this.$Method.copy(this.text);
                    }
                }
            },
            customInit () {
                if (this.config.selectkey) {
                    Object.assign(this.queryConfig, this.getQueryConfig(this.config.selectkey));
                    if (!this.queryConfig.isConfig) {
                        this.queryConfig.resources = this.OmdUrl[this.queryConfig.resources];
                    }
                    if (this.queryConfig.draggable) {
                        this.draggable = this.queryConfig.draggable;
                    }
                    if (this.config.multiSelect !== undefined) {
                        this.queryConfig.multiSelect = this.config.multiSelect;
                    }

                    if (this.config.showAll !== undefined) {
                        this.queryConfig.showAll = this.config.showAll;
                    }
                    if (this.queryConfig.popControl) {
                        if (this.queryConfig.popControl !== 'SimpleViewGrid' && this.queryConfig.popControl !== 'SimpleTree') {
                            this.footerHide = true;
                        }
                    }
                    this.setSizeConfig(this.queryConfig);
                    this.queryConfig.overrideSearchParam = this.overrideSearchParam;

                    if (JSON.stringify(this.myConfig.dictData) === '{}') {
                        let obj = {};
                        if (this.queryConfig.items && this.queryConfig.items.length > 0) {
                            this.queryConfig.items.forEach(el => {
                                let dictkey = el.dictkey;
                                if (el.customDictkey) {
                                    dictkey = el.customDictkey;
                                }
                                if (dictkey) {
                                    obj[dictkey] = '';
                                }
                            });
                        }
                        if (JSON.stringify(obj) !== '{}') {
                            if (this.myConfig.getDictData) {
                                obj = this.myConfig.getDictData(obj);
                            }
                            this.myConfig.dictData = obj;
                        }
                    }
                    if (this.myConfig.sysDictData !== undefined) {
                        if (this.myConfig.dictData === undefined) {
                            this.myConfig.dictData = {};
                        }
                        this.myConfig.dictData = Object.assign({}, this.myConfig.sysDictData, this.myConfig.dictData);
                    }
                    if (this.myConfig.multiple) {
                        this.multiple = true;
                    }

                    if(this.queryConfig.isTree) {
                        this.queryConfig.showTitle = false;
                    }

                    if (this.myConfig.setQueryConfig) {
                        this.myConfig.setQueryConfig(this.queryConfig);
                    }
                }

            },
            valueToFatherValue() {
                let para= {};
                if (!this.value || this.value.length === 0) {
                    if (this.multiple) {
                        this.text = [];
                        this.oldText = [];
                    } else {
                        this.value = '';
                        this.text = '';
                    }
                } else {
                    para.value = this.value;
                    para.text  = this.text;
                }
                return para;
            },
            click(){
                let flag = true;
                if (!this.queryConfig.isTree) {
                    if (this.$refs.popView.$children && this.$refs.popView.$children.length > 0) {
                        if (this.$refs.popView.$children[0].customClear) {
                            this.$refs.popView.$children[0].customClear();
                        }
                        this.$refs.popView.clearData();
                    }
                }
                if (this.myConfig.readOnly) {
                    return;
                }
                if (this.myConfig.searchBefore) {
                    this.$refs['popView'].clearSearchBeforeSearchParam();
                    flag = this.myConfig.searchBefore(this,this.$refs['popView']);
                    if (flag) {
                        if (this.searchParam !== undefined) {
                            this.$refs['popView'].setSearchBeforeSearchParam(this.searchParam);
                        }
                    }
                }
                if (flag) {
                    if (this.config.selectkey) {
                        if(this.query && this.query.Config ) {
                            const lastParam = this.query.Config.lastQueryParam;
                            if (this.queryConfig) {
                                const lastParam = this.query.Config.lastQueryParam || {};  // 始终记住前一次的参数
                                const currentParam = this.searchParam || {};               // 当前的参数

                                let finalParam = currentParam;

                                // 只有 lastflag = "1" 时才合并记录的旧参数
                                if (currentParam.lastflag === "1") {
                                    finalParam = { ...lastParam, ...currentParam };  // 当前参数优先覆盖旧参数
                                }

                                // 无论是否合并，都要记录当前的最终 searchParam 作为下一次的 lastQueryParam
                                this.query.Config.lastQueryParam = { ...finalParam };

                                // 更新 this.searchParam
                                this.searchParam = finalParam;

                                // 传递给 popView
                                this.$refs['popView'].setSearchBeforeSearchParam(this.searchParam);
                            }
                        }
                        this.popShow = true;
                        if (this.myConfig.clearCondition !== false) {
                            if (this.$refs['popView'].clearCondition) {
                                this.$refs['popView'].clearCondition();
                            }
                        }
                        if (this.queryConfig.manualLoad) {
                            this.$refs['popView'].refurbish();
                        } else {
                            this.$refs['popView'].setData([]);
                        }

                    }
                }
            },
            onEnter(e) {
                if (this.text === this.oldText) {
                    if (e && e.type ==='keydown' && e.key === 'Enter') {
                        if (this.$parent.enterKeyDown) {
                             this.$parent.enterKeyDown();
                        }
                    }
                    return;
                }
                let obj ={};
                let flag = true;
                let searchParam = {};
                if (this.myConfig.searchBefore) {
                    this.$refs['popView'].clearSearchBeforeSearchParam();
                    obj.value = this.text;
                    flag = this.myConfig.searchBefore(this,obj);
                }
                if (flag) {
                     if (!this.text) {
                        this.value = '';
                        this.oldValue='';
                        this.oldText='';
                        this.text = '';
                        if (this.myConfig.setDataBefore) {
                            this.myConfig.setDataBefore(null, this);
                        }
                        this.setFatherValue();
                         return;
                    }
                    if (this.searchParam !== undefined) {
                        this.$refs['popView'].setSearchBeforeSearchParam(this.searchParam);
                    }
                    searchParam[this.queryConfig.responseCode] =  this.text;
                    let data = this.$refs['popView'].popValueChanged(searchParam);
                    if (data.length  === 0) {
                        this.alert(this.myConfig.label+':['+this.text+']不存在！');
                        this.text = this.oldText;
                    } else {
                        this.setCommmonValue(data[0]);
                        if (e && e.type ==='keydown' && e.key === 'Enter') {
                            if (this.$parent.enterKeyDown) {
                                this.$parent.enterKeyDown();
                            }
                        }
                    }
                } else {
                    this.text = this.oldText;
                }

            },
            onSelectChange() {
                return this.$refs.myTreeBox.onSelectChange();
            },
            onCheckChange(param) {
                this.selectTreeData=param;
                let mktNameArray=[];
                param.forEach(el => {
                    mktNameArray.push(el.name);
                });
                let mktname=mktNameArray.join(',');
                this.text=mktname;
            },

            onToggleExpand() {
                return this.$refs.myTreeBox.onToggleExpand();
            },

            setData(data) {
                if (this.$refs.popView) {
                    this.$refs.popView.setData(data);
                }
            },
            dbclick(e) {
                let temp = {};
                temp.action= 'condition_ok';
                temp.rows = [];
                temp.rows.push(e);
                this.conditionAction(temp);
            },
            ok() {
                let temp = {};
                temp.action= 'condition_ok';
                temp.rows = this.$refs.popView.getSelection();
                this.conditionAction(temp);
            },
            watchCustomFatherValue () {
                if (!this.value) {
                    if (!this.multiple) {
                        this.text = '';
                        this.OldText = '';
                    } else {
                        this.text = [];
                        this.OldText = [];
                        this.selectedMultiple = [];
                    }
                }
            },
            setFocus(value) {
                if (value) {
                    this.$refs.myControl.focus();
                } else {
                    this.$refs.myControl.blur();
                }
            },
            initSlectedMultiple () {
                let selectedMultiple = [];
                if (this.value.length > 0) {
                    this.value.forEach((el,index) => {
                        let temp  = {};
                        temp[this.queryConfig.responseId] = el;
                        if (this.text && index < this.text.length) {
                            temp.label = this.text[index];
                        } else {
                            temp.label = el;
                        }
                        selectedMultiple.push(temp);
                    });
                }
                this.selectedMultiple = selectedMultiple;
            },
            cancel() {
                this.popShow = false;
            },
            onEnter2(e) {
                this.alert('1');
            }
        },
        mounted() {
            //this._setCustomWidth(this.clientWidth);
        },
        watch:{
            fatherText: {
                handler(newValue)  {
                    this.text = newValue;
                    this.oldText = this.$Method.copy(newValue);
                    if (this.config.multiple) {
                        this.$nextTick(() => {
                            this.initSlectedMultiple();
                        });
                    }
                },
                immediate: true
            },
            popShow:{
                handler(newValue)  {
                    if (this.config.onOpenChange) {
                        this.config.onOpenChange(newValue);
                    }
                },
                immediate: true
            }
        }

    };
</script>
