<template>
    <div class="page_search" ref="page_content">
        <div class="search_content">
            <div class="content_left">
                <el-button class="tab_button" @click="ChangeActiveTab('enableUse')" :class="statusPage=='enableUse'?'select_cur':''">启用用户</el-button>
                <el-button class="tab_button" @click="ChangeActiveTab('disabledUse')" :class="statusPage=='disabledUse'?'select_cur':''">禁用用户</el-button>
                <el-button class="tab_button" @click="ChangeActiveTab('lsuser')" :class="statusPage=='lsuser'?'select_cur':''">临时用户</el-button>
            </div>
        </div>
        <div class="page_jg"></div>
        <div class="search_content">
            <div class="content_left">
                <el-input style="width: 230px;" v-model="keyWord" @input="SearchTeacher" placeholder="教师姓名、账号">
                    <el-button slot="append" icon="el-icon-search" @click="SearchTeacher"></el-button>
                </el-input>
            </div>
            <div class="content_right">
                <!-- <el-button @click="ResetPassWord('AllUser')">重置密码</el-button> -->

                <el-button @click="BathDisabled" v-if="statusPage=='disabledUse'||statusPage=='enableUse'">{{ statusPage=='disabledUse'?'批量启用':'批量禁用' }}</el-button>
                <input type="file" ref="uploadStudents" @change="ImportTeacherList" enctype="multipart/form-data" style="display:none;"/>
                <el-button @click="BatchExport">批量导出</el-button>

                <el-tooltip class="item" effect="dark" content="当前导入的为教师用户的基本信息" placement="top">
                    <el-button  @click="BatchImport" v-if="statusPage=='enableUse'">批量导入</el-button>
                </el-tooltip>

                <!-- <el-button @click="uploadImage" v-if="statusPage=='enableUse'">上传头像</el-button> -->

                <input type="file" ref="fileImage" accept="image/*" multiple @change="handleFiles" style="display:none"/>

                <!-- <el-button class="dowmTepl"  @click="DownloadTemplent()">下载模板</el-button> -->

                <el-button type="primary" plain  @click="AddTeach()" v-if="statusPage=='enableUse'">新增教师</el-button>
            </div>
        </div>
        <div class="page_jg_16"></div>
        <div class="page_table">
            <el-table ref="teacherTable" :data="teacherList" border stripe @selection-change="HandleSelectionChange" :height="tableHeight">
                <el-table-column type="selection" width="55"  align="center"></el-table-column>
                <el-table-column type="index" label="序号" :index="GetIndexNumber" width="80" align="center"></el-table-column>
                <el-table-column prop="headPic" label="头像" align="center">
                    <template slot-scope="scope">
                        <img :src="scope.row.headPic" alt="" class="picStyle" v-if="scope.row.headPic">
                        <div v-else>-</div>
                    </template>
                </el-table-column>
                <el-table-column prop="userAccount" label="账号" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.userAccount }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="teacherName" label="姓名" align="center">
                    <template slot-scope="scope">
                        <div>{{ !scope.row.teacherName?'-':scope.row.teacherName }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="gender" label="性别" align="center">
                    <template slot-scope="scope">
                    <div>
                        {{  scope.row.gender == 1 ? '女' :scope.row.gender ==0? '男':'-'}}
                    </div>
                    </template>
                </el-table-column>
                <el-table-column prop="email" label="邮箱" align="center" show-overflow-tooltip :cell-class-name="'ellipsis-tooltip'">
                    <template slot-scope="scope">
                        <span>{{ scope.row.email || '-' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="userType" label="类型" align="center">
                    <template slot-scope="scope">
                        <!-- 用户类型0-正式,1-临时用户 -->
                        {{scope.row.userType==0 ? '正式' : '临时'}}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" align="center">
                    <template slot-scope="scope">
                        <div class="table_row_status">
                            <div :class="scope.row.status==1?'normal_icon':'abnormal_icon'"></div>&nbsp;{{  scope.row.status == 1 ? '启用' : '禁用'}}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="360px">
                <template slot-scope="scope">
                    <div class="table_row_option">
                        <!-- <div  class="button_delete" @click="UpdateEmail(scope.row)">{{!scope.row.email?'绑定邮箱':'解绑邮箱'}}</div> -->
                        <div  class="button_editor" @click="AddTeach('edit', scope.row)">编辑</div>
                        <div  class="button_editor" @click="ResetPassWord(scope.row)">重置密码</div>
                        <div  class="button_editor" @click="DisabledTeach(scope.row)">{{!scope.row.status?'启用':'禁用'}}</div>
                        <div  class="button_delete" @click="DeleteTeach(scope.row)">删除</div>
                    </div>
                </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="page_pagination" style=" margin-bottom: 10px;">
            <el-pagination
                @current-change="ChangePage"
                background
                layout="sizes,prev, pager, next"
                @size-change="HandleSizeChange"
                :page-sizes="[20,50,100]"
                :current-page="pageInfo.pageNum"
                :total="pageInfo.total">
            </el-pagination>
        </div>
        <div class="page_dialog">
            <!-- 新增教师-->
            <el-dialog :title="editTeachData.title" center :visible.sync="editTeachData.dialogShow" width="480px">
                <div class="dialog_center padding_20">
                    <el-form :model="editTeachData"  :rules="editTeachDataRules" ref="editTeachData" label-width="110px">
                        <el-form-item label="账号：" prop="userAccount">
                            <el-input v-model="editTeachData.userAccount" ></el-input>
                        </el-form-item>
                        
                        <el-form-item label="姓名：" prop="teacherName">
                            <el-input v-model="editTeachData.teacherName"></el-input>
                        </el-form-item>
                        <el-form-item label="性别：" prop="gender">
                            <el-select v-model="editTeachData.gender" placeholder="请选择" style="width:100%;">
                                <el-option
                                    v-for="item in genderOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editTeachData.dialogShow = false">取 消</el-button>
                    <el-button type="primary" @click="ConfirmTeacherAdd">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 重置密码 -->
            <el-dialog title="重置密码" center :visible.sync="editPassWordData.dialogShow"  width="480px">
                <div class="dialog_center padding_20">
                    <el-form :model="editPassWordData" ref="editPassWordData"  label-width="110px" >
                        <el-form-item label="教师姓名：" prop="teacherName" >
                            <el-input :value="editPassWordData.teacherName" disabled/>
                        </el-form-item>
                       
                        <el-form-item label="重置方式：">
                            <el-radio-group v-model="editPassWordData.useDefault">
                                <el-radio label="0">使用新密码</el-radio>
                                <el-radio label="1">重置为默认密码</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="新密码：" v-if="editPassWordData.useDefault=='0'">
                            <el-input v-model="editPassWordData.randomPassword" />
                        </el-form-item>
                        <el-form-item label="默认密码：" v-if="editPassWordData.useDefault=='1'">
                            <div class="default_pass">
                                <el-input value="******" disabled/>
                                <p>默认密码：学校编号@教师账号</p>
                            </div>
                            
                        </el-form-item>
                    </el-form>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="small" @click="editPassWordData.dialogShow = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="ConfirmPassWord" :loading="loading">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 批量禁用 -->
            <el-dialog title="批量禁用" center width="450px" :visible.sync="batchDisabledData.dialogShow">
                <el-form :model="batchDisabledData"  label-width="80px">
                <el-form-item label="禁用:" prop="isOverGrade">
                    <el-radio-group v-model="radioDisabled">
                        <el-radio :label="0">禁用</el-radio>
                        <el-radio :label="1">启用</el-radio>
                    </el-radio-group>
                </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="small" @click="batchDisabledData.dialogShow = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="confirmBatchDisabled">确 定</el-button>
                </div>
            </el-dialog>
        </div>
        
    </div>
</template>
<script>
import { throttle } from "lodash";
import { encrypt } from "@/utils/jsencrypt";
    export default{
        name:"teachtName",
        data(){
            return {
                selTermList:{
                    value:"",
                    name:"",
                    schoolGradeId:"",
                    arr:[]
                },
                queryData:{
                    "semesterId":"",
                    "classType":"", //0-行政班 1-教学班
                    "courseId":"",
                    "queryStr":"",
                    "schoolClassId":""
                },
                teacherList:[],//教师列表

                pageInfo:{
                    total:0,
                    pageSize:20,
                    pageNum:1,
                },//页面初始数据

                keyWord:'',//搜索输入框数据


                editTeachData:{
                    "dialogShow":false,
                    "title":"新增教师",//弹窗标题
                    "isEdit":false,//是否编辑
                    "gender": 0,//性别，2-未知，0-男，1-女
                    "email": "",//邮箱
                    "id":"",//id
                    "teacherCode":"",//教师ID(教工号) 暂未使用
                    "teacherName":"",//教师姓名
                    "userAccount":"",//用户账号
                    "teacherId":"",//教师id
                },
                editTeachDataRules: {
                   
                    userAccount: [
                        { required: true, message: '请输入账号', trigger: 'blur' },
                        { min: 6, max: 30, message: '账号名称6-30个字符', trigger: 'blur' }
                    ],
                    teacherName: [
                        { required: true, message: '请输入姓名', trigger: 'blur' },
                    ],
                    gender: [
                        { required: false, message: '', trigger: 'blur' },
                    ],
                },
                batchDisabledData:{
                    dialogShow:false,
                },
                genderOptions:[{
                    value: 2,
                    label: '-'
                },{
                    value: 0,
                    label: '男'
                },{
                    value: 1,
                    label: '女'
                }],
                isEdit:"",
                useStyle:{
                    background:"#2E64FA",
                    color:"#fff",
                    border:'1px solid #2E64FA',
                },
                disabledStyle:{
                    background:"#fff",
                    color:"#666666",
                    border: "1px solid #DCDFE6"
                },
                lsyhStyle:{
                    background:"#fff",
                    color:"#666666",
                    border: "1px solid #DCDFE6"
                },
                statusPage:"enableUse",//默认启用账号

                editPassWordData:{
                    dialogShow:false,
                    useDefault:'1',//重置方式0 新密码  1 默认密码
                    id:"",//用户id
                    teacherName:"",//用户姓名
                    randomPassword:""//新密码
                },//教师重置密码

                editPassWordDataRules:{
                    randomPassword:[
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
                    ],
                },

                checkPass:false,
                setPass:"",
                radioDisabled:0,
                files: [],
                multipleSelection:[],
                loading: false,
                mainHeight:0,
                tableHeight:0,//table高度

            }
        },
        mounted(){
            this.GetTeacherList();//获取教师列表
            this.SetTableHeight(); //设置表格高度
            window.addEventListener("resize", this.HandleResize); //监听窗口大小变化
        },
        beforeDestroy() {
            // 组件销毁移除监听 防止内存泄漏
            window.removeEventListener("resize", this.HandleResize);
        },
        methods:{
            //获取序号
            GetIndexNumber(index) 
            {
            
                let indexCount=(this.pageInfo.pageNum - 1) * this.pageInfo.pageSize + index +1 ;
                return indexCount   
                
            },
            // 监听窗口大小变化，重新计算表格高度 使用节流防止频繁改变窗口大小导致计算量过大而页面卡顿
            HandleResize: throttle(function () {
                this.SetTableHeight();
            }, 500), // 节流 500 毫秒内最多执行一次
            //设置表格高度
            SetTableHeight() 
            {
                let windowViewHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
               
                this.$nextTick(() => {
                    this.tableHeight = windowViewHeight - 365;
                });
            },



            //获取教师列表
            GetTeacherList()
            {
                let param = {
                    userType:0,
                    accountName:this.keyWord,//用户名称 
                    pageNum:this.pageInfo.pageNum,
                    pageSize:this.pageInfo.pageSize,
                    status:1,//正式用户必传 0=禁用 1=启用  
                };
                //
                if(this.statusPage=='enableUse')
                {   
                    //启用账户
                    param.userType=0;//临时账号	用户类型0-正式,1-临时用户
                    param.status=1;//启用
                }
                if(this.statusPage=='disabledUse')
                {   
                    //禁用账号
                    param.userType=0;//临时账号	用户类型0-正式,1-临时用户
                    param.status=0;//启用
                }
                if(this.statusPage=='lsuser')
                {
                    //临时账号
                    param.userType=1;//临时账号	用户类型0-正式,1-临时用户
                    param.status=1;
                }

                
                this.$api.user.getTeacherList(param).then(res=>{
                    if(res.code == 200)
                    {
                        this.teacherList = res.data.records || [];
                        this.pageInfo.total = parseInt(res.data.total);
                       

                    }
                })
            },
            //重置分页数据
            ResetPageData()
            {
                this.pageInfo={
                    total:0,
                    pageSize:20,
                    pageNum:1,
                };
            },
            //切换tab
            ChangeActiveTab(item)
            {
                this.statusPage = item;
                this.ResetPageData();
                this.GetTeacherList();//获取教师列表
            },

            //搜索教师
            SearchTeacher(){
                
                this.ResetPageData();
                this.GetTeacherList();//获取教师列表
            },
            //页面改变
            ChangePage(e){
                this.pageInfo.pageNum = e;
                this.GetTeacherList();//获取教师列表
                this.TableScrollTop();
            },

            //页面分页切换改变
            HandleSizeChange(val)
            {
                this.pageInfo.pageSize = val;
                this.GetTeacherList();//获取教师列表
                this.TableScrollTop();
            },

            //重置表格滚动条
            TableScrollTop()
            {

                this.$nextTick(() => {
                    if (this.$refs.teacherTable) {
                    const tableBody = this.$refs.teacherTable.$el.querySelector('.el-table__body-wrapper');
                    if (tableBody) {
                        tableBody.scrollTop = 0;
                    }
                    } 
                });
            },

            //编辑新增教师确定
            ConfirmTeacherAdd()
            {
                this.$refs["editTeachData"].validate((valid) => {
                    if (valid) 
                    {

                        let param={
                            "gender": this.editTeachData.gender,
                            "teacherCode": this.editTeachData.teacherCode,
                            "teacherId": this.editTeachData.teacherId,
                            "teacherName": this.editTeachData.teacherName,
                            "userAccount": this.editTeachData.userAccount
                        };
                        if(this.editTeachData.isEdit)
                        {
                            param.id=this.editTeachData.id;
                        }
                        
                        this.$api.user.addAndUpdateTeacher(param).then((res)=>{
                            if(res.code == 200)
                            {
                                this.$message.success("保存成功！")
                                this.editTeachData.dialogShow = false;
                                this.GetTeacherList();
                            }
                            else
                            {
                                this.$message.error("保存失败！"+res.msg)
                            
                            }
                        })
                    }
                })
            },

            //重置密码
            ResetPassWord(item)
            {
                this.editPassWordData={
                    dialogShow:true,
                    useDefault:'1',//重置方式0 新密码  1 默认密码
                    id:item.id,//用户id
                    teacherName:item.teacherName,//用户姓名
                    randomPassword:''//新密码
                };
            },

            //重置密码
            ConfirmPassWord()
            {
                if(this.editPassWordData.useDefault=='1')
                {
                    //默认密码
                    let param={
                        ids: [this.editPassWordData.id],//用户id
                        useDefault: 1//重置方式 使用默认密码 0-否 1-是
                    };
                    this.loading=true;
                    this.$api.user.resetPassWord(param).then(res=>{
                        this.loading=false;
                        if(res.code==200)
                        {
                            this.$message({
                                type: 'success',
                                message:"重置成功!"
                            });
                            this.editPassWordData.dialogShow = false;
                        }
                        
                    })
                }
                else
                {
                    //新密码
                    if(this.editPassWordData.randomPassword)
                    {

                    }
                    else
                    {
                        this.$message({
                            message: '请输入新密码',
                            type: 'warning'
                        });
                        return
                    }

                    let param={
                        ids: [this.editPassWordData.id],//用户id
                        password: encrypt(this.editPassWordData.randomPassword.trim()),//新密码
                        useDefault: 0//重置方式 使用默认密码 0-否 1-是
                    };
                    this.loading=true;
                    this.$api.user.resetPassWord(param).then(res=>{
                        this.loading=false;
                        if(res.code==200)
                        {
                            this.$message({
                                type: 'success',
                                message:"重置成功!"
                            });
                            this.editPassWordData.dialogShow = false;
                        }
                        
                    })

                }
                
               
               
            },
            //表格选择事件
            HandleSelectionChange(val) 
            {
                this.multipleSelection = val;
            },
            //批量禁用 或者启用
            BathDisabled()
            {
                if(this.multipleSelection.length===0)
                {
                    this.$message({
                        message: '请至少选择一个用户!',
                        type: 'warning'
                    });
                    return;
                }
                let ids=[];
                let status=1;//启用
                this.multipleSelection.map(item=>ids.push(item.id));
                if(this.statusPage=='disabledUse')
                {
                    status=1;//启用
                }
                else
                {
                    status=0;//禁用
                }

                let param = {
                    ids:ids,
                    status:status,//状态 1-启用 0-禁用
                };
                this.$api.user.updateUserEnable(param).then((res)=>{
                    if(res.code == 200)
                    {
                        this.$message({
                            type: 'success',
                            message: '操作成功!'
                        });
                        this.GetTeacherList();
                    }
                })

            },
            //批量禁用确定
            confirmBatchDisabled() {
                if (this.multipleSelection.length === 0) {
                    let warningMessage = this.statusPage == 'disabledUse'
                        ? '未选择启用的数据' 
                        : '未选择禁用的数据';
                    this.$message.warning(warningMessage);
                    return; // 提前返回，避免嵌套
                }
                let param = { ids:[] };
                this.multipleSelection.map(a=>param.ids.push(a.id))
                this.$api.school.updateStatusEnable(param)
                    .then((res) => {
                        if (res.code === 200) {
                            this.$message({
                                type: 'success',
                                message: res.msg
                            });
                            // this.batchDisabledData.dialogShow = false;
                            this.loading=false;
                            this.resetPageData();
                            this.teacherList=[];
                            this.listTeacherUser(this.statusPage);
                        }
                    })
                    .catch((error) => {
                        // 处理错误
                        this.$message.error('操作失败，请重试');
                        console.error(error);
                    });
            },
            // 批量导入教师列表
            ImportTeacherList(){
                let formdata = new FormData();
                formdata.append("file",this.$refs.uploadStudents.files[0]);
                this.$api.user.importTeacherList(formdata).then((res)=>{
                    if(res.code == 200){
                        //刷新
                        this.$message.success("导入成功");
                        this.GetTeacherList();//获取教师列表
                    }
                    else
                    {
                        // this.$message.error("导入失败");
                        this.$confirm("导入失败!  "+res.msg, '提示', {
                            confirmButtonText: '确定',
                            showCancelButton: false,
                            closeOnClickModal:false,
                            customClass: "page_dialog",
                            type: 'error'
                        }).then(() => {

                        }).catch(() => { });
                    }
                    this.$refs.uploadStudents.value = '';
                })
            },

            //批量导入教师事件
            BatchImport(){
                this.$refs.uploadStudents.value = null;
                this.$refs.uploadStudents.click();
            },

            //批量导出
            BatchExport()
            {

                let param = {
                    userType:0,//用户类型0-正式,1-临时用户
                    accountName:this.keyWord,//用户名称
                    status:1,//正式用户必传 0=禁用 1=启用  
                }
                
                if(this.statusPage=='enableUse')
                {   
                    //启用账户
                    param.userType=0;//临时账号	用户类型0-正式,1-临时用户
                    param.status=1;//启用
                }
                if(this.statusPage=='disabledUse')
                {   
                    //禁用账号
                    param.userType=0;//临时账号	用户类型0-正式,1-临时用户
                    param.status=0;//禁用
                }
                if(this.statusPage=='lsuser')
                {
                    //临时账号
                    param.userType=1;//临时账号	用户类型0-正式,1-临时用户
                    param.status=1;
                }
                this.$api.user.exportTeacherList(param).then((res)=>{
                    const blob = new Blob([res.data], {
                        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    });
                    const a = document.createElement("a");
                    a.href = URL.createObjectURL(blob);
                    a.download = decodeURIComponent(res.headers["content-disposition"].split("filename=")[1]);
                    a.click();
                    URL.revokeObjectURL(a.href);
                    a.remove();
                })
            },
            //下载模板
            DownloadTemplent()
            {
                //下载教师模板
                this.$api.user.exportTeacherTemplate().then((res)=>{
                    const blob = new Blob([res.data], {
                        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    });
                    const a = document.createElement("a");
                    a.href = URL.createObjectURL(blob);
                    a.download = decodeURIComponent(res.headers["content-disposition"].split("filename=")[1]);
                    a.click();
                    URL.revokeObjectURL(a.href);
                    a.remove();
                })
            },
            //新增教师
            AddTeach(isEdit,item)
            {
                this.isEdit = isEdit;
                if(this.isEdit=='edit')
                {
                    this.editTeachData={
                        "dialogShow":true,
                        "title":"编辑教师",//弹窗标题
                        "isEdit":true,//是否编辑
                        "gender": item.gender,//性别，2-未知，0-男，1-女
                        "email": item.email,//邮箱
                        "id":item.id,//id
                        "teacherCode":item.teacherCode,//教师ID(教工号) 暂未使用
                        "teacherName":item.teacherName,//教师姓名
                        "userAccount":item.userAccount,//用户账号
                        "teacherId":item.teacherId,//教师id
                    };
                }
                else
                {
                    this.editTeachData={
                        "dialogShow":true,
                        "title":"新增教师",//弹窗标题
                        "isEdit":false,//是否编辑
                        "gender": 2,//性别，2-未知，0-男，1-女
                        "email": "",//邮箱
                        "id":"",//id
                        "teacherCode":"",//教师ID(教工号) 暂未使用
                        "teacherName":"",//教师姓名
                        "userAccount":"",//用户账号
                        "teacherId":"",//教师id
                    };
                }
                
              
            },
            //删除
            DeleteTeach(item)
            {
                this.$confirm(`确定要删除   ${item.teacherName}(${item.userAccount})吗?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    customClass:'page_dialog',
                }).then(() => {
                    let param = {
                        id:item.id//用户id
                    }
                    this.$api.user.deleteUserTeacher(param).then((res)=>{
                        if(res.code == 200){
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            if(this.teacherList.length==1)
                            {
                                // 如果是当前页最后一个  删除后跳转到上一页
                                if(this.pageInfo.pageNum>1)
                                {
                                    this.pageInfo.pageNum--;
                                }
                                
                            }
                            this.GetTeacherList();
                        }
                    }).catch()
                    
                }).catch(() => {
                    //取消         
                });
            },
            //禁用
            DisabledTeach(item)
            {
                
                // 状态(正式用户0=禁用 1=启用 临时用户代表0-关闭 1-开启)
                if(this.statusPage=='disabledUse'){
                    this.$confirm(`确认要启用用户  ${item.teacherName}(${item.userAccount})  吗?`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                        customClass:'page_dialog',
                    }).then(() => {
                        let param = {
                            ids:[item.id],
                            status:1,//状态 1-启用 0-禁用
  
                        };
                        this.$api.user.updateUserEnable(param).then((res)=>{
                            if(res.code == 200){
                                this.$message({
                                    type: 'success',
                                    message: '启用成功!'
                                });
                                this.GetTeacherList();
                            }
                        }).catch()
                        
                    }).catch(() => {
                        //取消         
                    });
            }else{
                this.$confirm(`确认要禁用用户${item.teacherName}(${item.userAccount}) 吗?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    customClass:'page_dialog',
                }).then(() => {
                    
                    let param = {
                        ids:[item.id],
                        status:0,//状态 1-启用 0-禁用
                    };
                    this.$api.user.updateUserEnable(param).then((res)=>{
                        if(res.code == 200){
                            this.$message({
                                type: 'success',
                                message: '禁用成功!'
                            });
                            this.GetTeacherList();
                        }
                    }).catch()
                    
                }).catch(() => {
                    //取消         
                });
            }
            },
            //解绑和绑定邮箱
            UpdateEmail(item){
                if(!item.email){
                    this.$prompt('请输入邮箱', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
                        inputErrorMessage: '邮箱格式不正确'
                        }).then(({ value }) => {
                            let param={
                                    "email": value,
                                    "userId": item.id
                                }
                            this.$api.school.batchBindUserEmail([param]).then((res)=>{
                                if(res.code == 200){
                                    if(res.data.length>0){
                                        this.$message.warning("该邮箱已被其他用户绑定过！")
                                    }else{
                                        this.$message.success("绑定成功！")
                                    }
                                    this.loading=false;
                                    this.resetPageData();
                                    this.teacherList=[];
                                    this.listTeacherUser(this.statusPage);
                                }
                            }).catch((err)=>{})
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '取消输入'
                            });       
                        });
                }else{
                    this.$confirm(`确认要解绑教师${item.username}的邮箱绑定信息吗?`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                        customClass:'page_dialog',
                    }).then(() => {
                        let param = {ids:[item.id]}
                        this.$api.school.batchUnBindUserEmail(param).then((res)=>{
                            if(res.code == 200){
                                this.$message.success("解绑成功！")
                                this.loading=false;
                                this.resetPageData();
                                this.teacherList=[];
                                this.listTeacherUser(this.statusPage);
                            }
                        }).catch((err)=>{})
                        
                    }).catch(() => {
                        //取消         
                    });
                }
            },
        uploadImage(){
            if(this.teacherList.length>0){
                this.$refs.fileImage.click();
            }else{
                this.$message.warning('当前无教师信息');
            }
        },
        handleFiles(event) {
            this.files = Array.from(event.target.files);
            this.uploadFiles();
        },
        async uploadFiles() {
            const base64Images = await Promise.all(this.files.map(file => this.convertToBase64(file)));
            const payload = {
                base64Images: base64Images.map(({ fileName, imgData }) => ({
                fileName,
                imgData,
                urlSuffix: 'teacher/', // 根据需要设置 URL 后缀
                })),
                semesterId: this.selTermList.value,
                type: 1,
            };
            service1.post(base.prefix +'/api/v1/teach/oss/file/uploadFiles', payload)
                .then(response => {
                    this.$message.success(response.data.msg);
                    this.loading=false;
                    this.resetPageData();
                    this.teacherList=[];
                    this.listTeacherUser(this.statusPage);
                    // 处理成功逻辑
                })
                .catch(error => {
                console.error('上传失败:', error);
                // 处理失败逻辑
            });
        },
        convertToBase64(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => {
                resolve({
                    fileName: file.name,
                    imgData:`data:image/jpeg;base64,${reader.result.split(',')[1]}`  // 获取 base64 编码部分
                });
                };
                reader.onerror = reject;
                reader.readAsDataURL(file);
            });
        },
        },
    }
</script>
<style lang="scss" scoped>

</style>