<template>
    <div>
        <el-dropdown trigger="click" ref="dropdown" :style="'width:'+width+';' "  class="multiDropDown">
            <div>
                <el-tag
                    class="select-tag"
                    :key="tag"
                    v-for="tag in tagList"
                    :closable="closeTag"
                    :disable-transitions="false"
                    @close="handleClose(tag)">
                    {{tag}}
                </el-tag>
                <el-input v-model="selectLabel" :clearable="clearable"
                          :size="size"
                          :placeholder="placeholder" @keyup.native="searchEvent" @change="isEmpty" @focus="focusEvent"
                          @clear="clearValue"
                >
                </el-input>
            </div>
            <el-dropdown-menu slot="dropdown">
                <el-table
                    ref="dropDownTable"
                    :data="tableData"
                    @selection-change="handleSelectionChange"
                    @row-click="rowClick"
                    size="mini"
                    max-height="250"
                    highlight-current-row
                    :row-key="getRowKey"
                    v-loading="loading"
                >
                    <el-table-column
                        type="selection"
                        :reserve-selection="true"
                        width="60"
                        align="center"
                    />
                    <el-table-column v-for="(column,index) in tableColumn" :key="index"
                                     show-overflow-tooltip
                                     :width="column.width"
                                     :label="column.title"
                                     :prop="column.field"
                                     :align="column.align"
                    >
                    </el-table-column>
                </el-table>
                <!--分页-->
                <pagination
                    v-show="tablePage.total>0"
                    :total="tablePage.total"
                    :layout="layout"
                    :page.sync="tablePage.currentPage"
                    :limit.sync="tablePage.pageSize"
                    @pagination="findList"
                />
            </el-dropdown-menu>
        </el-dropdown>
    </div>
</template>

<script>
import XEUtils from 'xe-utils'

export default {
    name: "MultiSelectTable",
    props: {
        closeTag:{
          default: false
        },
        value: {
            required: true,
        },
        data: {
            type: Array,
            desc: '所有数据'
        },
        tableColumn: {
            type: Array,
            desc: '表格列'
        },
        label: {
            type: String,
            desc: '回显标签(当后端数据量过大时，可以先传递标签回显。)'
        },
        width: {
            type: String,
            default: 'auto',
            desc: '输入框宽度'
        },
        size: {
            type: String,
            desc: '输入框大小'
        },
        labelField: {
            type: String,
            default: 'name',
            desc: '回显标签,字段名。'
        },
        valueField: {
            type: String,
            default: 'code',
            desc: '回显值,字段名。'
        },
        placeholder: {
            type: String,
            default: '请输入关键字',
            desc: '占位符'
        },
        trigger:{
            type: Boolean,
            default: false,
            desc: '是否触发多次change事件。默认修改后触发一次回显不在触发，可按需求开启。'
        },
        disabled: Boolean,
        clearable: Boolean,
        //分页参数
        layout: String,
        pageSize: Number,
        currentPage: Number,
    },
    data() {
        return {
            //选中的值的（id主键）
            selectVal: undefined,
            //选中的值的标签
            selectLabel: undefined,
            //表格当前的数据
            tableData: [],
            //和关键字匹配的数据
            filterData: [],
            //分页参数
            tablePage: {
                total: 0,
                currentPage: 1,
                pageSize: 5
            },
            //标签数组
            tagList:[],
            //选中的行
            selectedRows:[],
            loading: true,//加载
        };
    },
    computed: {},
    watch: {
        data: {
            deep: true,
            immediate: true,
            handler(val) {
                //该方法，只有在data发生改变时才触发。此处会被执行两次第一次没值,第二次才有值
                if (val && val.length > 0) {
                    //data有值,搜索。
                    this.loading = false
                    if (this.tableData && this.tableData.length > 0) {
                        //不是第一次
                        this.searchEvent();
                        this.setCurrentRowBySelectVal();
                    } else {
                        //第一次调用组件，并得到数据。
                        // setTimeout(()=>{
                        //     this.firstEntry()
                        // },5000)
                        this.firstEntry();
                        this.findList();
                    }
                }else{
                    this.loading = false
                }
            },
        },
        value: {
            handler(val) {
                //如果值为空则把label也置空。
                if (this.$isNull(val)) {
                    this.selectLabel = undefined;
                    this.selectVal = undefined;
                } else {
                    this.$nextTick(() => {
                        this.selectVal = val;
                        // this.firstEntry()
                    })
                    // this.selectVal = val;
                    if (this.label) {
                        this.selectLabel = this.label
                    }
                }
            },
            immediate: true,
        },
    },

    created() {
    },
    mounted() {},
    methods: {
        getRowKey(){
           let key = Math.random()
            return key
        },
        rowClick(row) {
            this.$refs.dropDownTable.toggleRowSelection(row)
        },
        setCurrentRowBySelectVal() {
            if (this.selectVal) {
                //得到所有列。
                const searchProps = [];
                this.tableColumn.forEach(value => {
                    searchProps.push(value.field)
                })
                //查找值对应的下标
                if (this.tableData && this.tableData.length > 0) {
                    let index = this.tableData.findIndex(value => searchProps.some(key => value[key] == this.selectVal))
                    if (index > -1) {
                        this.selectLabel = this.tableData[index][this.labelField]
                        this.$nextTick(() => {
                            if (this.$refs.dropDownTable) {
                                this.$refs.dropDownTable.setCurrentRow(this.tableData[index])
                            }
                        })
                    }
                }
            }
        },
        //第一次进入
        firstEntry() {
            if (this.data.length > 0) {
                //初始化表格数据
                this.filterData = this.data;
            }
            if (this.selectVal) {
                //得到所有列。
                const searchProps = [];
                //获取选中对像
                const selectItems=[];
                // this.tableColumn.forEach(value => {
                //     searchProps.push(value.field)
                // })
                searchProps.push(this.valueField)
                //查找第一次传入的值对应的页
                let tempVal = this.selectVal.split(',')
                if(this.data.length > 0){
                    tempVal.forEach((item) =>{
                        let index = this.data.findIndex(value => searchProps.some(key => value[key] == item))
                        this.tagList.push(this.data[index][this.labelField])
                        this.data.forEach((item2,i)=>{
                           if(i === index){
                               selectItems.push(item2);
                               this.$refs.dropDownTable.toggleRowSelection(item2,true)
                           }
                        })
                    })
                }
                /**可以根据需求开启触发。默认不触发**/
                if (this.trigger) {
                    this.$emit("changeRow", selectItems);
                    this.$emit("change", this.valueField);
                }
            }
        },
        //聚焦输入框事件
        isEmpty(val) {
            if(val == ''){
                this.clearValue()
            }
        },
        focusEvent(){
            if(!this.selectVal){
                this.$refs.dropDownTable.setCurrentRow()
            }
            this.filterData = this.data
            this.findList()
        },
        //搜索框，触发方法
        searchEvent () {
            if(!this.data){
                return ;
            }
            if(this.$isNotNull(this.selectLabel)){
                //转小写，去空格
                const filterName = XEUtils.toValueString(this.selectLabel).trim().toLowerCase()
                //得到所有列。
                const searchProps = [];
                this.tableColumn.forEach(value => {
                    searchProps.push(value.field)
                })
                //双重循环遍历所有数据得到匹配的行。
                const rest = this.data.filter(item => searchProps.some(key => XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) > -1))
                this.filterData = rest;
            } else {
                this.filterData = this.data;
            }
            this.initTablePage()
            this.findList();
        },
        //清空传回undenfined
        clearValue(val){
            this.selectVal = val
            this.$refs.dropDownTable.setCurrentRow()
            this.$emit("change", val);
        },
        suffixClick() {
            this.$refs.dropdown.togglePanel()
        },
        //多选行，触发事件
        handleSelectionChange(rows){
            if(!rows){
                return;
            }
            this.selectedRows = rows
            const selectedLabel = []
            const selectedValue = []
            if(this.labelField){
                rows.forEach((item)=>{
                    selectedLabel.push(item[this.labelField])
                    selectedValue.push(item[this.valueField])
                })
                this.selectLabel = undefined
                this.selectVal = selectedValue.join(",")
                this.tagList = selectedLabel
                this.$emit("changeRow", rows);
                this.$emit("change", this.selectVal);
            }
        },
        handleClose(tag) {
            this.selectedRows.forEach((row)=>{
                if(row.nickName === tag){
                    this.$refs.dropDownTable.toggleRowSelection(row,false)
                }
            })
            this.$emit("change",this.selectVal)
        },
        //分页查询列表
        findList() {
            if (this.filterData) {
                this.tablePage.total = this.filterData.length
                this.tableData = this.filterData.slice((this.tablePage.currentPage - 1) * this.tablePage.pageSize, this.tablePage.currentPage * this.tablePage.pageSize)
            }
        },
        //初始化分页参数
        initTablePage() {
            this.tablePage = {
                total: 0,
                currentPage: 1,
                pageSize: 5
            }
        },

    }
}
</script>

<style scoped>
.my-dropdown {
    z-index: 1000;
    background-color: #fff;
    box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
}

.keyword-lighten {
    color: #000;
    background-color: #FFFF00;
}
.el-dropdown-menu{
    padding:20px;
}
/deep/.el-table tr{
    height: 5px!important;
}
/deep/.pagination-container{
    height:40px;
    box-shadow: none;
}
/deep/.el-input__inner{
    background-color: rgba(255,255,255,0);
    border:none;
}
/deep/.el-table__header, /deep/.el-table__body, /deep/.el-table__footer{
    width:550px!important;
}
.multiDropDown  .el-dropdown-selfdefine {
    display: flex;
    flex-wrap: wrap;
    background:#fff;
    align-items: center;
    border:1px solid #DCDFE6;
    border-radius: 4px;
    box-sizing: border-box;
}
.select-tag{
    margin: 2px 0 2px 6px;
}
</style>
