<template>
    <div>
        <el-container>
            <el-aside width="350px">
                <TeacherSide ref="getSelectData" @fircheck="fircheck" @twocheck="twocheck" @getData="getData"></TeacherSide>
            </el-aside>

            <el-main style="padding-top: 0">
                <el-col :span="24">
                    <el-card shadow="hover" class="mgb20 teacher_tab">
                        <div class="flex-between mgb20">
                            <div>
                                <el-input placeholder="请输入员工账号/姓名/工号" v-model="keyword">
                                    <i slot="suffix" class="el-input__icon el-icon-search"></i>
                                </el-input>
                            </div>
                            <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="55" align="center"></el-table-column>
                            <el-table-column type="index" label="序号" width="55" align="center">
                            </el-table-column>
                            <el-table-column prop="account" label="账号" align="center">
                            </el-table-column>
                            <el-table-column prop="userName" 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="NewaccountRole" label="账号角色" align="center">
                            </el-table-column>
                            <el-table-column prop="logInNumber" label="登录次数" align="center">
                            </el-table-column>
                            <el-table-column prop="lastLoginTime" label="上次登录时间" align="center">
                            </el-table-column>
                            <el-table-column label="操作" width="200" align="center">
                                <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="totals">
                            </el-pagination>
                        </div>
                    </el-card>
                </el-col>
            </el-main>
        </el-container>

        <!-- 新增用户 -->
        <el-dialog :title="isDetail ? '查看员工' : (isAddteacher ? '新增员工' : '编辑员工')" :visible.sync="teacherVisible"
         width="30%" center @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"></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-checkbox-group v-model="teacherForm.roleValue">
                        <el-checkbox label="老师"></el-checkbox>
                        <el-checkbox label="管理员"></el-checkbox>
                        <el-checkbox label="学生" disabled></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item prop="uniqueIdentificationAccount" label="唯一标识">
                    <el-input disabled v-model="teacherForm.uniqueIdentificationAccount" placeholder="请输入职工工号获取唯一标识"></el-input>
                </el-form-item>
                <template v-if="teacherForm.roleValue.some((n) => n == '老师')">
                    <el-form-item prop="teacherWorkNumber" label="老师职工工号">
                        <el-input v-model="teacherForm.teacherWorkNumber" placeholder="请输入老师职工工号" @change="OnlyId(14)"></el-input>
                    </el-form-item>
                    <el-form-item prop="teacherMajor" label="老师一级部门">
                        <el-select v-model="teacherForm.teacherMajor" placeholder="请选择一级部门" @change="getDepartment(14)">
                            <el-option v-for="(item,index) in majorList" :key="index"
                            :label="item.staffProfessionalArchitectureName" :value="item.staffProfessionalArchitectureId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="teacherDepartment" label="老师二级部门"> 
                        <el-select v-model="teacherForm.teacherDepartment" placeholder="请选择二级部门" :disabled="teacherForm.teacherMajor ? false : true">
                            <el-option v-for="(item,index) in teacherDepartmentList" :key="index"
                            :label="item.staffGradeName" :value="item.staffGradeId"></el-option>
                        </el-select>
                    </el-form-item>
                </template>
                <template v-if="teacherForm.roleValue.some((n) => n == '管理员')">
                    <el-form-item prop="managerWorkNumber" label="管理员职工工号">
                        <el-input v-model="teacherForm.managerWorkNumber" placeholder="请输入管理员职工工号" @change="OnlyId(13)"></el-input>
                    </el-form-item>
                    <el-form-item prop="managerMajor" label="管理员一级部门">
                        <el-select v-model="teacherForm.managerMajor" placeholder="请选择一级部门" @change="getDepartment(13)">
                            <el-option v-for="(item,index) in majorList" :key="index"
                            :label="item.staffProfessionalArchitectureName" :value="item.staffProfessionalArchitectureId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="managerDepartment" label="管理员二级部门"> 
                        <el-select v-model="teacherForm.managerDepartment" placeholder="请选择二级部门" :disabled="teacherForm.managerMajor ? false : true">
                            <el-option v-for="(item,index) in managerDepartmentList" :key="index"
                            :label="item.staffGradeName" :value="item.staffGradeId"></el-option>
                        </el-select>
                    </el-form-item>
                </template>
                
                <el-form-item prop="phone" label="手机号">
                    <el-input v-model="teacherForm.phone" placeholder="请输入手机号" maxlength="11" @change="phoneChange"></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="major" label="专业方向">
                    <el-select v-model="teacherForm.major" placeholder="请选择专业方向">
                        <el-option v-for="(item,index) in majorList1" :key="index"
                        :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item prop="schoolId" label="所在院校">
                    <el-select v-model="teacherForm.schoolId" placeholder="默认为当前院校（可修改）" filterable>
                        <el-option v-for="(item,index) in schoolList" :key="index" :label="item.schoolName" :value="item.schoolId"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer" v-if="!isDetail">
                <el-button @click="teacherVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveSure('teacherForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 批量导入 -->
        <el-dialog title="批量导入" :visible.sync="importVisible" width="24%" center :close-on-click-modal="false">
            <div style="text-align: center">
                <div style="margin-bottom: 10px;"><el-button type="primary" @click="downLoad">模板下载<i class="el-icon-download el-icon--right"></i></el-button></div>
                <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"
                    name="file"
                > 
                    <el-button type="primary" class="ml20">上传文件<i class="el-icon-upload2 el-icon--right"></i></el-button>
                </el-upload>
                <el-link v-if="uploadFaild" type="primary" @click="showFaild">部分数据导入失败，查看失败原因</el-link>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="importVisible = false">取 消</el-button>
                <el-button type="primary" @click="uploadSure">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import TeacherSide from './StaffSide.vue';
export default {
    data() {
        return {
            pages: 10,
            isDetail: false,
            isAddteacher: false,
            teacherVisible: false,
            schoolId: 2105,
            teacherForm: {
                teacherId: '',
                userName: '',
                roleValue: [],
                tearcherAccount: '',
                phone: '',
                uniqueIdentificationAccount: '',
                teacherWorkNumber: '',
                managerWorkNumber: '',
                email: '',
                teacherMajor: '',
                teacherDepartment: '',
                managerMajor: '',
                managerDepartment: '',
                userAccount: '',
                major: '',
                schoolId: this.schoolId
            },
            rules: {
                userAccount: [
                    { required: true, message: '请输入职工账号', trigger: 'blur' },
                    {
                        pattern: /^[a-zA-Z0-9_-]{1,16}$/,
                        message: '请输入正确的账号',
                        trigger: 'blur'
                    }
                ],
                userName: [
                    { required: true, message: '请输入用户姓名', trigger: 'blur' }
                ],
                roleValue: [
                    { required: true, message: '请选择账号角色', trigger: 'change' }
                ],
                tearcherAccount: [
                    { required: true, message: '请输入老师职工工号', trigger: 'blur' },
                    {
                        pattern: /^[0-9]*$/,
                        message: '职工工号必须为数字',
                        trigger: 'blur'
                    }
                ],
                uniqueIdentificationAccount: [
                    // { required: true, message: '请输入唯一标识', trigger: 'blur' },
                ],
                teacherWorkNumber: [
                    { required: true, message: '请输入老师职工工号', trigger: 'blur' },
                    {
                    pattern: /^[A-Za-z0-9]+$/,
                    message: '请输入正确的职工工号',
                    trigger: 'blur'
                    }
                ],
                teacherDepartment: [
                    { required: true, message: '请选择老师二级部门', trigger: 'change' }
                ],
                managerMajor: [
                    { required: true, message: '请选择管理员一级部门', trigger: 'change' }
                ],
                managerWorkNumber: [
                    { required: true, message: '请输入管理员职工工号', trigger: 'blur' },
                    {
                    pattern: /^[A-Za-z0-9]+$/,
                    message: '请输入正确的职工工号',
                    trigger: 'blur'
                    }
                ],
                managerDepartment: [
                    { required: true, message: '请选择管理员二级部门', trigger: 'change' }
                ],
                teacherMajor: [
                    { 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' }
                ],
            },
            listData: [],
            importVisible: false,
            keyword: '',
            pageNo: 1,
            pageSize: 10,
            totals: 0,
            managerDepartmentList: [],
            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: '',
            managerNumberNoAdd: true,
            teacherNumberNoAdd: true,
            studentNumberNoAdd: true,
            managerNumberNoAdd1: true,
            teacherNumberNoAdd1: true,
            platformId: this.$store.state.platformId,
            isManager: false,
            isTeacher: false,
            isNewUser: 1,
            schoolList: [],
            uploadFaild: false,
            token: ''
        };
    },
    components: {
        TeacherSide
    },
    watch: {
        keyword: function(val) {
            clearTimeout(this.searchTimer)
            this.searchTimer = setTimeout(() => {
                this.getData()
            },500)
        }
    },
    mounted(){
        this.getData()
        this.teacherForm.schoolId = 2105
        this.getSchoolData()
        // this.getSubject()
    },
    methods: {
        handleCheck(data){
            let oneDepartmentIds = []
            let twoDepartmentIds = []

            data.forEach( e => {
                if(e.ischeck){
                    oneDepartmentIds.push(e.staffProfessionalArchitectureId)
                }else{
                    this.removeByValue(oneDepartmentIds, e.staffProfessionalArchitectureId);
                }
                e.children.forEach( r => {
                    if(r.ischeck){
                        twoDepartmentIds.push(r.staffGradeId)
                    }else{
                        this.removeByValue(twoDepartmentIds, r.staffGradeId);
                    }
                })
            })
            this.oneDepartmentIds = oneDepartmentIds.toString()
            this.twoDepartmentIds = twoDepartmentIds.toString()
            this.getData()
        },
        fircheck(val,val2){
            val.ischeck = !val.ischeck
            val.children.map( e => e.ischeck = val.ischeck)
            this.handleCheck(val2)
        },
        twocheck(val,val2){
            val.ischeck = !val.ischeck
            val2.map( e => {
                e.children.map( r => {
                    if(r.staffGradeId == val.staffGradeId){
                        if(e.children.every(i => i.ischeck)){
                            e.ischeck = true
                        }else{
                            e.ischeck = false
                        }
                    }
                })
            })
            this.handleCheck(val2)
        },
        getData(){
            let data = {
                // staffProfessionalArchitectureIds: this.oneDepartmentIds,
                staffProfessionalArchitectureIds: '',
                staffGradeIds: this.twoDepartmentIds,
                searchContent: this.encodeString(this.keyword),
                page: this.pageNo,
                size: this.pageSize,
                schoolId: this.schoolId
            }
            this.$post(this.api.queryStaff,data).then(res => {
                this.listData = res.data.list
                this.totals = res.data.totalCount
                this.listData.forEach(e => {
                    if(e.roleId.length > 1) {
                        let NewaccountRole = []
                        let roleIds = e.roleId.split(',')
                        roleIds.forEach((n,k) => {
                            NewaccountRole.push(this.roleStatus(n))
                        })
                        e.NewaccountRole = NewaccountRole.join(',')
                    }else{
                        e.NewaccountRole = this.roleStatus(e.roleId)
                    }
                })
            }).catch(res => {});
        },
        getSchoolData(){
            let data = {
                schoolName: '',
                provinceId: '',
                cityId: ''
            }
            this.$get(this.api.querySchool,data).then(res => {
                this.schoolList = res.message
            }).catch(res => {});
        },
        closeTeacher(){
            this.teacherForm=  {
                teacherId: '',
                userName: '',
                roleValue: [],
                tearcherAccount: '',
                phone: '',
                uniqueIdentificationAccount: '',
                teacherWorkNumber: '',
                managerWorkNumber: '',
                email: '',
                teacherMajor: '',
                teacherDepartment: '',
                managerMajor: '',
                managerDepartment: '',
                userAccount: '',
                major: '',
                schoolId: this.schoolId
            }
            this.isManager = false
            this.isTeacher = false
            this.$refs.teacherForm.clearValidate()
        },
        addTeacher(){
            this.isDetail = false
            this.teacherVisible = true
            this.isAddteacher = true
            this.teacherForm.teacherId = ''
            this.majorList = this.$refs.getSelectData.majorList
            this.$refs.teacherForm.clearValidate()
        },
        getStaffDetail(userId){
            let data = {
                userId: userId
            }
            this.$get(this.api.querystaffDetail,data).then(res => {
                let user = res.data.userInfo;
                let or = res.data.staffInfo;
                this.teacherForm.userName = user.userName
                this.teacherForm.phone = user.phone
                this.teacherForm.email = user.email
                this.teacherForm.userAccount = user.account
                this.teacherForm.userId = user.userId
                this.teacherForm.schoolId = user.schoolId
                or.forEach((n,i) => {
                    this.teacherForm.roleValue.push(this.roleStatus(n.roleId))
                    if(n.roleId == 13) {
                        this.teacherForm.managerMajor = n.staffProfessionalArchitectureId
                        this.teacherForm.managerDepartment = n.staffGradeId
                        this.teacherForm.managerWorkNumber = n.workNumber
                        this.isManager = true
                        this.teacherForm.managerStaffId = n.staffId
                        this.getDepartment(13)
                    }else if(n.roleId == 14){
                        this.teacherForm.teacherMajor = n.staffProfessionalArchitectureId
                        this.teacherForm.teacherDepartment = n.staffGradeId
                        this.teacherForm.teacherWorkNumber = n.workNumber
                        this.isTeacher = true
                        this.teacherForm.teacherStaffId = n.staffId
                        this.getDepartment(14)
                    }
                })
            }).catch(res => {});
        },
        editTeacher(row){
            this.isDetail = false
            this.teacherVisible = true
            this.isAddteacher = false
            this.AccountNoAdd = false
            this.teacherForm.teacherId = row.userId
            this.majorList = this.$refs.getSelectData.majorList
            this.isNewUser = 0
            this.getStaffDetail(row.userId)
        },
        resetPassword(row){
            this.$confirm(`重置后的密码为：${this.$config.initialPassword}，确定重置？`, '提示', {
                }).then(() => {
                    let data = {
                        newPwd: this.$config.initialPassword,
                        userId: row.userId,
                    }
                    this.$get(this.api.resetPwd,data).then(res => {
                        if(res.errmessage == 'success'){
                            this.$message.success('重置成功')
                        }else{
                            this.$message.error('重置失败')
                        }
                    }).catch(res => {});
                }).catch(() => {
            });
        },
        showTeacher(row){
            this.isDetail = true
            this.teacherVisible = true
            this.isAddteacher = false
            this.AccountNoAdd = false
            this.teacherForm.teacherId = row.userId
            this.majorList = this.$refs.getSelectData.majorList
            this.isNewUser = 0
            this.getStaffDetail(row.userId)
        },
        getDepartment(type){
            let data = {
                staffProfessionalArchitectureId: type == 13 ? this.teacherForm.managerMajor : this.teacherForm.teacherMajor
            }
            this.$get(this.api.queryStaffGrade,data).then(res => {
                if(type == 13){
                    this.managerDepartmentList = res.message
                }else{
                    this.teacherDepartmentList = res.message
                }
            }).catch(res => {});
        },
        async phoneChange(){
            let res = await this.$get(this.api.queryPhone, { phone: this.teacherForm.phone });
            if(res.message.length != 0){
                this.$message.warning('该手机号已存在');
                this.NoAdd = false
            }else{
                this.NoAdd = true
            }
        },
        async accountChange(){
            let res = await this.$get(this.api.queryAccountIsExist, { 
                account: this.encodeString(this.teacherForm.userAccount),
                schoolId: this.schoolId
            });
            if(this.isAddteacher){
                this.isManager = false
                this.isTeacher = false
            }
            if(res.message.user.length != 0){
                let user = res.message.user[0];
                let or = res.message.OR;
                this.$message.warning('该账号已存在');
                this.teacherForm.email = user.email
                this.teacherForm.phone = user.phone
                this.teacherForm.uniqueIdentificationAccount = user.uniqueIdentificationAccount
                this.teacherForm.userName = user.userName
                // this.teacherForm.schoolId = user.schoolId
                this.teacherForm.userId = user.userId
                this.isNewUser = 0
                or.forEach((n,i) => {
                    this.teacherForm.roleValue.push(this.roleStatus(n.roleId))
                    if(n.roleId == 13) {
                        this.teacherForm.managerMajor = n.oneDepartmentId
                        this.teacherForm.managerDepartment = n.twoDepartmentId
                        this.teacherForm.managerWorkNumber = n.workNumber
                        this.teacherForm.managerSchoolId = n.schoolId
                        this.teacherForm.managerSchoolName = n.schoolName
                        this.isManager = true
                        this.getDepartment(13)
                    }else if(n.roleId == 14){
                        this.teacherForm.teacherMajor = n.oneDepartmentId
                        this.teacherForm.teacherDepartment = n.twoDepartmentId
                        this.teacherForm.teacherWorkNumber = n.workNumber
                        this.teacherForm.teacherSchoolId = n.schoolId
                        this.teacherForm.tacherSchoolName = n.schoolName
                        this.isTeacher = true
                        this.getDepartment(14)
                    }
                })
                this.AccountNoAdd = false
            }else{
                this.isNewUser = 1
                this.AccountNoAdd = true
            }
        },
        async submitOnlyId(){
            if(this.teacherForm.managerWorkNumber != ''){
                this.OnlyId(13)
            }else if(this.teacherForm.teacherWorkNumber != ''){
                this.OnlyId(14)
            }
        },
        async OnlyId(type){
            let workNumber = type == 13 ? this.encodeString(this.teacherForm.managerWorkNumber) : this.encodeString(this.teacherForm.teacherWorkNumber)
            let data = {
                workNumber,
                roleId: 13,
                schoolId: this.teacherForm.schoolId
            }
            let data1 = {
                workNumber,
                roleId: 14,
                schoolId: this.teacherForm.schoolId
            }
            let data2 = {
                workNumber,
                roleId: 4,
                schoolId: this.teacherForm.schoolId
            }
            let res = await this.$get(this.api.queryWorkNumberIsExist, data)
            let res1 = await this.$get(this.api.queryWorkNumberIsExist, data1)
            let res2 = await this.$get(this.api.queryWorkNumberIsExist, data2)
            if(type == 13 && JSON.stringify(res.message) != '{}'){
                this.$message.warning('该工号已存在');
                this.managerNumberNoAdd = false
            }else if(type == 14 && JSON.stringify(res1.message) != '{}'){
                this.$message.warning('该工号已存在');
                this.teacherNumberNoAdd = false
            }else if(JSON.stringify(res2.message) != '{}'){
                this.$message.warning('该工号已绑定学生角色');
                this.studentNumberNoAdd = false
            }else if(type == 14 && JSON.stringify(res.message) != '{}'){
                this.$message.warning('该工号已绑定管理员角色');
                this.managerNumberNoAdd1 = false
            }else if(type == 13 && JSON.stringify(res1.message) != '{}'){
                this.$message.warning('该工号已绑定老师角色');
                this.teacherNumberNoAdd1 = false
            }
            if(JSON.stringify(res.message) == '{}' && JSON.stringify(res1.message) == '{}' && JSON.stringify(res2.message) == '{}'){
                let timestamp = Date.parse(new Date());
                this.teacherForm.uniqueIdentificationAccount = `${this.schoolId}${this.teacherForm.uniqueIdentificationAccount}${timestamp}`
                type == 13 ? (this.managerNumberNoAdd = true) : (this.teacherNumberNoAdd = true)
            }
        },
        async saveSure(teacherForm){
            this.$refs[teacherForm].validate((valid) => {
                if (valid) {
                    if(this.isAddteacher) {
                        if(this.isManager && this.isTeacher) return this.$message.warning('该用户已经是老师和管理员，请重新添加');
                        if(this.isManager && !this.teacherForm.roleValue.some((n) => n == '老师')) return this.$message.warning('该用户已经是管理员');
                        if(this.isTeacher && !this.teacherForm.roleValue.some((n) => n == '管理员')) return this.$message.warning('该用户已经是老师');
                        if(!this.AccountNoAdd) return this.$message.warning('该账号已存在');
                        if(this.NoAdd == '' && this.teacherForm.phone){
                            this.phoneChange()
                            if(!this.NoAdd) return false
                        }else if(this.NoAdd === false) return this.$message.warning('该手机号已存在');
                    }
                    if(!this.managerNumberNoAdd) return this.$message.warning('该管理员工号已存在');
                    if(!this.teacherNumberNoAdd) return this.$message.warning('该老师工号已存在');
                    if(!this.managerNumberNoAdd1) return this.$message.warning('该工号已绑定管理员角色');
                    if(!this.teacherNumberNoAdd1) return this.$message.warning('该工号已绑定老师角色');
                    if(!this.studentNumberNoAdd) return this.$message.warning('该工号已绑定学生角色');
                    
                    let roleId = []
                    this.teacherForm.roleValue.forEach((n,k) => {
                        n == '老师' && roleId.push(14)
                        n == '管理员' && roleId.push(13)
                    })
                    let data = { 
                        userName: this.teacherForm.userName,
                        account: this.teacherForm.userAccount,
                        schoolId: this.teacherForm.schoolId,
                        roleId: roleId.join(','),
                        phone: this.teacherForm.phone,
                        email: this.teacherForm.email,
                        uniqueIdentificationAccount: this.teacherForm.uniqueIdentificationAccount ? this.teacherForm.uniqueIdentificationAccount : Date.parse(new Date()),
                        userId: this.teacherForm.userId ? this.teacherForm.userId : ''
                    }
                    data.staff = [];
                    if((!this.isAddteacher && this.teacherForm.managerWorkNumber && roleId.includes(13)) || (this.isAddteacher && !this.isManager && this.teacherForm.managerWorkNumber)){
                        let oneDepartmentName = '';
                        for(let i in this.majorList){
                            if(this.majorList[i].staffProfessionalArchitectureId == this.teacherForm.managerMajor) {
                                oneDepartmentName = this.majorList[i].staffProfessionalArchitectureName
                                break;
                            }
                        }
                        let twoDepartmentName = this.managerDepartmentList.find((n) => {
                            return n.staffGradeId == this.teacherForm.managerDepartment
                        }).staffGradeName;
                        let orList = {
                            roleId: 13,
                            staffId: this.teacherForm.managerStaffId,
                            workNumber: this.teacherForm.managerWorkNumber,
                            staffProfessionalArchitectureId: this.teacherForm.managerMajor,
                            staffGradeId: this.teacherForm.managerDepartment,
                            staffProfessionalArchitectureName: oneDepartmentName,
                            staffGradeName: twoDepartmentName,
                        };
                        data.staff.push(orList)
                    }
                    if((!this.isAddteacher && this.teacherForm.teacherWorkNumber && roleId.includes(14)) || (this.isAddteacher && !this.isTeacher && this.teacherForm.teacherWorkNumber)){
                        let oneDepartmentName = '';
                        for(let i in this.majorList){
                            if(this.majorList[i].staffProfessionalArchitectureId == this.teacherForm.teacherMajor) {
                                oneDepartmentName = this.majorList[i].staffProfessionalArchitectureName
                                break;
                            }
                        }
                        let twoDepartmentName = this.teacherDepartmentList.find((n) => {
                            return n.staffGradeId == this.teacherForm.teacherDepartment
                        }).staffGradeName;
                        let orList = {
                            roleId: 14,
                            staffId: this.teacherForm.teacherStaffId,
                            workNumber: this.teacherForm.teacherWorkNumber,
                            staffProfessionalArchitectureId: this.teacherForm.teacherMajor,
                            staffGradeId: this.teacherForm.teacherDepartment,
                            staffProfessionalArchitectureName: oneDepartmentName,
                            staffGradeName: twoDepartmentName,
                        };
                        data.staff.push(orList)
                    }
                    if(this.teacherForm.teacherId){
                        this.$put(this.api.updateStaff,data).then(res => {
                            this.teacherVisible = false
                            this.$message.success('编辑成功');
                            this.getData()
                        }).catch(res => {});
                    }else{
                        this.$post(this.api.addStaff,data).then(res => {
                            this.teacherVisible = false
                            this.$message.success('添加成功');
                            this.getData()
                        }).catch(res => {});
                    }
                }else{
                    return false;
                }
            })
        },
        delTeacher(row){
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
            .then(() => {
                this.$post(this.api.daleteBatchStaff,[row.userId]).then(res => {
                    this.$message.success('删除成功')
                    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.userId
                })
                // 批量删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                .then(() => {
                    let data = delList
                    this.$post(this.api.daleteBatchStaff,data).then(res => {
                        this.$refs.table.clearSelection()
                        this.$message.success('删除成功')
                        this.getData()
                    }).catch(res => {});
                }).catch(() => {});
            }else{
                this.$message.error('请先选择员工 ！')
            }
        },
        batchImport(){
            this.importVisible = true
            this.uploadList = []
            this.uploadFaild = false
        },
        searchTeacher(){
            this.pageNo = 1;
            this.getData()
        },
        handleCurrentChange(val) {
            this.pageNo = val;
            this.getData();
        },
        downLoad(){
            location.href = 'http://www.liuwanr.cn/template/staff.xlsx'
        },
        showFaild(){
            location.href = `${this.api.export_failureStaff}?token=${this.token}`
        },
        // 上传文件
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 1 个文件，如需更换，请删除上一个文件再重新选择！` 
            );
        },
        uploadSuccess(res, file, fileList) {
            this.uploadFaild = false
            if(res.errmessage == 'success'){
                if(res.data.token){
                    this.token = res.data.token
                    this.uploadFaild = true
                }else{
                    this.$message.success('上传成功')
                }
            }else{
                res.message ? this.$message.error(res.message) : this.$message.error('上传失败，请检查数据')
            }
        },
        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()
        },
        // 获取学科类别
        getSubject(){
            this.$get(this.api.queryCourseDiscipline).then(res => {
                this.subjectList = res.message
            }).catch(res => {});
        },
        // 清除学科类别
        clearClass(){
            this.teacherForm.professionalClassId = '',
            this.teacherForm.professionalId = ''
        },
        // 获取专业类
        getProfessionalClass(){
            this.clearClass()
            if(this.teacherForm.disciplineId){
                this.getProfessionalClassData()
            }
        },
        getProfessionalClassData(){
            let data = {
                disciplineId: this.teacherForm.disciplineId
            }
            this.$get(this.api.queryCourseProfessionalClass,data).then(res => {
                this.ProfessionalClassList = res.message
            }).catch(res => {});
        },
        // 清除专业类
        clearProfess(){
            this.teacherForm.professionalId = ''
        },
        // 获取专业
        getProfessional(){
            this.clearProfess()
            if(this.teacherForm.professionalClassId){
                this.getProfessionalData()
            }
        },
        getProfessionalData(){
            let data = {
                professionalClassId: this.teacherForm.professionalClassId
            }
            this.$get(this.api.queryCourseProfessional,data).then(res => {
                this.ProfessionalList = res.message
            }).catch(res => {});
        }
    }
};
</script>
<style scoped>
.el-container{
    background-color: #f0f0f0;
}
.mag{
    margin-right: 20px;
    margin-left: 20px;
}
</style>
