<template>
    <div>
        <el-dialog
            :title="addOrEditUserConfig.title"
            :visible="true"
            width="400px"
            append-to-body
            :close-on-click-modal="false"
            @close="handleClose"
        >
        <el-scrollbar class="bor">
            <div class="dialog-content">
                <el-form ref="ruleForm" 
                    :model="userInfo" 
                    :rules="rulesClient" 
                    label-width="100px" 
                    class="demo-ruleForm">
                    <el-row  type="flex" align="middle">
                        <el-col :span="24">
                        <el-form-item label="员工姓名" prop="realName">
                            <el-input
                            v-model.trim="userInfo.realName"
                            placeholder="请输入"
                            clearable
                            maxlength="11"
                            ></el-input>
                        </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row  type="flex" align="middle">
                        <el-col :span="24">
                        <el-form-item label="电话号码" prop="phone">
                            <el-input
                            v-model.trim="userInfo.phone"
                            placeholder="请输入"
                            clearable
                            maxlength="11"
                            ></el-input>
                        </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row  type="flex" align="middle">
                        <el-col :span="24" v-if="Object.keys(addOrEditUserConfig.data).length == 0">
                            <el-form-item label="用户密码" prop="password">
                                <el-input v-model="userInfo.password" maxlength="18" type="password"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row  type="flex" align="middle">
                        <el-col :span="24">
                        <el-form-item label="电子邮箱" prop="email">
                            <el-input
                            v-model.trim="userInfo.email"
                            placeholder="请输入"
                            clearable
                            maxlength="30"
                            ></el-input>
                        </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row  type="flex" align="middle">
                        <el-col :span="24">
                        <el-form-item label="员工角色" prop="roleIds">
                            <el-select v-model="userInfo.roleIds" multiple placeholder="请选择" class="width100">
                                <el-option
                                v-for="item in userRoleOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        </el-col>
                    </el-row>

                    <!-- <el-row  type="flex" align="middle">
                        <el-col :span="24">
                        <el-form-item label="选择团队" prop="deptId">
                            <el-cascader class="width100"
                                v-model="userInfo.deptIds"
                                :options="deptOptions"
                                :props="{ expandTrigger: 'hover' }"
                                @change="handleCascaderChange">
                                <template slot-scope="{ node, data }">
                                    <span>{{ data.name }}</span>
                                    <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                                </template>
                            </el-cascader>
                            
                        </el-form-item>
                        </el-col>
                    </el-row> -->

                    <el-row  type="flex" align="middle">
                        <el-col :span="24">
                        <el-form-item label="选择区域" prop="regionId">
                            <el-select v-model="userInfo.regionId" placeholder="请选择" class="width100" @change="regionChange">
                                <el-option
                                v-for="item in regionOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row  type="flex" align="middle">
                        <el-col :span="24">
                        <el-form-item label="选择团队" prop="teamId">
                            <el-select v-model="userInfo.teamId" placeholder="请选择" class="width100">
                                <el-option
                                v-for="item in teamOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                                </el-option>
                            </el-select>
                            
                        </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row  type="flex" align="middle">
                        <el-col :span="24">
                        <el-form-item label="负责人" prop="deptFlag">
                            <el-switch
                                v-model="userInfo.identity"
                                active-color="#535AFF"
                                inactive-color="#dcdfe6"
                                :active-value="2"
                                :inactive-value="3">
                            </el-switch>
                        </el-form-item>
                        </el-col>
                    </el-row>
                    
                
                </el-form>
            </div>
        </el-scrollbar>
        <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/systemManage'
export default {
    components: {
        
    },
    props: {
        addOrEditUserConfig: {
            type: Object,
            default: () => {
                return {}
            },
        },
    },
    data() {
        return {
            userId:'',
            userInfo:{
                username:'',
                phone:'',
                email:'',
                realName:'',
                roleIds:[],
                regionId:'',
                teamId:'',
                deptId:'',
                deptIds:[],
                type: 2,
                status:1,
                identity:3
            },
            rulesClient: {
                password: [
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                    { pattern: /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\W_]).{6,18}$/, message: '只能输入由6-18个字母、数字、特殊字符组成的密码', trigger: ['blur', 'change']}
                ],
                realName: [
                    { required: true, message: '请输入员工姓名', trigger: ['blur','change'] }
                ],
                roleIds: [
                    { required: true, message: '请选择员工角色', trigger: ['blur','change'] }
                ],
                regionId: [
                    { required: true, message: '请选择区域', trigger: ['blur','change'] }
                ],
                // deptId: [
                //     { required: true, message: '请选择团队', trigger: ['blur','change'] }
                // ],
                phone: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { pattern: /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})|(19[0-9]{9})$/, message: '请输入正确手机号码', trigger: ['blur', 'change']}
                ],
                email: [
                    { required: false, message: '请输入邮箱地址', trigger: 'blur' },
                    { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确邮箱地址', trigger: ['blur', 'change']}
                ],
                
            },
            userRoleOptions: [],
            deptOptions: [],
            regionOptions:[],//区域
            teamOptions:[]//团队
            
        };
    },
    methods: {
        handleSubmit(){
            if(!this.$clickThrottle()) { return }
            let _this=this;
            console.log(_this.userInfo,'_this.userInfo')
            this.$refs.ruleForm.validate(async(valid) => {
                if (valid) {
                    _this.userInfo.username = _this.userInfo.phone;
                    if(Object.keys(this.addOrEditUserConfig.data).length>0)
                    {
                        api.updateUserById(_this.userInfo).then(res => {
                            this.$message({
                                showClose: true,
                                message: '编辑用户成功！',
                                type: 'success'
                            });
                            this.handleClose()
                            this.$parent.getUserList(1)
                        })
                    }
                    else
                    {
                        api.addUser(_this.userInfo).then(res => {
                            this.$message({
                                showClose: true,
                                message: '新增用户成功！',
                                type: 'success'
                            });
                            this.handleClose()
                            this.$parent.getUserList(1)
                        })
                    }
                } 
                else 
                {
                    return false;
                }
            });
        },
        handleClose() {
            this.$emit('update:addOrEditUserConfig', null)
        },
        // 递归获取目标节点所有父节点
        ShowRecursive(childlist) {
            let _this=this
            childlist.forEach(function(item) {
                if(item.children.length > 0)
                {
                    //递归
                    item.label = item.name
                    item.value = item.id
                    _this.ShowRecursive(item.children);
                }
                else
                {
                    if(item.pid != 0)
                    {
                        item.children = null
                    }
                    item.label = item.name
                    item.value = item.id
                }
                if(_this.userInfo.deptId == item.id){
                    _this.userInfo.deptIds = [item.pid,item.id]
                }
            })
        },
        handleCascaderChange(e){
            this.userInfo.deptId = e[1]
        },
        getRegion(){
            api.getDeptList({current: 1,size: 100,companyId:this.$store.state.userinfo.companyId}).then(res => {
                res.records.forEach(item =>{
                    if(item.pid == 0)
                    {
                        this.regionOptions.push({id:item.id.toString(),name:item.name})
                        if(this.userInfo.deptId == item.id){
                            this.userInfo.regionId = item.id.toString()
                        }
                    }

                    if(this.userInfo.deptId == item.id)
                    {
                        if(item.pid == 0)
                        {
                            this.userInfo.regionId = item.id.toString()
                        }
                        else
                        {
                            this.userInfo.regionId = item.pid.toString()
                            this.userInfo.teamId = item.id.toString()
                        }
                    }
                })

                if(this.userInfo.regionId != '')
                {
                    this.regionChange(0)
                }
            })
        },
        regionChange(type){
            this.teamOptions = []
            if(type != 0){ this.userInfo.teamId = '' }
            if(this.userInfo.regionId != '')
            {
                api.getDeptList({current: 1,size: 100,companyId:this.$store.state.userinfo.companyId,pid:this.userInfo.regionId}).then(res => {
                    res.records.forEach(item =>{
                        this.teamOptions.push({id:item.id.toString(),name:item.name})
                    })
                })
            }
        }

    },
    async created()
    {
        if(JSON.parse(sessionStorage.getItem('userInfo'))){
            this.userId = JSON.parse(sessionStorage.getItem('userInfo')).id
        }

        if(Object.keys(this.addOrEditUserConfig.data).length>0)
        {
            this.userInfo = JSON.parse(JSON.stringify(this.addOrEditUserConfig.data));
            this.userInfo.regionId = '0'
            this.userInfo.teamId = ''
        }


        api.getRoleListByUserId({userId:this.userId}).then(res => {
            res.forEach(element => {
                this.userRoleOptions.push({name:element.name,id:element.id})
            });
        })

        this.getRegion()
        // api.getDeptTree({current: 1,size: 100,companyId:this.$store.state.userinfo.companyId}).then(res => {
        //     this.deptOptions = res
        //     this.ShowRecursive(this.deptOptions)
        // })
        
        

    }
};
</script>
<style lang="scss" scoped>
.dialog-content{
    padding: $size16;
    max-height:500px
}

::v-deep .el-dialog__header{
    border-bottom: 1px solid $border-color-lighter !important;
}
::v-deep  .el-dialog__footer{
    border-top: 1px solid $border-color-lighter !important;
}
</style>