<template>
    <div v-click-outside="onClickOutside" class="selectSearchWrapper">
        <div
            :style="{ width: baseWidth || '140px' }"
            @mouseover="showIconFn"
            @mouseout="iconType = ''"
        >
            <i-input
                :maxlength="60"
                :icon="iconType"
                :placeholder="queryIfo.placeholder || ''"
                v-model="searchLabel"
                :disabled="disabled"
                @on-keyup="remoteMethod(searchLabel)"
                @on-blur="isChooseFn"
                @click.native="showSelectFn"
                @on-click="removeFn"
            >
            </i-input>
        </div>
        <div
            v-show="showSelect"
            class="ivu-select-dropdown ivu-select-dropdown-transfer"
            :style="{ width: dropdownWidth || baseWidth || '140px' }"
        >
            <ul
                v-show="selectedMultiple.length !== 0 && !loading"
                class="ivu-select-dropdown-list"
            >
                <li
                    v-for="(item, index) in selectedMultiple"
                    :key="index"
                    class="ivu-select-item"
                    :class="{ 'ivu-select-item-selected': item.select }"
                    @click="selectFn(index)"
                >
                    {{ item.label }}
                </li>
            </ul>
            <ul
                v-show="selectedMultiple.length === 0 && !loading"
                class="ivu-select-not-found"
            >
                <li @click="showSelect = false">无匹配数据</li>
            </ul>
            <ul v-show="loading" class="ivu-select-not-found">
                <li>加载中</li>
            </ul>
        </div>
    </div>
</template>
<script>
import { ESVHttpUtil } from 'esvcp-pc';

export default {
    name: 'es-select-search',
    data() {
        return {
            loading: false,
            showSelect: false,
            iconType: '',
            searchLabel: '',
            itemVal: '',
            itemLabel: '',
            selectedMultiple: []
        };
    },
    props: {
        disabled: {},
        queryIfo: {
            type: Object
        },
        baseWidth: {
            type: String
        },
        dropdownWidth: {
            type: String
        },
        defaultValue: {
            type: String
        },
        defaultKey: {},
        isDefault: {
            type: Boolean
        }
    },
    mounted() {
        let ths = this;

        ths.$nextTick(function() {
            ths.searchLabel = ths.defaultValue;
        });
    },
    watch: {
        defaultValue: function(newV, oldV) {
            let ths = this;

            if (newV) {
                // 将备用数据置为新值
                ths.itemLabel = newV;
                // 将绑定数据置为新值
                ths.searchLabel = newV;
            }
        },
        immediate: true
    },
    methods: {
        test() {
            console.log('12345');
        },
        remoteMethod(query) {
            const ths = this;
            let params = ths.queryIfo.params ? { ...ths.queryIfo.params } : {};

            params[ths.queryIfo.keywords] = query;
            if (query !== '') {
                ESVHttpUtil.post({
                    url: ths.queryIfo.url,
                    params: params,
                    beforeFn: function() {
                        ths.showSelect = true;
                        ths.loading = true;
                    },
                    completeFn: function() {
                        ths.loading = false;
                    }
                })
                    .then(res => {
                        ths.selectedMultiple = [];
                        if (res.hasOwnProperty('result') > 0) {
                            res.result.forEach(item => {
                                ths.selectedMultiple.push({
                                    label: item[ths.queryIfo.label],
                                    value: item[ths.queryIfo.value]
                                });
                            });
                        }
                    })
                    .catch(() => {});
            }
        },
        selectFn(index) {
            const ths = this;

            ths.selectedMultiple.forEach(item => {
                item.select = false;
            });

            ths.selectedMultiple[index].select = true;
            ths.searchLabel = JSON.parse(
                JSON.stringify(ths.selectedMultiple[index].label)
            );

            ths.itemLabel = ths.selectedMultiple[index].label;
            ths.itemVal = ths.selectedMultiple[index].value;
            ths.remoteMethod(ths.selectedMultiple[index].label);

            ths.showSelect = false;

            ths.$emit('selectData', ths.itemLabel);
            ths.$emit('selectData2', { value: ths.itemLabel, id: ths.itemVal });
        },
        // 如果没有选中任何值的时候，就使用备用数据
        onClickOutside(event) {
            this.showSelect = false;

            if (this.itemLabel) {
                this.searchLabel = JSON.parse(JSON.stringify(this.itemLabel));
            }
        },
        showSelectFn(event) {
            if (!this.disabled) {
                event.stopPropagation();
                this.showSelect = !this.showSelect;
            }
        },
        // 显示输入框尾部图标
        showIconFn() {
            this.iconType =
                this.searchLabel === '' || this.isDefault ? '' : 'ios-close';
        },
        isChooseFn(index) {
            const ths = this;

            if (!ths.selectedMultiple[index]) {
                ths.searchLabel = '';
            }
        },
        resetFn(event) {
            // let ths = this;

            this.searchLabel = '';
            this.itemVal = '';
            this.itemLabel = '';
            this.iconType = '';
            this.selectedMultiple = [];
            this.showSelect = false;
            this.loading = false;
            this.$emit('selectData', this.searchLabel);
            if (event) {
                event.stopPropagation();
            }
        },
        removeFn(event) {
            this.searchLabel = '';
            this.$emit('selectData', this.searchLabel);
        }
    }
};
</script>
<style lang="scss">
.selectSearchWrapper {
    position: relative;
    .ivu-select-dropdown {
        position: absolute;
        top: 28px;
        left: 0;
    }
    .ivu-select-not-found li {
        height: 19px;
        line-height: 19px;
        font-size: 14px;
    }
}
</style>
