<template>
    <div :class="'el-input-tag input-tag-wrapper' [size ? 'el-input-tag--' + size : '']">
        <div class="selectOfficeBox">
            <el-tag
                style="margin:7px 5px 7px 5px;"
                v-for="(office, officeIndex) in selectData"
                :key="office.id"
                :closable="!readonly && !disabled"
                :disable-transitions="false"
                size="small"
                type="info"
                @close="handleOfficeRemove(officeIndex)">
                {{ office.name }}
            </el-tag>
            <el-autocomplete ref="officeSelect"
                             v-if="!readonly && !disabled"
                             v-model="name"
                             style="width: 220px"
                             placeholder="点击选择部门"
                             :fetch-suggestions="handleOfficeSearch"
                             @select="handleOfficeSelect">
            </el-autocomplete>
            <el-button class="selectOfficeButton" :disabled="disabled" :readonly="readonly" @click="showOfficeSelect" icon="el-icon-search"></el-button>
        </div>
        <office-select-dialog ref="officeSelectDialog" :limit="limit" @confirmSelect="confirmDialogSelect" :selectData="selectData" :checkSelectable="checkSelectable"></office-select-dialog>
    </div>
</template>
<script>
import OfficeSelectDialog from './OfficeSelectDialog'

export default {
    data() {
        return {
            name: '',         // 搜索框关键字
            searchOfficeList: [],       // 搜索框用户列表
            selectData: [],      // 已选中的用户, 由props传递的value, watch生成数组
            selectDataMap: {}, // 已选中的用户id作为key, true作为value的map对象, 用于判断本次新增选择的用户是否已经被选中
            allOfficeTreeList: []
        }
    },
    props: {
        limit: {            // 人数限制
            type: Number,
            default: 0
        },
        value: String | Array,  // 已选中的人员ids
        offices: Array,      // 已选中的人员
        size: String,   // 输入框长度
        readonly: {     // 是否只读, 默认不只读
            type: Boolean,
            default: () => {
                return false
            }
        },
        disabled: {     // 是否禁用, 默认不禁用
            type: Boolean,
            default: () => {
                return false
            }
        },
        checkSelectable: ''  //禁止选中人id
    },
    components: {
        OfficeSelectDialog
    },
    created() {
        if (!this.readonly) {
            this.refreshContactOfficeList()
        }
    },
    watch: {
        value: {
            handler(ids) {
                if (ids && ids.length > 0) {
                    if (this.offices && this.offices.length === ids.split(',').length) {
                        // this.handleOfficeChange(this.offices)
                    } else {
                        this.$http.get(`/sys/office/queryByIds?ids=${ids}`).then(({data}) => {
                            if (data.success && data.offices && data.offices.length > 0) {
                                this.handleOfficeChange(data.offices)
                            }
                        })
                    }
                } else {
                    this.selectData = []
                }
            },
            immediate: true,
            deep: false
        },
        selectData: {
            handler(offices) {
                // 选中项有变更时, 同步更新选中项Map对象
                if (offices && offices.length > 0) {
                    this.selectDataMap = []
                    offices.forEach(office => {
                        this.selectDataMap[office.id] = true
                    })
                }
            },
            immediate: true,
            deep: false
        }
    },
    methods: {
        // 近期联系人
        refreshContactOfficeList() {
            this.$http({
                url: '/sys/contact/office/list',
                method: 'post',
                params: {
                    'pageNo': this.pageNo,
                    'pageSize': -1
                }
            }).then(({data}) => {
                if (data && data.success) {
                    this.searchOfficeList = data.page.list.map(office => {
                        return {
                            value: office.name || office.loginName,
                            ...office
                        }
                    })
                } else {
                    return []
                }
            })
        },
        refreshAllOfficeTree() {
            this.$http({
                url: `/sys/office/treeData`,
                method: 'get',
                params: {
                    name: this.searchOfficeName
                }
            }).then(({data}) => {
                if (data && data.success) {
                    this.allOfficeTreeList = data.treeData
                }
            }).catch(() => {
            })
        },
        dataChange(data) {
            let obj = []
            let nums = data.length
            for (var i = 0; i < nums; i++) {
                if (data[i].id === this.parentId) {
                    obj.push(data[i])
                    return obj
                } else {
                    if (data[i].children !== undefined) {
                        obj = this.dataChange(data[i].children)
                        if (obj.length > 0) {
                            obj.push(data[i])
                        }
                    }
                }
                if (i === nums - 1) {
                    return obj
                }
            }
        },
        // 删除标签
        handleOfficeRemove(index) {
            this.selectData.splice(index, 1)
            this.doSubmit()
        },
        // 搜索框候选项列表变更
        // 搜索框过滤结果
        handleOfficeSearch(name, cb) {
            // 拆分输入项
            let letters = []
            if (name && name.length > 0) {
                letters = name.split('')
            }
            // 对结果进行过滤
            let result = this.searchOfficeList.filter(office => {
                // 拼音首字母过滤
                let letterMatch = true
                letters.forEach(letter => {
                    // 用户设置了拼音, 则进行过滤, 没设置拼音, 过滤失败
                    if ((office.alphabet && office.alphabet.indexOf(letter.toUpperCase()) === -1) || !office.alphabet) {
                        letterMatch = false
                    }
                })
                // 姓名过滤
                let nameMatch = true
                letters.forEach(letter => {
                    // 用户设置了拼音, 则进行过滤, 未设置拼音, 从结果中删除
                    if ((office.name && office.name.indexOf(letter.toUpperCase()) === -1) || !office.name) {
                        nameMatch = false
                    }
                })
                // 拼音和姓名任意一项过滤成功即可
                return letterMatch || nameMatch
            })
            cb(result)
        },
        // 搜索框选人
        handleOfficeSelect(selectedOffice) {
            // 选人后清空搜索框
            this.name = ''
            // 推送选中用户到主面板
            this.handleOfficeChange([selectedOffice])
            this.increaseContactOffice([selectedOffice])
        },
        // 显示用户选择面板
        showOfficeSelect() {
            if (!this.readonly && !this.disabled) {
                this.$refs.officeSelectDialog.init()
            }
        },
        // 清空已选人员信息
        clearSelectedOffices() {
            this.selectData = []
            this.selectDataMap = {}
        },
        // 选择面板选人
        confirmDialogSelect(offices) {
            this.clearSelectedOffices()
            this.handleOfficeChange(offices)
            this.increaseContactOffice(offices)
        },
        // 确认选人
        handleOfficeChange(offices) {
            // 判断本次选择的用户是否在集合中, 如果在则跳过, 否则加入到选中项内
            if (!offices || offices.bufLength === 0) {
                return
            }
            if (this.selectData.length > 0 && this.limit) {
                let officesIds = offices.map((item) => {
                    return item.id
                })
                for (let i in this.selectData) {
                    if (officesIds.join(',').indexOf(this.selectData[i].id) !== -1) {
                        this.selectData.splice(i, 1)
                    }
                }
            }
            // 判断当前users是否在selectData中
            if (this.selectData && this.limit && this.selectData.length === this.limit) {
                this.$message({
                    showClose: true,
                    message: `你最多只能选择${this.limit}个单位！`,
                    type: 'warning'
                })
                return
            }
            offices.forEach(office => {
                if (this.selectData.length === 0 || !this.selectDataMap[office.id]) {
                    this.selectData.push(office)
                }
            })
            this.doSubmit()
        },
        increaseContactOffice(offices) {
            // 通讯录热点+1
            this.$http({
                url: '/sys/contact/office/increase',
                method: 'get',
                params: {
                    'ids': offices.map(data => {
                        return data.id
                    }).join(',')
                }
            }).then(({data}) => {
                if (data && data.success) {
                }
            })
        },
        doSubmit() {
            // 返回新选择的用户信息
            this.$emit('getValue', this.selectData, this.selectData.map(offices => offices.id), this.selectData.map(offices => offices.name))
            // this.$refs.officeSelect.focus()
        }
    }
}
</script>
<style scoped lang="scss">
.selectOfficeBox {
    display: flex;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    position: relative;
    padding: 0 45px 0 5px;
    min-height: 36px;
    flex-wrap: wrap;
    
    .selectOfficeButton {
        position: absolute;
        width: 40px;
        height: 100%;
        right: 0;
        top: 0;
        border: none;
        border-left: 1px solid #dcdfe6;
        background: #f5f7fa;
        border-radius: 0px;
        text-align: center;
        padding: 0;
    }
    
    .el-input__inner {
        max-width: 100%;
        min-width: 60px;
        border: none !important;
    }
   
}
</style>
<style lang="scss">
.selectOfficeBox .el-tag.el-tag--info .el-tag__close{
    color: #909399 !important;
    &:hover{
        color: #fff !important;
    }
}
.el-form-item__content .el-input-group {
    vertical-align: middle;
}
.selectOfficeBox .el-input.is-disabled .el-input__inner{
    background-color: #fff !important;
}

.selectOfficeBox{
    .el-input__inner{
        max-width: 100%;
        min-width: 60px;
        border:none !important;
    }
}
</style>

