<template>
    <div>
        <div class="tool">
            <ul class="filter">
                <li>
                    <label>筛选：</label>
                    <el-cascader :options="orgList" :props="props" collapse-tags clearable size="small" @change="orgChange"></el-cascader>
                </li>
                <li>
                    <label>搜索：</label>
                    <el-input style="width: 250px" placeholder="请输入员工姓名/工号/角色名称" v-model="keyword" suffix-icon="el-icon-search" clearable size="small"></el-input>
                </li>
            </ul>
            <div>
                <el-button type="primary" size="small" round @click="addTeacher" v-auth="'system:员工管理:新增员工'">新增员工</el-button>
                <el-button type="primary" size="small" round @click="batchImport" v-auth="'system:员工管理:批量导入'">批量导入</el-button>
                <el-button type="primary" size="small" round @click="delAllSelection" v-auth="'system:员工管理:批量删除'">批量删除</el-button>
            </div>
        </div>
        <el-table :data="listData" class="table" ref="table" stripe header-align="center" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="80" align="center"></el-table-column>
            <el-table-column type="index" label="序号" width="55" align="center">
            </el-table-column>
            <el-table-column prop="userName" label="职工姓名" align="center">
            </el-table-column>
            <el-table-column prop="account" label="账号" align="center">
            </el-table-column>
            <el-table-column prop="workNumber" label="职工工号" align="center">
            </el-table-column>
            <el-table-column prop="staffProfessionalArchitectureName" label="一级部门" align="center">
            </el-table-column>
            <el-table-column prop="staffGradeName" label="二级部门" align="center">
            </el-table-column>
            <el-table-column prop="roleName" label="角色" align="center">
            </el-table-column>
            <el-table-column prop="lastLoginTime" label="上次登录时间" width="160" align="center">
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
                <template slot-scope="scope">
                    <el-button type="text" @click="showTeacher(scope.row)" v-auth="'system:员工管理:查看'">查看</el-button>
                    <el-button type="text" @click="editTeacher(scope.row)" v-auth="'system:员工管理:编辑'">编辑</el-button>
                    <el-button type="text" @click="resetPassword(scope.row)" v-auth="'system:员工管理:重置密码'">重置密码</el-button>
                    <el-button type="text" @click="delTeacher(scope.row)" v-auth="'system:员工管理:删除'">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination background layout="total,prev, pager, next" :current-page="pageNo" @current-change="handleCurrentChange" :total="total">
            </el-pagination>
        </div>
                    

        <!-- 新增用户 -->
        <el-dialog :title="isDetail ? '查看员工' : (isAddteacher ? '新增员工' : '编辑员工')" :visible.sync="teacherVisible" width="500px" @close="closeTeacher" class="dialog" :close-on-click-modal="false">
             <el-form ref="teacherForm" :model="teacherForm" :rules="rules" label-width="120px" :disabled="isDetail">
                 <el-form-item prop="userAccount" label="账号">
                    <el-input v-model="teacherForm.userAccount" ref="account" placeholder="请输入职工账号" @change="accountChange" maxlength="20"></el-input>
                </el-form-item>
                <el-form-item prop="userName" label="用户姓名">
                    <el-input v-model="teacherForm.userName" placeholder="请输入员工姓名"></el-input>
                </el-form-item>
                <el-form-item prop="roleValue" label="账号角色">
                    <el-select v-model="teacherForm.roleValue" placeholder="请选择账号角色">
                        <el-option v-for="(item,index) in roleList" :key="index" :label="item.roleName" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="uniqueIdentificationAccount" label="唯一标识">
                    <el-input disabled v-model="teacherForm.uniqueIdentificationAccount" placeholder="请输入职工工号获取唯一标识"></el-input>
                </el-form-item>
                <el-form-item prop="workNumber" label="职工工号">
                    <el-input v-model="teacherForm.workNumber" placeholder="请输入职工工号" @change="workNumberChange"></el-input>
                </el-form-item>
                <el-form-item prop="major" label="一级部门">
                    <el-select v-model="teacherForm.major" placeholder="请选择一级部门" @change="getDepartment">
                        <el-option v-for="(item,index) in orgList" :key="index"
                        :label="item.staffProfessionalArchitectureName" :value="item.staffProfessionalArchitectureId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="department" label="二级部门"> 
                    <el-select v-model="teacherForm.department" placeholder="请选择二级部门" :disabled="teacherForm.major ? false : true">
                        <el-option v-for="(item,index) in departmentList" :key="index"
                        :label="item.staffGradeName" :value="item.staffGradeId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="phone" label="手机号">
                    <el-input v-model="teacherForm.phone" placeholder="请输入手机号" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                    <el-input v-model="teacherForm.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item prop="email" label="默认密码">
                    <el-input v-model="password" disabled></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer" v-if="!isDetail">
                <el-button size="small" @click="teacherVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="saveSure('teacherForm')">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="查看员工" :visible.sync="staffShowVisible" width="500px" :close-on-click-modal="false">
            <ul class="list">
                <li>
                    <span class="name"><i class="required">*</i>账号：</span>
                    <span class="val">{{teacherForm.userAccount}}</span>
                </li>
                <li>
                    <span class="name"><i class="required">*</i>用户姓名：</span>
                    <span class="val">{{teacherForm.userName}}</span>
                </li>
                <li>
                    <span class="name">账号角色：</span>
                    <span class="val">{{teacherForm.roleValue ? roleList.find(n => n.id == teacherForm.roleValue).roleName : ''}}</span>
                </li>
                <li>
                    <span class="name">唯一标识：</span>
                    <span class="val">{{teacherForm.uniqueIdentificationAccount}}</span>
                </li>
                <li>
                    <span class="name"><i class="required">*</i>职工工号：</span>
                    <span class="val">{{teacherForm.workNumber}}</span>
                </li>
                <li>
                    <span class="name"><i class="required">*</i>一级部门：</span>
                    <span class="val">{{teacherForm.major ? orgList.find(n => n.staffProfessionalArchitectureId == teacherForm.major).staffProfessionalArchitectureName : ''}}</span>
                </li>
                <li>
                    <span class="name"><i class="required">*</i>二级部门：</span>
                    <span class="val">{{teacherForm.department ? departmentList.find(n => n.staffGradeId == teacherForm.department).staffGradeName : ''}}</span>
                </li>
                <li>
                    <span class="name">手机号：</span>
                    <span class="val">{{teacherForm.phone}}</span>
                </li>
                <li>
                    <span class="name">邮箱：</span>
                    <span class="val">{{teacherForm.email}}</span>
                </li>
                <li>
                    <span class="name">默认密码：</span>
                    <span class="val">{{password}}</span>
                </li>
            </ul>
        </el-dialog>

        <el-dialog title="批量导入" :visible.sync="importVisible" width="400px" :close-on-click-modal="false">
            <div class="upload-wrap" :class="{lg: uploadFaild}">
                <el-button class="download" size="small" @click="downLoad"><img src="../assets/img/download.png" alt=""> 模板下载</el-button>
                <el-upload accept=".xls,.xlsx" :on-remove="handleRemove" :on-error="uploadError" :on-success="uploadSuccess" :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed" :action="this.api.uploadFileStaff" :file-list="uploadList" :data="{schoolId: this.schoolId}" name="file"> 
                    <el-button size="small"><img src="../assets/img/upload.png" alt=""> 上传文件</el-button>
                </el-upload>
                <div class="link" v-if="uploadFaild">
                    <el-link type="primary" @click="showFaild">导入失败，查看原因</el-link>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="importVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="uploadSure">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import Setting from '@/setting';
export default {
    data() {
        return {
            schoolId: this.$store.state.schoolId,
            props: { multiple: true },
            orgList: [],
            isDetail: false,
            isAddteacher: false,
            teacherVisible: false,
            roleList: [
                {
                    id: '1',
                    roleName: '超级管理员(系统默认)'
                },{
                    id: '2',
                    roleName: '教师管理员(系统默认)'
                }
            ],
            teacherForm: {
                clientId: this.$store.state.schoolId,
                clientName: this.$store.state.schoolName,
                teacherId: '',
                userName: '',
                roleValue: '',
                phone: '',
                uniqueIdentificationAccount: '', 
                workNumber: '',
                email: '',
                major: '',
                department: '',
                userAccount: '',
                major: '',
                schoolId: this.schoolId
            },
            rules: {
                userAccount: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    {
                        pattern: /^[A-Za-z0-9]+$/,
                        message: '请输入正确的账号',
                        trigger: 'blur'
                    }
                ],
                userName: [
                    { required: true, message: '请输入用户姓名', trigger: 'blur' }
                ],
                roleValue: [
                    { required: true, message: '请选择账号角色', trigger: 'change' }
                ],
                uniqueIdentificationAccount: [
                    // { required: true, message: '请输入唯一标识', trigger: 'blur' },
                ],
                major: [
                    { required: true, message: '请选择一级部门', trigger: 'change' }
                ],
                workNumber: [
                    { required: true, message: '请输入职工工号', trigger: 'blur' },
                    {
                    pattern: /^[A-Za-z0-9]+$/,
                    message: '请输入正确的职工工号',
                    trigger: 'blur'
                    }
                ],
                department: [
                    { required: true, message: '请选择二级部门', trigger: 'change' }
                ],
                phone: [
                    // { required: true, message: '请输入职工手机号', trigger: 'blur' },
                    {
                    pattern: /^1[3456789]\d{9}$/,
                    message: '请输入正确的手机号',
                    trigger: 'blur'
                    }
                ],
                email: [
                    // { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {
                    pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
                    message: '请输入正确的邮箱',
                    trigger: 'blur'
                    }
                ],
                // schoolId: [
                //     { required: true, message: '请选择所在院校', trigger: 'change' }
                // ],
            },
            staffShowVisible: false,
            listData: [],
            importVisible: false,
            keyword: '',
            pageNo: 1,
            pageSize: 10,
            total: 0,
            departmentList: [],
            teacherDepartmentList: [],
            staffstateProfessId: '',
            staffGradeId: '',
            multipleSelection: [],
            uploadList: [],
            provinceId: this.$store.state.provinceId,
            cityId: this.$store.state.cityId,
            userId: this.$store.state.userId,
            oneDepartmentIds: '',
            twoDepartmentIds: '',
            ProfessionalClassList: [],
            subjectList: [],
            ProfessionalList: [],
            NoAdd: '',
            AccountNoAdd: '',
            NumberNoAdd: '',
            platformId: this.$store.state.platformId,
            schoolList: [],
            uploadFaild: false,
            token: '',
            accountRepeat: false,
            workNumberRepeat: false,
            originalAccount: '',
            originalWorkNumber: '',
            password: Setting.initialPassword,
            submiting: false
        };
    },
    watch: {
        keyword: function(val) {
            clearTimeout(this.searchTimer)
            this.searchTimer = setTimeout(() => {
                this.initData()
            },500)
        }
    },
    mounted(){
        this.getOrg()
        this.getData()
        this.getRoles()
    },
    methods: {
        getOrg(){
            let data = {
                schoolId: this.schoolId
            }
            this.$get(this.api.queryStaffPro,data).then(res => {
                let firList = res.data.StaffProfessionalArchitectureList
                if(firList){
                    firList.map(e => {
                        e.isParent = true
                        e.value = e.staffProfessionalArchitectureId
                        e.label = e.staffProfessionalArchitectureName
                        let data = {
                            staffProfessionalArchitectureId: e.staffProfessionalArchitectureId
                        }
                        this.$get(this.api.queryStaffGrade,data).then(res1 => {
                            res1.data.staffGradeList.map(e => {
                                e.value = e.staffGradeId
                                e.label = e.staffGradeName
                            })
                            e.children = res1.data.staffGradeList
                        }).catch(res => {})
                    })
                    setTimeout(() => {
                        this.orgList = firList
                    },500)
                }
            }).catch(res => {})
        },
        getData(){
            let data = {
                staffProfessionalArchitectureIds: this.oneDepartmentIds,
                staffGradeIds: this.twoDepartmentIds,
                searchContent: this.keyword,
                schoolId: this.schoolId
            }
            this.$get(`${this.api.queryStaff}/${this.pageNo}/${this.pageSize}`,data).then(res => {
                this.listData = res.data.staffList
                this.total = res.data.total
                if(!this.listData.length && this.total){
                    this.pageNo--
                    this.getData()
                }
            }).catch(res => {});
        },
        initData(){
            this.pageNo = 1
            this.getData()
        },
        orgChange(node){
            this.twoDepartmentIds = node.map(n => n[1]).toString()
            this.getData()
        },
        getRoles(){
            this.$get(this.api.getRoles,{clientId: this.schoolId}).then(res => {
                this.roleId = res.data.data[0].id
                this.roleList = this.roleList.concat(res.data.data)
            })
        },
        resetPassword(row){
            this.$confirm(`重置后的密码为：${Setting.initialPassword}，确定重置？`, '提示', {
                }).then(() => {
                    let data = {
                        userId: row.userId,
                        password: Setting.initialPassword
                    }
                    this.$post(this.api.userinfoUpdate,data).then(res => {
                        if(res.success){
                            this.successMsg('重置成功')
                        }else{
                            this.errorMsg('重置失败')
                        }
                    }).catch(res => {});
                }).catch(() => {
            });
        },
        accountChange(){
            if(this.teacherForm.userAccount !== this.originalAccount){
                this.$get(`${this.api.getAccount}?account=${this.teacherForm.userAccount}`).then(res => {
                    if(res.data.userInfo){
                        this.accountRepeat = true
                        this.warningMsg('该账号已存在')
                    }else{
                        this.accountRepeat = false
                    }
                }).catch(res => {});
            }else{
                this.accountRepeat = false
            }
        },
        workNumberChange(){
            if(this.teacherForm.workNumber !== this.originalWorkNumber){
                this.$get(`${this.api.getWorkNumber}?workNumber=${this.teacherForm.workNumber}`).then(res => {
                    if(res.data.staff){
                        this.workNumberRepeat = true
                        this.warningMsg('该工号已存在')
                    }else{
                        this.workNumberRepeat = false
                    }
                }).catch(res => {});
            }else{
                this.workNumberRepeat = false
            }
        },
        closeTeacher(){
            this.$refs.teacherForm.resetFields()
            this.teacherForm.clientId = this.$store.state.schoolId
            this.teacherForm.clientName = this.$store.state.schoolName
            this.teacherForm.department = ''
            this.teacherForm.major = ''
            this.teacherForm.workNumber = ''
            this.teacherForm.userId = ''
            this.teacherForm.staffId = ''
        },
        addTeacher(){
            this.isDetail = false
            this.teacherVisible = true
            this.isAddteacher = true
            this.teacherForm.teacherId = ''
        },
        getStaffDetail(userId){
            this.$get(`${this.api.getStaff}/${userId}`).then(res => {
                let user = res.data.userInfo;
                let or = res.data.staff;
                this.teacherForm.uniqueIdentificationAccount = user.uniqueIdentificationAccount
                this.teacherForm.clientId = user.clientId
                this.teacherForm.clientName = user.clientName
                this.teacherForm.userName = user.userName
                this.teacherForm.phone = user.phone
                this.teacherForm.email = user.email
                this.teacherForm.userAccount = user.account
                this.originalAccount = Number(user.account)
                this.teacherForm.userId = user.userId
                this.teacherForm.schoolId = user.schoolId
                this.teacherForm.roleValue = user.roleId

                this.teacherForm.major = or.staffProfessionalArchitectureId
                this.teacherForm.department = or.staffGradeId
                this.teacherForm.workNumber = or.workNumber
                this.originalWorkNumber = or.workNumber
                this.isManager = true
                this.teacherForm.staffId = or.staffId
                this.getDepartment(1)
            }).catch(res => {});
        },
        editTeacher(row){
            this.isDetail = false
            this.teacherVisible = true
            this.isAddteacher = false
            this.AccountNoAdd = false
            this.teacherForm.teacherId = row.staffId
            this.getStaffDetail(row.staffId)
        },
        showTeacher(row){
            this.isDetail = true
            this.staffShowVisible = true
            this.isAddteacher = false
            this.AccountNoAdd = false
            this.teacherForm.teacherId = row.staffId
            this.getStaffDetail(row.staffId)
        },
        getDepartment(isDetail){
            if(!isDetail) this.teacherForm.department = ''
            let data = {
                staffProfessionalArchitectureId: this.teacherForm.major
            }
            this.$get(this.api.queryStaffGrade,data).then(res => {
                this.departmentList = res.data.staffGradeList
            }).catch(res => {});
        },
        async saveSure(teacherForm){
            if(this.submiting) return false
            this.$refs[teacherForm].validate((valid) => {
                if (valid) {
                    if(this.accountRepeat) return this.warningMsg('该账号已存在')
                    if(this.workNumberRepeat) return this.warningMsg('该工号已存在')
                    let isTeacher = false
                    let isManager = false
                    let data = { 
                        userInfo: {
                            userId: this.teacherForm.userId,
                            userName: this.teacherForm.userName,
                            account: this.teacherForm.userAccount,
                            schoolId: this.teacherForm.schoolId,
                            clientId: this.teacherForm.clientId,
                            clientName: this.teacherForm.clientName,
                            roleId: this.teacherForm.roleValue,
                            phone: this.teacherForm.phone,
                            email: this.teacherForm.email,
                            isPort: 2,
                            uniqueIdentificationAccount: this.teacherForm.uniqueIdentificationAccount ? this.teacherForm.uniqueIdentificationAccount : Date.parse(new Date()),
                        }
                    }
                    let oneDepartmentName = '';
                    for(let i in this.orgList){
                        if(this.orgList[i].staffProfessionalArchitectureId == this.teacherForm.major) {
                            oneDepartmentName = this.orgList[i].staffProfessionalArchitectureName
                            break;
                        }
                    }
                    let twoDepartmentName = this.departmentList.find((n) => {
                        return n.staffGradeId == this.teacherForm.department
                    }).staffGradeName;
                    data.staff = {
                        roleId: this.teacherForm.roleValue,
                        isPort: 2,
                        schoolId: this.schoolId,
                        staffId: this.teacherForm.staffId,
                        userId: this.teacherForm.userId,
                        workNumber: this.teacherForm.workNumber,
                        staffProfessionalArchitectureId: this.teacherForm.major,
                        staffGradeId: this.teacherForm.department,
                        staffProfessionalArchitectureName: oneDepartmentName,
                        staffGradeName: twoDepartmentName,
                    };
                    this.submiting = true

                    if(this.teacherForm.teacherId){
                        this.$post(this.api.updateStaff,data).then(res => {
                            this.submiting = false
                            this.teacherVisible = false
                            this.successMsg('编辑成功');
                            this.getData()
                        }).catch(res => {
                            this.submiting = false
                        });
                    }else{
                        this.$post(this.api.addStaff,data).then(res => {
                            this.submiting = false
                            this.teacherVisible = false
                            this.successMsg('添加成功');
                            this.getData()
                        }).catch(res => {
                            this.submiting = false
                        });
                    }
                }else{
                    return false;
                }
            })
        },
        delTeacher(row){
            this.$confirm('此删除操作不可逆，是否确认删除选中项？', '提示', {
                type: 'warning'
            })
            .then(() => {
                let data = {
                    staffIds: row.staffId
                }
                this.$del(this.api.deleteStaffs,data).then(res => {
                    this.successMsg('删除成功')
                    this.getData()
                }).catch(res => {});
            })
            .catch(() => {});
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            if(this.multipleSelection.length != ''){
                let newArr = this.multipleSelection
                let delList = newArr.map(item => {
                    return item.staffId
                })
                // 批量删除
                this.$confirm(`此批量删除操作不可逆，是否确认删除${newArr[0].userName}等${newArr.length}个选中项？`, '提示', {
                    type: 'warning'
                })
                .then(() => {
                    let data = {
                        staffIds: delList.join(',')
                    }
                    this.$del(this.api.deleteStaffs,data).then(res => {
                        this.$refs.table.clearSelection()
                        this.successMsg('删除成功')
                        this.getData()
                    }).catch(res => {});
                }).catch(() => {});
            }else{
                this.errorMsg('请先选择数据 ！')
            }
        },
        batchImport(){
            this.importVisible = true
            this.uploadList = []
            this.uploadFaild = false
        },
        handleCurrentChange(val) {
            this.pageNo = val;
            this.getData();
        },
        downLoad(){
            location.href = this.api.downloadStaffTemp
        },
        showFaild(){
            location.href = `${this.api.exportFailureStaff}?token=${this.token}`
        },
        // 上传文件
        handleExceed(files, fileList) {
            this.warningMsg(
                `当前限制选择 1 个文件，如需更换，请删除上一个文件再重新选择！` 
            );
        },
        uploadSuccess(res, file, fileList) {
            this.uploadFaild = false
            if(res.success){
                if(res.data.data.token){
                    this.token = res.data.data.token
                    this.uploadFaild = true
                }else{
                    this.successMsg('上传成功')
                }
            }else{
                res.data.message ? this.errorMsg(res.data.message) : this.errorMsg('上传失败，请检查数据')
            }
        },
        uploadError(err, file, fileList) {
            this.$message({
                message: "上传出错，请重试！",
                type: "error",
                center: true
            });
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        handleRemove(file, fileList) {
            this.uploadList = fileList
            this.uploadFaild = false
        },
        uploadSure(){
            this.importVisible = false
            this.pageNo = 1
            this.keyword = ''
            this.getData()
        }
    }
};
</script>
<style lang="scss" scoped>
    /deep/.dialog{
        .el-form-item{
            .el-form-item__label{
                font-size: 16px;
                color: rgba(0, 0, 0, 0.65);
                &:before{
                    margin-right: 0;
                    color: #CC221C;
                }
            }
        }
        .el-input,.el-select{
            width: 100%;
        }
    }
    .list{
        li{
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 32px 0;
            .name,.val{
                font-size: 16px;
                color: rgba(0, 0, 0, 0.65);
            }
            .name{
                width: 45%;
                text-align: right;
            }
            .val{
                width: 55%;
            }
        }
    }
</style>
