<style>
    .editOrderDrawerTop {
        width: 100%;
        height: 50px;
        display: flex;
        justify-content: space-between;
        background-color: #f0f5fb;
        padding: 5px 10px;
        align-items: center;
    }

    .disableStatus {
        opacity: 0.3 !important;
        cursor: auto;
    }

    .imgstyle {
        width: 100%;
        height: 126px;
        border-radius: 4px;
    }



    .addDutyMain {
        display: inline-block;
        width: 118px;
        height: 118px;
        font-size: 40px;
        border: 1px dashed #d9d9d9;
        line-height: 118px;
    }

    .up-box {
        width: 90px;
        height: 90px;
        border: 1px dashed #ccc;
        text-align: center;
        line-height: 80px;
        font-size: 50px;
        cursor: pointer;
    }

    .chaneelcodeform .el-date-editor.el-input,
    .chaneelcodeform .el-date-editor.el-input__inner {
        width: 140px;
        margin-right: 10px;
    }

    .el-popper {
        z-index: 6001 !important;
    }

    .chaneelcodeform .ant-tag {
        display: inline-block;
        height: auto;
        margin-right: 8px;
        padding: 0 7px;
        font-size: 12px;
        line-height: 20px;
        white-space: nowrap;
        background: #fafafa;
        border: 1px solid #d9d9d9;
        border-radius: 2px;
        cursor: pointer;
        opacity: 1;

    }

    .chaneelcodeform .ant-tag-has-color {
        color: #FFF;
        border: 1px solid #1890ff;
    }
</style>

<template>
    <div>
        <q-dialog v-model="IsShow" persistent>
            <q-card style="width: 800px; max-width: 80vw;" class="chaneelcodeform">
                <q-card-section class="row items-center q-pb-none ">
                    <div class="text-h6">添加企业成员</div>
                    <q-space />
                    <q-btn icon="close" flat round dense @click="closeEditOrder"/>
                </q-card-section>
                <q-separator />
                <q-card-section class="q-pt-none">
                    <div style="width:100%;background: #fffbe6;padding: 20px;margin-top: 20px;">
                        <div>1、系统默认生成一条每日24小时（00:00~00:00）数据，当时间点不在所新增的时段内，客户扫码后，添加的是“24小时”的企业成员。</div>
                        <div>2、因受官方限制，无法对动态部门的员工设置添加好友上限，只可针对指定活码成员进行设置。</div>

                    </div>
                    <el-form label-width="120px">
                        <el-form-item label="固定时段：" v-if="peopletype==1">
                            <div v-for="(x,y) in addMsg " :key="y"
                                style="display: flex;align-items: center;margin-top: 10px;">
                                <el-time-select :disabled="x.IsDefault==1" placeholder="起始时间" v-model="x.StartHours"  @change="changeTime(y,2)"
                                    :picker-options="{ start: '00:00', step: '01:00', end: '23:00', }">
                                </el-time-select>
                                <el-time-select :disabled="x.IsDefault==1" placeholder="结束时间" v-model="x.EndHours" @change="changeTime(y,2)"
                                    :picker-options="{ start: '00:00', step: '01:00', end: '23:00',  minTime: x.StartHours}">
                                </el-time-select>
                                <el-select v-model="x.EmpId" placeholder="请选择" @change="selectPersonnel(y)">
                                    <el-option filterable v-for="item in Employeelist" :key="item.Id"
                                        :label="item.EmployeeName" :value="item.Id">
                                    </el-option>
                                </el-select>
                                <q-btn flat color="red" v-if="y>0" label="删除" @click="addMsg.splice(y,1)" />
                            </div>
                            <q-btn flat color="primary" label="添加" @click="adddata()" />

                        </el-form-item>
                        <el-form-item label="固定时段：" v-if="peopletype==2">
                            <div v-for="(x,y) in addMsg " :key="y" >
                                <div style="display: flex;align-items: flex-start;margin-top: 10px;">
                                    <el-time-select :disabled="x.IsDefault==1" placeholder="起始时间" v-model="x.StartHours"  @change="changeTime(y,2)"
                                        :picker-options="{ start: '00:00', step: '01:00', end: '23:00', }">
                                    </el-time-select>
                                    <el-time-select :disabled="x.IsDefault==1" placeholder="结束时间" v-model="x.EndHours"@change="changeTime(y,2)"
                                        :picker-options="{ start: '00:00', step: '01:00', end: '23:00',  minTime: x.StartHours}">
                                    </el-time-select>
                                    <div style="max-width: 320px;">
                                        <div style="line-height: 20px;">
                                            <span v-if="x.EmpList.length>0" v-for="(item,index) in x.EmpList " :key="index">{{item.DeptName}}{{x.EmpList.length-1 !=index?'、':''}}</span>
                                        </div>
                                        <el-button @click="outerVisible=true,outerindex=y,byval=x.EmpList" style="margin-top: 0;">选择企业成员</el-button>
                                    </div>
                                </div>
                                <div>
                                    <selectTree  class="col-6 q-pb-lg q-pr-lg" :treeData='DeptList' style="margin-top: 10px;"
                                        :defaultArray="x.returnString" nodeKey="DeptId" :multiple="true" :defaultExpandAll="true"
                                        labelKey="DeptName" childrenKey="ChildList" tipText="选择部门" @getChild="getChild($event,y)"
                                        classStr="col-6 q-pr-lg q-pb-lg"></selectTree>
                                </div>

                                <q-btn flat color="red" v-if="y>0" label="删除" @click="addMsg.splice(y,1)" />
                            </div>
                            <q-btn flat color="primary" label="添加" @click="adddata()" />

                        </el-form-item>
                        <el-form-item label="适用周期：">
                            <div style="line-height: 40px;">
                                <span class="ant-tag" :class="{'ant-tag-has-color':item.chek}"
                                v-for="(item,index) in weekList" :key='index'
                                @click=" weekList[index].chek = !weekList[index].chek,$forceUpdate()"
                                :style="{background:item.chek?'#1890ff':'#FFF'}">{{item.Name}}</span>
                            </div>
                            
                        </el-form-item>
                    </el-form>
                </q-card-section>

                <q-separator />
                <q-card-actions align="right" class="bg-white">
                    <q-btn class="q-mr-md" label="取消" @click="closeEditOrder" />
                    <q-btn color="accent" class="q-mr-md" label="确定" @click="saveOrderInfo()" />
                </q-card-actions>
            </q-card>
        </q-dialog>

        <choiceapproval v-if="outerVisible" @close="getclose()" @success="getsuccess" :byval='byval'></choiceapproval>
    </div>

</template>
<script>

    import {
        setWeChatMediumInfo,//新增素材
    } from '../../api/system/wechat';
    import selectMaterial from "./selectMaterial"
    import {
        queryEmployee
    } from '../../api/users/user'
    import choiceapproval from './choiceapproval'
    import {
        getDeptTree
    } from '../../api/system/dept.js'
    import selectTree from '../../components/common/select-tree'

    export default {
        components: {
            choiceapproval,//所有列表
            selectTree
        },
        props: {
            lsday: {
                type: String,
                default: '',
            },
            peopletype: {
                type: Number,
                default: 1,
            },

            lsweeklist: {
                type: Array,
                default: [],
            }


        },
        data() {
            return {
                IsShow: true,
                Employeelist: [],
                addMsg: [],
                weekList: [{ Id: 1, Name: '周一', chek: false }, { Id: 2, Name: '周二', chek: false }, { Id: 3, Name: '周三', chek: false }, { Id: 4, Name: '周四', chek: false }, { Id: 5, Name: '周五', chek: false }, { Id: 6, Name: '周六', chek: false }, { Id: 0, Name: '周日', chek: false }],

                outerVisible: false,
                outerindex: 0,
                byval:[],
                DeptList: [], // 部门下拉

            }
        },
        created() {
            if (this.peopletype == 1) {//单人模式
                this.addMsg = [
                    { Id: 0, Week: '', IsDefault: 1, StartHours: '00:00', EndHours: "00:00", EmpId: '', EmpName: '', }
                ]
            } else {
                this.addMsg = [
                    { Id: 0, Week: '', IsDefault: 1, StartHours: '00:00', EndHours: "00:00", EmpList: [], DeptList: [], returnString:[],}
                ]
            }
            if (this.lsday != '') {//修改单独周几
                this.weekList = JSON.parse(JSON.stringify(this.lsweeklist))
                this.addMsg = []
                this.weekList.map(x => {
                    if (x.Id == this.lsday) {

                        this.addMsg=[]
                        this.addMsg = JSON.parse(JSON.stringify(x.lsMsg));
                        setTimeout(()=>{
                            if(this.peopletype == 2){//修改时 处理部门的数据
                                let that = this
                                for(let i=0 ;i<that.addMsg.length;i++){
                                    that.addMsg[i].returnString=[];
                                    let dplist = []
                                    that.addMsg[i].DeptList.forEach(j=>{
                                        dplist.push(j.Id)
                                    })
                                    that.addMsg[i].DeptList = dplist
                                    that.addMsg[i].returnString = dplist;
                                    this.$forceUpdate();

                                }
                            }
                        },500)
                    }else{
                        x.chek= false
                    }
                })
            }
            this.queryEmployee()//单选
            this.getDepartList()//部门下拉
        },
        mounted() {

        },
        watch: {

        },
        methods: {
            //获取部门下拉数据
            getDepartList(id) {
                let msg = {
                School_Id: -1
                }
                getDeptTree(msg).then(res => {
                if (res.Code == 1) {
                    this.DeptList = res.Data;
                }
                })
            },
            adddata() {
                if (this.peopletype == 1) {//单人模式
                    let obj = { Id: 0, Week: '', IsDefault: 2, StartHours: '', EndHours: "", EmpId: '', EmpName: '', }
                    this.addMsg.push(obj)
                } else {
                    let obj = { Id: 0, Week: '', IsDefault: 2, StartHours: '', EndHours: "", EmpList: [], DeptList: [], returnString:[],}
                    this.addMsg.push(obj)
                }
            },
            //关闭弹窗
            closeEditOrder() {
                this.$emit('close')
            },
            queryEmployee() {//下拉人员列表 IsLeave=1排除了离职的
                queryEmployee({IsLeave:1}).then(res => {
                    if (res.Code == 1) {
                        this.Employeelist = res.Data
                    }
                }).catch(() => {

                })
            },

            selectPersonnel(index) {
                this.Employeelist.map(x => {//部门id带过去
                    if (x.Id == this.addMsg[index].EmpId) {
                        this.addMsg[index].EmpName = x.EmployeeName;
                        return
                    }
                })
            },
            saveOrderInfo() {
                if (this.peopletype == 1) {
                    let isEmpId = false;
                    let isHours = false;
                    this.addMsg.map((x, i) => {
                        if (i > 0) {
                            if (x.StartHours == '' || x.EndHours == '') {
                                isHours = true;
                                return
                            }
                            if (x.EmpId == '') {
                                isEmpId = true;
                                return
                            }
                        } else {
                            if (x.EmpId == '') {
                                isEmpId = true;
                                return
                            }
                        }
                    })
                    if (isHours == true) {
                        this.$q.notify({
                            type: 'negative',
                            message: `请选择时间`,
                            position: 'top'
                        })
                        return
                    }
                    if (isEmpId == true) {
                        this.$q.notify({
                            type: 'negative',
                            message: `请选择成员`,
                            position: 'top'
                        })
                        return
                    }
                    let isweek = false;
                    this.weekList.map(x => {
                        if (x.chek == true) {
                            isweek = true;
                            return
                        }
                    })
                    if (isweek == false) {
                        this.$q.notify({
                            type: 'negative',
                            message: `请选择适用周期`,
                            position: 'top'
                        })
                        return
                    }
                    let list = [];
                    // if (this.lsday == '') {
                        this.weekList.forEach(x => {
                            if (x.chek == true) {
                                x.lsMsg = this.addMsg
                            } else {
                                this.lsweeklist.map(j => {
                                    if (x.Id == j.Id) {
                                        x.lsMsg = j.lsMsg ? JSON.parse(JSON.stringify(j.lsMsg)) : [];
                                        x.chek = j.chek
                                        return
                                    }
                                })
                            }
                            list.push(x)
                        })

                    // } else {// 只修改某一天的数据
                    //     this.weekList.map(x => {
                    //         if (x.Id == this.lsday) {
                    //             x.lsMsg = this.addMsg
                    //             return
                    //         }
                    //     })
                    //     list = this.weekList
                    // }
                    this.$emit('success', this.addMsg, list)


                }else{
                    let isEmpId = false;
                    let isHours = false;
                    this.addMsg.map((x, i) => {
                        if (i > 0) {
                            if (x.StartHours == '' || x.EndHours == '') {
                                isHours = true;
                                return
                            }
                            if (x.EmpList.length == 0 &&  x.DeptList.length==0) {
                                isEmpId = true;
                                return
                            }
                        } else {
                            if (x.EmpList.length == 0 &&  x.DeptList.length==0) {
                                isEmpId = true;
                                return
                            }
                        }
                    })
                    if (isHours == true) {
                        this.$q.notify({
                            type: 'negative',
                            message: `请选择时间`,
                            position: 'top'
                        })
                        return
                    }
                    if (isEmpId == true) {
                        this.$q.notify({
                            type: 'negative',
                            message: `请选择成员`,
                            position: 'top'
                        })
                        return
                    }
                    let isweek = false;
                    this.weekList.map(x => {
                        if (x.chek == true) {
                            isweek = true;
                            return
                        }
                    })
                    if (isweek == false) {
                        this.$q.notify({
                            type: 'negative',
                            message: `请选择适用周期`,
                            position: 'top'
                        })
                        return
                    }
                    let list =[];
                    // if (this.lsday == '') {
                        this.weekList.forEach(x => {
                            if (x.chek == true) {
                                x.lsMsg = this.addMsg
                            } else {
                                this.lsweeklist.map(j => {
                                    if (x.Id == j.Id) {
                                        x.lsMsg = j.lsMsg ? JSON.parse(JSON.stringify(j.lsMsg)) : [];
                                        x.chek = j.chek
                                        return
                                    }
                                })
                            }
                            list.push(x)
                        })
                    // } else {// 只修改某一天的数据
                    //     this.weekList.map(x => {
                    //         if (x.Id == this.lsday) {
                    //             x.lsMsg = this.addMsg
                    //             return
                    //         }
                    //     })
                    //     list = this.weekList
                    // }
                    if(this.peopletype == 2){//多人模式下部门数据处理
                        this.addMsg.forEach((l,index)=>{
                            let tempStr = JSON.parse(JSON.stringify(l.DeptList)) 
                            l.returnString = []
                            l.DeptList=[]
                            tempStr.forEach(x=>{
                                this.DeptList.map(j=>{
                                    if(x ==  j.DeptId){
                                        let obj = {
                                            Id:j.DeptId,
                                            Name:j.DeptName,
                                        }
                                        l.DeptList.push(obj)
                                        return
                                    }else{
                                        if(j.ChildList && j.ChildList.length>0){
                                            this.ChildList(x,j.ChildList,index)
                                        }
                                    }
                                })
                            }) 
                        })
                    }
                    this.$emit('success', this.addMsg, list)
                }
            },
            getclose() {// 企业关闭
                this.outerVisible = false
            },
            getsuccess(list) {
                this.addMsg[this.outerindex].EmpList = JSON.parse(JSON.stringify(list))
                this.outerVisible = false

            },
            getChild(deptArray,index) {
                var tempStr = [];
                if (deptArray && deptArray != '') {
                    tempStr = deptArray.split(',');
                }
                this.addMsg[index].DeptList = tempStr            
            },
            ChildList(x,list,index){
                list.map(j=>{
                    if(x == j.DeptId){
                        let obj = {
                            Id:j.DeptId,
                            Name:j.DeptName,
                        }
                        this.addMsg[index].DeptList.push(obj)
                        return
                    }else{
                        if(j.ChildList && j.ChildList.length>0){
                            this.ChildList(x,j.ChildList,index)
                        }
                    }
                })
            },
            changeTime(index,type){
                if(this.addMsg[index].StartHours=='' || this.addMsg[index].EndHours=='' || this.addMsg[index].StartHours==null || this.addMsg[index].EndHours==null){
                    return
                }
                if(this.addMsg[index].StartHours>this.addMsg[index].EndHours){
                    this.addMsg[index].EndHours = ''
                }
                let a = this.addMsg[index].StartHours
                let b = this.addMsg[index].EndHours
                let continuemap = true
                this.addMsg.map((x,y)=>{
                    if(continuemap == false){
                        return
                    }
                    if(x.IsDefault !=1 && y!=index){//默认和选择自己的时候不做判断
                        let bx = x.StartHours;
                        let by = x.EndHours;
                        continuemap =  this.checkTime(a,b,bx,by)
                        if(continuemap == false){
                            this.$q.notify({
                                type: 'negative',
                                message: `时间段存在冲突`,
                                position: 'top'
                            })
                            this.addMsg[index].StartHours='';
                            this.addMsg[index].EndHours='';
                        }
                    }
                })
            },
            checkTime(a,b,x,y){
                var times1=[],times2 = [];
                times1.push([a,b]);
                times2.push([x,y]);
                var flag = false;
                //循环比较时间段是否冲突
                for (var i = 0; i < times1.length; i++) {
                    if (flag) break;
                    for (var j = 0; j < times2.length; j++) {
                        if(this.check(times1[i][0],times1[i][1],times2[j][0],times2[j][1])){
                            flag = true;
                            break;
                        }
                    }
                }
                if (flag) {
                    return false;
                }else{
                    return true;
                }

            },
            check (a,b,x,y) {
                if(a>=y || x>=b){  
                    return false;
                }else{
                    return true;
                }
            }


        }
    }

</script>