<template>
<div style="display: inline-block;">
  <div tabindex="0" @blur="selectClihide()" style="display: inline-block;" v-if="!wxCope">
    <!-- <div :style="'width:' + selectWidth + 'px;height:' + selectHeight + 'px'" :class="classDiv ? 'select selectDiv' : 'select'" @click="selectCli" :ref="disabled ? '' : 'selectDiv'"> -->
    <div :class="disabled ? 'disabledTrue' : 'disabledFalse'" @mouseenter="moveIonDiv" @mouseleave="outIonDiv">
        <div :style="`width:${selectWidth}px;min-height:${selectHeight}px`" :class="classDiv ? 'select selectDiv' : 'select'" @click="selectCli" :ref="disabled ? '' : 'selectDiv'">
            <div v-if="!multiSelect" :style="'line-height: '+selectHeight+'px;font-size: '+selectFontSize+'px;'" :class="selectName == $t('defaultText.pleaseChoose') ? 'selecttex selecttexXuan' : 'selecttex'">
                <TranslationOpenDataText type='userName' :openid='selectName'></TranslationOpenDataText>
            </div>
            <div v-if="multiSelect" :style="'line-height: '+selectHeight+'px;margin-left: -10px'" :class="selectName == $t('defaultText.pleaseChoose') ? 'selecttex selecttexXuan' : 'selecttex'">
                <template v-if="multiSelectList.length > 0">
                    <div v-if="!tile" style="width: 100%">
                        <template v-if="!expandPersonnel">
                            <span class="all">
                                <TranslationOpenDataText type='userName' :openid='multiSelectList[0].name'></TranslationOpenDataText>
                                <i class="el-icon-error" v-if="!disabled" @click.stop="deleteMultiSelectList('-1')"></i>
                            </span>
                            <span class="all" v-if="multiSelectList.length > 1"> + {{multiSelectList.length - 1}}</span>
                        </template>
                        <template v-else>
                            <span class="all" v-for="(ueseItem, userIndex) in multiSelectList" :key="userIndex">
                                <TranslationOpenDataText type='userName' :openid='ueseItem.name'></TranslationOpenDataText>
                                <i class="el-icon-error" v-if="!disabled" @click.stop="deleteMultiSelectList('-2', userIndex)"></i>
                            </span>
                        </template>
                    </div>
                    <span v-if="tile" style="width: 100%">
                        <span class="all" style="margin-right: 6px" v-for="(items, indexs) in multiSelectList" :key="indexs">
                            <TranslationOpenDataText type='userName' :openid='items.name'></TranslationOpenDataText>
                            <span v-if="items.jobNumber" class="spanFllat">{{items.jobNumber}}</span>
                            <i class="el-icon-error" @click.stop="deleteMultiSelectList(indexs)" v-if="!disabled"></i>
                        </span>
                    </span>
                </template>
                <span v-else class="allTwo">{{$t('defaultText.pleaseChoose')}}</span>
            </div>
            <i :class=" move ? 'el-icon-arrow-down iostu iostuHover' : 'el-icon-arrow-down iostu'" v-if="!moveIon"></i>
            <i v-if="moveIon" class="el-icon-circle-close iostu" @click.stop="clearDelete"></i>
        </div>
    </div>
    <div ref="selectRefs"></div>
    <transition name="el-zoom-in-top">
      <!-- <div v-show="show" style="position: relative;z-index: 999;">  -->
      <div v-show="show" class="selectBox" :style="`width:${selecsWths}px;top:${selectTop}px;left:${selectLeft}px;`"> 
        <!-- 搜索框 -->
        <div class="searchBox" v-if="filterable" :style="`top: ${searchBoxTop}px`">
            <el-input placeholder="请输入名称搜索" size="mini" v-model="searchTex" style="width: 100%" @input="searchLick()" @focus="selectCli()"></el-input>
        </div>
        <div class="transitionBox" :style="filterable ? 'margin: 30px 0;' : ''">
            <ul class="transitionBoxUl">
                <li :class="transitionBoxLiIdx == index ? 'liHover' : ''" v-for="(item, index) in options" :key="index" @mouseover="liMouseOver(index)" @click="liClick(item, index)"> 
                    <span v-if="!multiSelect" style="width: 100%">
                        <span v-if="item.name">
                            <TranslationOpenDataText type='userName' :openid='item.name'></TranslationOpenDataText>
                        </span> 
                        <span v-if="item.auditorName">
                            <TranslationOpenDataText type='userName' :openid='item.auditorName'></TranslationOpenDataText>
                        </span>
                        <!-- {{item.name || item.auditorName}} -->
                        <span v-if="item.jobNumber" class="spanFllat">{{item.jobNumber}}</span>
                    </span>

                    <span v-if="multiSelect" style="width: 100%">
                        <span :class="item.flg ? 'hoverSpan hoverSpanHover' : 'hoverSpan'">
                            <span style="width: 100%;display: inline-block;">
                                <TranslationOpenDataText type='userName' :openid='item.name'></TranslationOpenDataText>
                                <!-- {{item.name}} -->
                                <span v-if="item.jobNumber" class="spanFllat">{{item.jobNumber}}</span>
                            </span>
                            <span v-if="item.flg"><i class="el-icon-check"></i></span>
                        </span>
                    </span>
                </li>
            </ul>
        </div>
      </div>
    </transition>
  </div>
  <div v-if="wxCope" class="waihez">
    <!-- <div @click="dianjis()">点击</div> -->
    <div :style="`width:${selectWidth}px;height:${selectHeight}px;line-height:${selectHeight}px;background:#fff`" class="select selectDandu" @click="dianjis()">
        <span v-if="!multiSelect"><TranslationOpenDataText type='userName' :openid='selectName'></TranslationOpenDataText></span>
        <!-- <span>你好</span> -->
    </div>
  </div>
</div>
</template>

<script>
export default {
    props: {
        subject:{
            type: Array
        },
        size: {
            type: String,
        },
        subjectId: {
            type: [String, Number, Array]
        },
        wxCope: {
            type: Boolean,
            default: false,
        },
        // 是否支持多选
        multiSelect: {
            type: Boolean,
            default: false
        },
        // 是否平铺 (需要 multiSelect 为 true)
        tile: {
            type: Boolean,
            default: false
        },
        // 当前页面用到的第几个
        distinction: {
            type: String,
            default: '1',
        },
        // 真对填写日报单独处理
        idx: {
            type: String
        },
        flg: {
            type: Boolean,
            default: false, // 默认值，不是填写日报
        },
        // 宽度
        widthStr: {
            type: String,
            default: false
        },
        // 剩下统一索引
        index: {
            type: String
        },
        // 是否禁用
        disabled: {
            type: Boolean,
            default: false
        },
        // 是否可清空
        clearable: {
            type: Boolean,
            default: false
        },
        // 是否可搜索
        filterable: {
            type: Boolean,
            default: false
        },
        // 其他数据
        other: {
            type: [String, Number, Boolean],
            default: false
        },
        // 是否执行到日报单独的函数
        flgs: {
            type: Boolean,
            default: false
        },
        // searchBoxTop 搜索框距离顶部的距离
        searchBoxTop: {
            type: String,
            default: '-9'
        },
        expandPersonnel: { // 多选是否展开
            type: Boolean,
            default: true
        }
    },
    components: {
        selectWidth: '150',
        selectHeight: '28'
    },
    data() {
        return {
            selectWidth: '150',
            selectHeight: '28',
            selectFontSize: '12',
            show: false, // 下拉框
            options: [], // 列表数据
            optionsCopy: [], // 列表数据复制
            transitionBoxLiIdx: '', // hover 背景色
            selectName: this.$t('defaultText.pleaseChoose'), // 显示的文字
            classDiv: false, // 获得焦点样式
            optionsOId: '', // 选中人的id
            dailyListObj: null, // 填写日报的数据
            dailyListIndex: null, // 日报点的索引
            move: false,
            moveIon: false,
            multiSelectList: [],
            searchTex: '', // 搜索文字
            cursor: '', // 搜索的标记（需传给后端）
            time: null,//防抖
            fistArrList: [], // 第一次进来的人员数组
            fistArrListOne: [], // 第一次进来的人员初始数组
            selectTop: 0,
            selectLeft: 0,
            selecsWths: 0,
        };
    },
    computed: {},
    watch: {
        subject: {
            handler(newValue, oldValue) {
                this.options = newValue
                this.optionsCopy = JSON.parse(JSON.stringify(newValue))
                if(this.flg) {
                    if(newValue) {
                        this.selectName = newValue[0].auditorName || newValue[0].name
                        this.optionsOId = newValue[0].auditorId || newValue[0].id
                    }
                }
            },
        },
        // 日报点的索引, 真对填写的日报
        idx: {
            handler(newValue, oldValue) {
                // console.log(newValue, oldValue)
                this.dailyListIndex = newValue
            },
        },
        subjectId: {
            handler(newValue, oldValue) {
                // console.log(newValue, oldValue)
                this.optionsOId = newValue
                this.multiSelectList = []
                if(!this.multiSelect) {
                    if(this.optionsOId) {
                        for(let i in this.options) {
                            if(this.options[i].userId == this.optionsOId || this.options[i].auditorId == this.optionsOId || this.options[i].id == this.optionsOId) {
                                this.selectName = this.options[i].name || this.options[i].auditorName
                            }
                        }
                    } else {
                        this.selectName = this.$t('defaultText.pleaseChoose')
                    }
                }
                if(this.multiSelect) {
                    for(var i in this.options) {
                        for(var j in this.optionsOId) {
                            if(this.options[i].userId == this.optionsOId || this.options[i].auditorId == this.optionsOId[j] || this.options[i].id == this.optionsOId[j]) {
                                this.multiSelectList.push(this.options[i])
                                this.options[i].flg = true
                            }
                        }
                    }
                }
            },
        },
        widthStr: {
            handler(newValue, oldValue) {
                this.selectWidth = newValue
            },
        }
    },
    created() {},
    mounted() {
        if(this.size == 'mini') {
            this.selectWidth = '150'
            this.selectHeight = '28'
        } else if(this.size == 'small') {
            this.selectWidth = '191'
            this.selectHeight = '32'
        } else if(this.size == 'medium') {
            this.selectWidth = '205'
            this.selectHeight = '40'
            this.selectFontSize = '14'
        }
        if(this.widthStr) {
            this.selectWidth = this.widthStr
        }
        
        if(this.subject) {
            this.options = JSON.parse(JSON.stringify(this.subject))
        }
        if(this.subjectId) {
            this.multiSelectList = []
            if(!this.multiSelect) {
                this.optionsOId = JSON.parse(JSON.stringify(this.subjectId))
                for(let i in this.options) {
                    if(this.options[i].userId == this.optionsOId || this.options[i].auditorId == this.optionsOId || this.options[i].id == this.optionsOId) {
                        this.selectName = this.options[i].auditorName || this.options[i].name 
                    }
                }
            }
            // console.log(this.options, this.subjectId)
            if(this.multiSelect) { 
                for(var i in this.options) {
                    for(var j in this.subjectId) {
                        if(this.options[i].id == this.subjectId[j] || this.options[i].auditorId == this.subjectId[j]) {
                            this.multiSelectList.push(this.options[i])
                            this.options[i].flg = true
                        }
                    }
                }
            }
        }
        // console.log(this.subject, this.subjectId)

        var thats = this
        var phoneArr = []
        setTimeout(()=>{
            for(var s in thats.subject) {
                phoneArr.push(thats.subject[s].optionsOId || thats.subject[s].auditorId || thats.subject[s].id) 
            }
            thats.fistArrListOne = thats.subject
        }, 500)
        
        thats.fistArrList = phoneArr
        // console.log(thats.fistArrList)
        this.dailyListIndex = this.idx
    },
    methods: {
        dianjis() {
            if(!this.disabled) {
                let modes = this.multiSelect ? 'multi' : 'single'
                let that = this
                wx.invoke("selectEnterpriseContact", {
                    "fromDepartmentId": 0,// 必填，表示打开的通讯录从指定的部门开始展示，-1表示自己所在部门开始, 0表示从最上层开始
                    "mode": modes,// 必填，选择模式，single表示单选，multi表示多选
                    "type": ["user"],// 必填，选择限制类型，指定department、user中的一个或者多个
                    "selectedDepartmentIds": [],// 非必填，已选部门ID列表。用于多次选人时可重入，single模式下请勿填入多个id
                    "selectedUserIds": []// 非必填，已选用户ID列表。用于多次选人时可重入，single模式下请勿填入多个id
                        },function(res){
                            // console.log(res)
                            if (res.err_msg == "selectEnterpriseContact:ok"){
                                // console.log(res, '数据来源')
                                if(typeof res.result == 'string'){
                                    res.result = JSON.parse(res.result) //由于目前各个终端尚未完全兼容，需要开发者额外判断result类型以保证在各个终端的兼容性
                                }
                                var selectedUserList = res.result.userList; // 已选的成员列表
                                var userId = ''
                                var userName = ''
                                for (var i = 0; i < selectedUserList.length; i++) {
                                        var user = selectedUserList[i];
                                        userId = user.id; // 已选的单个成员ID
                                        userName = user.name;// 已选的单个成员名称
                                        // console.log(userId, userName)
                                }
                                for(var s in that.options) {
                                    if(that.options[s].name == userId) {
                                        that.selectName = userId
                                        that.wxCoper(that.options[s].id)
                                    }
                                }
                            }
                        }
                );
            }
        },
        wxCoper(id) {
            let obj = {
                id: id,
                distinction: this.distinction,
                index: this.index, // 选中的索引
                other: this.other,
                name: this.selectName
            }
            // console.log(obj)
            this.$emit("selectCal", obj)
        },
        selectCli() {
            if(!this.disabled) {
                this.$refs.selectDiv.focus()
                this.classDiv = !this.classDiv
                this.show = !this.show
                this.move = !this.move
                this.searchTex = ''
                if(this.optionsCopy.length > 0) {
                    this.$set(this, 'options', JSON.parse(JSON.stringify(this.optionsCopy)))
                }
            }

            if(this.show) {
                this.setSelectlocation()
            }
        },
        setSelectlocation() {
            let witdhs = this.$refs.selectRefs.offsetWidth
            let tops = this.$refs.selectRefs.getBoundingClientRect().top
            let lefts = this.$refs.selectRefs.getBoundingClientRect().left
            this.selecsWths = witdhs
            this.selectTop = tops + 4
            this.selectLeft = lefts
        },
        selectClihide() {
            if(this.classDiv) {
                this.transitionBoxLiIdx = ''
                this.show = !this.show
                this.classDiv = false
                this.move = false
                if(this.multiSelect) {
                    let obj = {
                        // id: nameId,
                        distinction: this.distinction,
                        index: this.index, // 选中的索引
                        other: this.other,
                        arrUserList: this.multiSelectList,
                        name: this.selectName
                    }
                    this.$emit("selectCal", obj)
                    this.options = this.fistArrListOne
                }
            }
        },
        liMouseOver(index) {
            this.transitionBoxLiIdx = index
        },
        liClick(item, itemIndex) {
            // console.log(item, '进来的')
            let nameId = item.auditorId || item.id
            this.selectName = item.auditorName || item.name
            if(!this.multiSelect) {
                // console.log('我进来了', this.flg)
                if(this.flgs) {
                    let obj = {
                        id: nameId,
                        idx: this.dailyListIndex
                    }
                    this.$emit("selectCatCli", obj);
                    this.options = this.fistArrListOne
                } else {
                    let obj = {
                        id: nameId,
                        distinction: this.distinction,
                        index: this.index, // 选中的索引
                        other: this.other,
                        name: this.selectName
                    }
                    this.$emit("selectCal", obj)
                    this.options = this.fistArrListOne
                }
                this.transitionBoxLiIdx = ''
                this.show = false
                this.classDiv = false
                this.move = false
            }
            if(this.multiSelect) {
                if(this.options[itemIndex].flg) {
                    this.options[itemIndex].flg = !this.options[itemIndex].flg
                    for(var i in this.multiSelectList) {
                        if(this.multiSelectList[i].id == item.id) {
                            this.multiSelectList.splice(i, 1)
                        }
                    }
                } else {
                    this.options[itemIndex].flg = false
                    this.options[itemIndex].flg = !this.options[itemIndex].flg
                    this.multiSelectList.push(item)
                }
            }
        },
        moveIonDiv() {
            if(this.clearable) {
                this.moveIon = true
            }
        },
        outIonDiv() {
            if(this.clearable) {
                this.moveIon = false
            }
        },
        clearDelete() {
            if(!this.multiSelect) {
                this.selectName = this.$t('defaultText.pleaseChoose')
                let obj = {
                    name: this.$t('defaultText.pleaseChoose'),
                    id: ''
                }
                this.liClick(obj)
            }
            if(this.multiSelect) {
                this.multiSelectList = []
                let obj = {
                    distinction: this.distinction,
                    index: this.index, // 选中的索引
                    other: this.other,
                    arrUserList: []
                }
                for(var i in this.options) {
                    if(this.options[i].flg) {
                        this.options[i].flg = false
                    }
                }
                this.$emit("selectCal", obj)
                this.options = this.fistArrListOne
            }
        },
        deleteMultiSelectList(str, userIndex) {
            let userId
            if(str == '-1') {
                userId = this.multiSelectList[0].id
                this.multiSelectList.splice(0, 1)
            } else if(str == '-2') {
                this.multiSelectList.splice(userIndex, 1)
            } else {
                userId = this.multiSelectList[str].id
                this.multiSelectList.splice(str, 1)
            }
            for(var i in this.options) {
                if(this.options[i].id == userId) {
                    if(this.options[i].flg) {
                        this.options[i].flg = false
                    }
                }
            }

            let obj = {
                distinction: this.distinction,
                index: this.index, // 选中的索引
                other: this.other,
                arrUserList: this.multiSelectList,
                name: this.selectName
            }
            this.$emit("selectCal", obj)
            this.options = this.fistArrListOne
        },
        // searchBox() {
        //     this.selectCli()
        // },
        // // 搜索
        searchLick() {
            if (this.time != null) {
                clearTimeout(this.time)
            }
            var that = this
            this.time = setTimeout(() => {
                that.getSimpleActiveUserList()
            }, 500)
            
        },
        // 针对  getSimpleActiveUserList 获取所有人员接口
        getSimpleActiveUserList() {
            this.http.post('/user/getEmployeeList', {
                departmentId: -1,
                pageIndex: 1,
                pageSize: 200,
                keyword: this.searchTex,
                status: 1,
                roleId: '',
                cursor: '',
                onlyDirect: 0,
            },
            res => {
                if (res.code == "ok") {
                    var arr = res.data.records.filter((item) => {
                        if (this.fistArrList.indexOf(item.id) != '-1') {
                            return item;
                        }
                    })
                    // this.options = arr
                    // console.log('将要赋值')
                    var newArr = arr.length > 0 ? arr : res.data.records
                    this.$set(this, 'options', newArr)
                    this.cursor = res.data.nextCursor
                } else {
                    this.$message({
                        message: res.msg,
                        type: "error"
                    });
                }
            },
            error => {
                this.$message({
                    message: error,
                    type: "error"
                });
            });
        }
    },
    triggerOption(){

    },
    choose(item,value){
      
    },

};
</script>

<style scoped lang="scss">
    @import "../assets/scss/handle";
    .selectBox {
        position: fixed;
        z-index: 999;
    }
    .selectDandu {
        font-size: 16px;
    }
    .waihez {
        // padding-top: 7px;
        // box-sizing: border-box;
        // background: #FFF;
        display: inline-block;
    }
    .selectDiv {
        @include border_color("border_color");
    }
    .disabledTrue {
        background: #F5F7FA !important;
        border-radius: 4px;
        cursor: not-allowed !important;
        position: relative;
    }
    .disabledFalse .select {
        background: #FFF !important;
        border-radius: 4px;
    }
    .select {
        -webkit-appearance: none;
        // background-color: #FFF;
        background-image: none;
        border-radius: 4px;
        border: 1px solid #DCDFE6;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        color: #606266;
        display: inline-block;
        font-size: inherit;
        min-height: 40px;
        line-height: 40px;
        outline: 0;
        padding: 0 15px;
        -webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
        transition: border-color .2s cubic-bezier(.645,.045,.355,1);
        width: 100%;
        position: relative;
        cursor: pointer;
    }
    .selecttex {
        // height: 28px;
        line-height: 28px;
        text-overflow: ellipsis;
        font-size: 12px;
    }
    .iostu {
        position: absolute;
        top: 50%;
        margin-top: -4px;
        right: 8px;
        color: #C0C4CC;
        transition: All 0.2s ease-in-out;
    }
    .iostuHover {
        transform: rotate(-180deg);
    }
    .searchBox {
        position: absolute; 
        width: 100%;
        top: -9px;
        // top: 0px;
    }
    .transitionBox {
        background: #FFF;
        position: absolute; 
        width: 100%;
        border-radius: 2em;
        border: 1px solid #E4E7ED;
        border-radius: 4px;
        background-color: #FFF;
        box-sizing: border-box;
        margin: 5px 0;
        box-shadow: 0 2px 12px #dfdfdf;
        max-height: 274px;
        overflow: auto;
        z-index: 500 !important;
    }
    .transitionBoxUl {
        list-style: none;
        padding: 6px 0;
        margin: 0;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
    }
    .transitionBoxUl li {
        font-size: 14px;
        padding: 0 20px;
        position: relative;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        color: #606266;
        height: 34px;
        line-height: 34px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        cursor: pointer;
    }
    .liHover {
        background-color: #F5F7FA;
    }
    .selecttexXuan {
        color: #C0C4CC;;
    }
    .all {
        display: inline-block;
        font-size: 10px;
        background: #f4f4f5;
        height: 20px;
        line-height: 24px;
        padding: 0px 8px;
        color: #909399;
        margin-right: 4px;
    }
    .allTwo {
        display: inline-block;
        margin-left: 10px;
    }
    .hoverSpan {
        display: flex;
        width: 100%;
        justify-content: space-between;
    }
    .hoverSpanHover {
        @include font_color("color");
        font-weight: 700;
    }
    .spanFllat {
        display: inline-block;
        float: right;
    }
</style>
