<template>
    <div>
        <el-dialog
            :title="caseAllocationDialog.title"
            :visible="true"
            width="880px"
            append-to-body
            :close-on-click-modal="false"
            @close="handleClose"
        >
        
            <div class="dialog-content">
                <div class="pb-16">
                    <el-row :gutter="20" type="flex" align="middle">
                        <el-col :span="24">

                            <div class="flex-row align-items-center">
                                <div class="mr-8 flex-shrink-0">区域</div> 
                                <div class="width100">
                                    <el-select v-model="deptId" 
                                            size="medium"
                                            clearable placeholder="请选择区域"
                                            @change="handleChangeDept"
                                            class="width100">
                                        <el-option
                                            v-for="item in departmentOptions"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                            class="width100"
                                            >
                                        </el-option>
                                    </el-select>
                                </div>
                                
                            </div>
                        </el-col>
                    </el-row>
                </div> 
                <el-scrollbar class="bor bg-color-light min-height350">   
                    <div class="department-wrap">
                        <div v-for="(item,inx) in peopleList" :key="inx" class="department-wrap-list">
                            <div class="department-dept">
                                <el-checkbox v-model="checkedAll" :label="item.deptId"  @change="handleCheckChange(1,inx,item,item.deptId,$event)">{{item.name}}({{item.count}}人)</el-checkbox>
                            </div>
                            <div class="flex-row justify-content-start flex-flow-wrap ">
                                <div v-for="(v,i) in item.values" :key="i" class="pt-16" style="flex:0 0 25%">
                                    <el-checkbox v-model="checkedAll" :label="v.id" @change="handleCheckChange(2,inx,v,item.deptId,$event)">{{v.realName}}</el-checkbox>
                                </div>

                            </div>
                        </div>
                    </div>
                </el-scrollbar>
                <div class="p-v-24">
                    <el-form ref="ruleForm" 
                            :model="queryParam" 
                            :rules="rulesClient" 
                            label-width="120px" 
                            class="demo-ruleForm">
                            <el-row :gutter="20" type="flex" align="middle">
                                <el-col :span="24">
                                    <el-form-item label="分配方式" prop="dispatchType" label-width="80px">
                                        <template>
                                            <el-radio v-model="queryParam.dispatchType" :label="1">平均分配</el-radio>
                                            <el-radio v-model="queryParam.dispatchType" :label="2">调解中案件量最少</el-radio>
                                            <el-radio v-model="queryParam.dispatchType" :label="3">当天分案量最少</el-radio>
                                            <el-radio v-model="queryParam.dispatchType" :label="4">当月分案量最少</el-radio>
                                            <el-radio v-model="queryParam.dispatchType" :label="5">同案由调解成功率最高</el-radio>
                                        </template>
                                    </el-form-item>
                                </el-col>
                                
                            </el-row>
                    </el-form>
                </div>

            </div>
        
        <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose()">取消</el-button>
            <el-button type="primary" @click="handleSubmit()">确认</el-button>
        </span>
        </el-dialog>
        
    </div>
</template>
<script>
import api from "@/services/caseManagement";
import apipack from "@/services/casePackageManagement";
    export default {
        components: {
            
        },
        props: {
            caseAllocationDialog: {
                type: Object,
                default: () => {
                    return {}
                },
            },
        },
        data() {
            return {
                deptId:[],//获取区域id集合
                queryParam:{
                    id:'',//案件包ID	
                    dispatchType:1,//分案方式；1，平均分配；2，调解中案件量最少；3，当天分案量最少；4，当月分案量最少；5，同案由调解成功率最高
                },
                userList:[],
                rulesClient: {
                    dispatchType: [
                        { required: true, message: '请选择分案方式', trigger: 'change',},
                    ],
                },
                peopleList:[
                    {deptId:1,name:'调解一部',count:10,
                        values:[
                            {id:1,deptId:1,realName:'张三' },
                            {id:2,deptId:1,realName:'张三' },
                            {id:3,deptId:1,realName:'张三' },
                            {id:4,deptId:1,realName:'张三' },
                            {id:5,deptId:1,realName:'里面' },
                        ]
                    }
                ],
                departmentOptions:[],//区域
                checkedAll:[],
                chooseChecked:[],

                deptUsers:[]
            };
        },
        mounted () {
            this.getDeptList();//获取区域
        },
        methods: {
            // 获取区域
            getDeptList(){
                let data = {
                    companyId: this.$store.state.userinfo.companyId,
                    current: 1,
                    size: 500,
                    pid:0
                }
                api.getDeptList(data).then(res => {
                    if (!res.code) {
                        this.departmentOptions = res.records;
                        this.deptId = this.departmentOptions[0].id
                        this.getByDeptList()
                    }
                })
            },
            handleChangeDept(e){
                this.checkedAll=[]
                this.chooseChecked=[]
                this.getByDeptList()
                this.peopleList=[]
                
            },
            // 根据区域id列表查看用户列表
            getByDeptList(){

                // 当前区域自身
                let deptList = []
                let userlistmy = []
                api.getUserByDeptList({ids:[this.deptId]}).then(res => {
                    res.forEach(item =>{
                        userlistmy.push({
                            id:item.id,
                            realName:item.realName,
                            checked:false
                        }) 
                    })
                })

                deptList.push({
                    deptId:this.deptId,
                    name:this.departmentOptions.find(item=>{ return item.id == this.deptId}).name,
                    count:this.departmentOptions.find(item=>{ return item.id == this.deptId}).count,
                    checked:false,
                    values:userlistmy
                })
                
                // 下属区域或团队
                api.getDeptList({companyId:this.$store.state.userinfo.companyId,current:1,size:500,pid:this.deptId}).then(res => {
                    if (!res.code) 
                    {
                        // let deptList = []
                        res.records.forEach(item =>{
                            let userlist = []
                            api.getUserByDeptList({ids:[item.id]}).then(res => {
                                
                                res.forEach(item =>{
                                    userlist.push({
                                        id:item.id,
                                        realName:item.realName,
                                        checked:false
                                     }) 
                                })
                            })

                            deptList.push({
                                deptId:item.id,
                                name:item.name,
                                count:item.count,
                                checked:false,
                                values:userlist
                            })
                        })
                        this.peopleList = deptList
                    }
                })
            },
            handleCheckChange(type,a=0,chooseItem,deptId,event){
            // console.log(chooseItem,event,a,'this.peopleList')
                let self = this
                if(type==2){//二级菜单
                let index = 0;
                self.peopleList[a].values.map((item)=>{
                    if(self.checkedAll.indexOf(item.id)>-1){
                        index+=1
                    }
                })
                if(index>0){
                    if(self.checkedAll.indexOf(self.peopleList[a].deptId)<0){
                        self.checkedAll.push(self.peopleList[a].deptId)
                    }
                }else{
                    if(self.checkedAll.indexOf(self.peopleList[a].deptId)>0){
                        self.checkedAll.splice(self.checkedAll.indexOf(self.peopleList[a].deptId),1)
                    }
                }

                if(event)
                {
                    if(this.chooseChecked.length==0){self.chooseChecked.push({deptId:deptId,child:[]})}
                    this.chooseChecked.forEach((item,index) => {
                        let haveDeptId = self.chooseChecked.find(citem=>{
                            return citem.deptId===deptId
                        })
                        if(haveDeptId != undefined)
                        {
                            if(item.deptId==deptId)
                            {
                                item.child.push({deptId:deptId,id:chooseItem.id,realName:chooseItem.realName})
                            }
                        }
                        else
                        {
                            self.chooseChecked.push({deptId:deptId,child:[{deptId:deptId,id:chooseItem.id,realName:chooseItem.realName}]})
                        }
                    });
                }
                else
                {
                    this.chooseChecked.forEach((item,index) => {
                        item.child.forEach((itemchild,index) => {
                            if(itemchild.id==chooseItem.id)
                            {
                                item.child.splice(index,1)
                            }
                        });
                    });
                }
                
                let childnum = this.chooseChecked.find(item=>{
                    return item.deptId === deptId
                }).child.length;

                let allchildnum = this.peopleList.find(item=>{
                    return item.deptId === deptId
                }).values.length;
                if(childnum != allchildnum)
                {
                    if(self.checkedAll.indexOf(deptId)>-1){
                        self.checkedAll.splice(self.checkedAll.indexOf(deptId),1)
                    }
                }
                else
                {
                    if(self.checkedAll.indexOf(deptId)<0){
                        self.checkedAll.push(deptId)
                    }
                }

                }else{
                    if(self.checkedAll.indexOf(self.peopleList[a].deptId)>-1){
                        self.peopleList[a].values.map((item)=>{
                            if(self.checkedAll.findIndex((n)=> n==item.id)<0){
                                self.checkedAll.push(item.id)
                            //  self.checkedAll.push({id:item.id,realName:item.realName,deptId:self.peopleList[a].deptId})
                            }
                        })
                    }else{
                        self.peopleList[a].values.map((item)=>{
                            if(self.checkedAll.findIndex((n)=> n==item.id)>-1){
                                self.checkedAll.splice(self.checkedAll.findIndex((n)=> n==item.id),1)
                            }
                        })
                    }


                let haveDeptId=self.chooseChecked.find(citem=>{
                    return citem.deptId === deptId
                })
                if(event)
                {
                    if(haveDeptId == undefined)
                    {
                        let addchild=[]
                        self.peopleList.forEach((item,index) => {
                            if(item.deptId==deptId)
                            {
                                item.values.forEach((item,index) => {
                                    addchild.push({deptId:deptId,id:item.id,realName:item.realName})
                                });
                            }
                        });
                        self.chooseChecked.push({deptId:deptId,child:addchild})
                    }
                }
                else
                {
                    if(haveDeptId != undefined)
                    {
                        self.chooseChecked.forEach((item,index) => {
                            if(item.deptId==deptId)
                            {
                                self.chooseChecked.splice(index,1)
                            }
                        });
                    }
                }
                }
            //  console.log(this.checkedAll,self.chooseChecked,'checkedAll')
            },  
            
            handleSubmit(){
                if(!this.$clickThrottle()) { return }//防止重复点击
                let chooseUser=[]
                this.chooseChecked.forEach((item,index) => {
                    item.child.forEach((item,index) => {
                        chooseUser.push({deptId:item.deptId,id:item.id,realName:item.realName})
                    });
                });
                if(chooseUser.length == 0)
                {
                    this.$message({
                        showClose: true,
                        message: '请先选择调解员！',
                        type: 'warning'
                    });
                    return false
                }

                this.$refs.ruleForm.validate((valid) => {
                    if(valid) {
                        
                        let data = {
                            id:this.caseAllocationDialog.ObjectInfo.id,
                            dispatchType:this.queryParam.dispatchType,
                            userList:chooseUser
                        }
                        
                        apipack.postpkgdispatchCase(data).then(res => {
                            this.$message({
                                showClose: true,
                                message: '调解案件分配成功！',
                                type: 'success'
                            });
                            this.$parent.getCaseInfoList()
                            this.handleClose()
                        })
                    }
                })
            },
            handleSearch(){

            },
            handleChangeDate(){
                let planStart = new Date(this.queryParam.planStartTime);
                let planEnd = new Date(this.queryParam.planEndTime);
                if (planEnd < planStart) {
                    this.$message({
                        showClose: true,
                        message: '开始日期不能大于结束日期！',
                        type: 'warning'
                    });
                    this.queryParam.planEndTime=''
                } 
            },
            handleClose() {
                this.$emit('update:caseAllocationDialog', null)
            },
        }
    };
</script>
<style scoped lang="scss">
.dialog-content{
    padding: 16px 24px;
    max-height:500px
}
.department-wrap{
    padding: 16px 24px;
    max-height: 250px;
    .department-wrap-list{
        margin-bottom:32px;
    }
    .department-wrap-list:last-child{
        margin-bottom:0;
    }
}
.min-height350{height: 350px;}
.department-dept ::v-deep .el-checkbox__label {color: $color-000000}
</style>