<template>
    <div :class="'el-input-tag input-tag-wrapper' [size ? 'el-input-tag--' + size : '']">
        <div class="selectUserBox">
            <el-tag
                style="margin:7px 5px 7px 5px;"
                v-for="(user, userIndex) in selectData"
                :key="user.id"
                :closable="!readonly && !disabled"
                :disable-transitions="false"
                :size="tagSize"
                type="info"
                @close="handleUserRemove(userIndex)">
                {{ user.name }}
            </el-tag>
            <el-autocomplete ref="userSelect"
                             v-if="showSelect && !readonly && !disabled"
                             v-model="name"
                             :disabled="disabled"
                             placeholder="点击选择人员"
                             :fetch-suggestions="handleUserSearch"
                             @select="handleUserSelect">
            </el-autocomplete>
            <el-button class="selectUserButton" :disabled="disabled" :readonly="readonly" @click="showUserSelect" icon="el-icon-search"></el-button>
        </div>
        <!-- <el-input ref="userSelect"
                        size="medium"
                        v-model="name"
                        placeholder="请选择姓名或拼音"
                        style="outline:none;border:none;"
                        clearable>
             <el-button slot="append" :disabled="disabled" :readonly="readonly" @click="showUserSelect" icon="el-icon-search"></el-button>
         </el-input>-->
        <user-select-dialog ref="userSelectDialog" @confirmSelect="confirmDialogSelect" :limit="limit" :selectData="selectData" :checkSelectable="checkSelectable"></user-select-dialog>
    </div>
</template>
<script>
import UserSelectDialog from './UserSelectDialog'

export default {
    data() {
        return {
            name: '',         // 搜索框关键字
            searchUserList: [],       // 搜索框用户列表
            selectData: [],      // 已选中的用户, 由props传递的value, watch生成数组
            selectDataMap: {},    // 已选中的用户id作为key, true作为value的map对象, 用于判断本次新增选择的用户是否已经被选中
            isRadio: false  //如果是单选选中人员隐藏input
        }
    },
    props: {
        limit: {        // 人数限制
            type: Number,
            default: 0
        },
        value: String,  // 已选中的人员ids
        users: Array,      // 已选中的人员
        size: String,   // 输入框长度
        readonly: {     // 是否只读, 默认不只读
            type: Boolean,
            default: () => {
                return false
            }
        },
        disabled: {     // 是否禁用, 默认不禁用
            type: Boolean,
            default: () => {
                return false
            }
        },
        checkSelectable: '',  //禁止选中人id
        showSelect: {     // 是否显示热度人员快捷输入
            type: Boolean,
            default: () => {
                return true
            }
        },
        tagSize: {     // 选中人员的标签大小
            type: String,
            default: () => {
                return 'small'
            }
        }
    },
    components: {
        UserSelectDialog
    },
    created() {
        if (!this.readonly) {
            this.refreshContactUserList()
        }
    },
    watch: {
        value: {
            handler(ids) {
                if (ids) {
                    if (this.users && this.users.length === ids.split(',').length) {
                        // this.handleUserChange(this.users)
                    } else {
                        this.$http.get(`/sys/user/queryByIds?ids=${ids}`).then(({data}) => {
                            if (data.success && data.users && data.users.length > 0) {
                                this.handleUserChange(data.users)
                            }
                        })
                    }
                } else {
                    this.selectData = []
                }
            },
            immediate: true,
            deep: false
        },
        selectData: {
            handler(users) {
                // 选中项有变更时, 同步更新选中项Map对象
                if (users && users.length > 0) {
                    this.selectDataMap = []
                    users.forEach(user => {
                        this.selectDataMap[user.id] = true
                    })
                }
            },
            immediate: true,
            deep: false
        }
    },
    methods: {
        // 近期联系人
        refreshContactUserList() {
            this.$http({
                url: '/sys/contact/user/list',
                method: 'post',
                params: {
                    'pageNo': this.pageNo,
                    'pageSize': -1
                }
            }).then(({data}) => {
                if (data && data.success) {
                    let list = data.page.list.map(user => {
                        return {
                            value: user.name || user.loginName,
                            ...user
                        }
                    })
                    //当前登录人不显示
                    list = list.filter(item => item.id !== this.$store.state.user.id)
                    this.searchUserList = list
                } else {
                    return []
                }
            })
        },
        // 删除标签
        handleUserRemove(index) {
            this.isRadio = false
            this.selectData.splice(index, 1)
            this.doSubmit()
        },
        // 搜索框过滤结果
        handleUserSearch(name, cb) {
            // 拆分输入项
            let letters = []
            if (name && name.length > 0) {
                letters = name.split('')
            }
            // 对结果进行过滤
            let result = this.searchUserList.filter(user => {
                // 拼音首字母过滤
                let letterMatch = true
                letters.forEach(letter => {
                    // 用户设置了拼音, 则进行过滤, 没设置拼音, 过滤失败
                    if ((user.alphabet && user.alphabet.indexOf(letter.toUpperCase()) === -1) || !user.alphabet) {
                        letterMatch = false
                    }
                })
                // 姓名过滤
                let nameMatch = true
                letters.forEach(letter => {
                    // 用户设置了拼音, 则进行过滤, 未设置拼音, 从结果中删除
                    if ((user.name && user.name.indexOf(letter.toUpperCase()) === -1) || !user.name) {
                        nameMatch = false
                    }
                })
                // 拼音和姓名任意一项过滤成功即可
                return letterMatch || nameMatch
            })
            cb(result)
        },
        // 搜索框选人
        handleUserSelect(selectedUser) {
            // 选人后清空搜索框
            this.name = ''
            // 推送选中用户到主面板
            this.handleUserChange([selectedUser])
            this.increaseContactUser([selectedUser])
        },
        // 显示用户选择面板
        showUserSelect() {
            if (!this.readonly && !this.disabled) {
                this.$refs.userSelectDialog.init()
            }
        },
        // 清空已选人员信息
        clearSelectedUsers() {
            this.selectData = []
            this.selectDataMap = {}
        },
        // 选择面板选人
        confirmDialogSelect(users) {
            this.clearSelectedUsers()
            this.handleUserChange(users)
            this.increaseContactUser(users)
        },
        // 确认选人
        handleUserChange(users) {
            // 判断本次选择的用户是否在集合中, 如果在则跳过, 否则加入到选中项内
            if (!users || users.bufLength === 0) {
                return
            }
            if (this.selectData.length > 0 && this.limit) {
                let usersIds = users.map((item) => {
                    return item.id
                })
                for (let i in this.selectData) {
                    if (usersIds.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
            }
            users.forEach(user => {
                if (this.selectData.length === 0 || !this.selectDataMap[user.id]) {
                    this.selectData.push(user)
                }
            })
            this.doSubmit()
        },
        increaseContactUser(users) {
            // 通讯录热点+1
            this.$http({
                url: '/sys/contact/user/increase',
                method: 'get',
                params: {
                    'ids': users.map(data => {
                        return data.id
                    }).join(',')
                }
            }).then(({data}) => {
                if (data && data.success) {
                }
            })
        },
        doSubmit() {
            // 返回新选择的用户信息
            this.$emit('getValue', this.selectData, this.selectData.map(users => users.id), this.selectData.map(users => users.name))
            // this.$refs.userSelect.focus()
        }
    }
}
</script>
<style scoped lang="scss">
.selectUserBox {
    display: flex;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    position: relative;
    padding: 0 45px 0 5px;
    min-height: 36px;
    flex-wrap: wrap;
    
    .selectUserButton {
        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">
.selectUserBox .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;
}
.selectUserBox .el-input.is-disabled .el-input__inner{
    background-color: #fff !important;
}

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


