<template>
  <div class="page_search">
    <div class="search_content">
      <div class="content_left">
        <el-select  v-model="schoolYearId" @change="ChangeFilter"  placeholder="请选择" class="select_year">
          <el-option
            v-for="item in schoolYearList"
            :key="item.id"
            :label="item.schoolYearName"
            :value="item.id">
          </el-option>
        </el-select>
        <el-select  v-model="schoolYearGradeId" @change="ChangeFilter" size="small" placeholder="请选择" class="select_width">
          <el-option label="全部年级" value=""></el-option>
          <el-option  v-for="item in schoolYearGradeList" :key="item.id" :label="item.gradeName" :value="item.id">
          </el-option>
        </el-select>
        <el-select  v-model="courseCode" @change="ChangeFilter" size="small" placeholder="请选择" class="select_width">
          <el-option label="全部科目" value=""></el-option>
          <el-option
            v-for="item in courseList"
            :key="item.courseCode"
            :label="item.courseName"
            :value="item.courseCode">
          </el-option>
        </el-select>
        <el-select  v-model="roleId" @change="ChangeRole" size="small" placeholder="请选择" class="select_width">
          <el-option label="全部角色" value=""></el-option>
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
        <el-input class="input_width"  v-model="teacherName" @input="ChangeFilter" placeholder="教师姓名，编号"><el-button slot="append" icon="el-icon-search" @click="ChangeFilter()"></el-button></el-input>
      </div>
      <div class="content_right">
        <!-- <el-button type="text" @click="addTeacher">新增</el-button> -->
        <!-- <el-button type="text">批量导入</el-button>
        <el-button type="text">批量导出</el-button> -->
      </div>
    </div>
    <div class="page_jg"></div>
    <div class="page_table">
        <el-table :data="tableData" border :height="tableHeight">
          <el-table-column type="index" width="80" align="center" label="序号"></el-table-column>
          <el-table-column prop="userAccount" label="账号" align="center">
          </el-table-column>
          <el-table-column prop="teacherName" label="教师姓名" align="center">
          </el-table-column>
          <el-table-column prop="roleName" label="角色" width="100" align="center">
          </el-table-column>
         
          <el-table-column prop="gradeName" label="年级" align="center">
          </el-table-column>
          <el-table-column prop="courseName" label="科目" align="center">
          </el-table-column>
          <el-table-column prop="startDate" label="开始时间" align="center">
          </el-table-column>
          <el-table-column prop="endDate" label="结束时间" align="center">
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope">
              <div class="table_row_option">
                
                <div class="button_delete"  @click.stop="DeleteTeacher(scope.row)">删除</div>
                
              </div>
            </template>
          </el-table-column>
        </el-table>
    </div>
    <div class="page_pagination">
        <el-pagination
        @current-change="changePage"
          background
          layout="prev, pager, next"
          :page-size="20"
          :current-page="pageInfo.pageNum"
          :total="Number(pageInfo.total)">
        </el-pagination>
    </div>
    <!-- 新增教师 -->
    <el-dialog title="教师角色新增" center width="450px" :visible.sync="editTeacherData.dialogShow">
      <el-container class="courseDialogBox">
        <el-form :model="editTeacherData" style="flex:1;" :rules="editTeacherDataRules" ref="editTeacherData" label-width="140px">
          <el-form-item label="教师编号:" prop="teacherCode">
            <el-select :popper-append-to-body="false" :value="roleAddSelTeacher.loginName" @change="roleAddSelectTeacher" clearable placeholder="请选择">
              <el-option
                v-for="item in teacherList"
                :key="item.loginName"
                :label="item.username"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教师名称:" prop="userId">
            <el-select :popper-append-to-body="false" :value="roleAddSelTeacher.username" @change="roleAddSelectTeacher" clearable placeholder="请选择">
              <el-option
                v-for="item in teacherList"
                :key="item.id"
                :label="item.username"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色:" prop="identityId">
            <!-- <el-input v-model="editTeacherData.roleName" ></el-input> -->
            <el-select :popper-append-to-body="false" :value="selRoleData.identityName" @change="selRoleChange1" placeholder="">
              <el-option
                v-for="(item) in selRoleList"
                :key="item.id"
                :label="item.identityName"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年级:" prop="gradeId">
            <el-select :popper-append-to-body="false" :value="editTeacherData.gradeId" :disabled="selRoleData.identityCode == 3 || selRoleData.identityCode == 5" @change="selGradeChange" placeholder="请选择">
              <el-option
                v-for="item in selGradeList"
                :key="item.gradeInfoId"
                :label="item.gradeName"
                :value="item.gradeInfoId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科目:" prop="courseId">
            <el-select :popper-append-to-body="false" :value="editTeacherData.courseId" @change="selCourseChange" :disabled="selRoleData.identityCode == 5||selRoleData.identityCode ==4" placeholder="请选择">
              <el-option
                v-for="item in selCourseList"
                :key="item.courseInfoId"
                :label="item.courseName"
                :value="item.courseInfoId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>    
      </el-container>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editTeacherData.dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="confirmTeacherAdd">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 重置密码 -->
    <el-dialog title="重置密码" center width="450px" :visible.sync="editPassWordData.dialogShow">
      <el-form :model="editPassWordData" label-width="80px" :rules="editPassWordDataRules" ref="editPassWordData">
        <el-form-item label="教师编号:" prop="teacherCode">
          <el-input 
            disabled
            v-model="editPassWordData.teacherCode"/>
        </el-form-item>
        <el-form-item label="教师姓名:" prop="teacherName">
          <el-input 
            disabled
            v-model="editPassWordData.teacherName"/>
        </el-form-item>
        <el-form-item label="新密码:" prop="newPassWord">
          <el-input v-model="editPassWordData.newPassWord"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="editPassWordData.dialogShow = false">取 消</el-button>
        <el-button size="small" type="primary" @click="resetPassWord">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { throttle } from '@/utils/common';
export default{
  name:"ListSettingPage",
  data(){
    return {
      selRole:{
        value:"",
        arr:[
          {
            roleId:101,
            roleName:"所有角色"
          },
        ]
      },
      selGradeYear:{
        value:"",
        arr:[]
      },
      selTermList:{
          value:"",
          arr:[
            {id:101,gradeName:"全年级"}
          ]
      },
      selTermSubject:{
          value:"",
          arr:[
            {courseInfoId:101,courseName:"语文"}
          ]
      },
      studentName:"",
      classTreeList:[],
      studentList:[],
      classData:[],
      tableData:[],
      teacherName:"",//教师姓名 编号搜索
      defaultPropsClass:{
        children: 'gradeClasses',
        label: 'displayName',
        labelId:'courseId'
      },
      courseData:{
        value:"",
        arr:[]
      },
      gradeData:{
        value:"",
        arr:[]
      },
      editTeacherData:{   //教师数据 编辑添加
        "dialogShow":false,
        "courseId": "",
        "gradeId": "",
        "id": "",
        "identityId": "",
        "schoolYearId": "",
        "userId": ""
      },
      editTeacherDataRules:{
        userId:[
            { required: true, message: '请选择教师名称', trigger: 'blur' },
        ],
      },
      pageInfo:{
        pageNum:1,
        pageSize:10,
        total:0,
      },
      teacherList:[],
      roleAddSelTeacher:{},
      selRoleList:[],
      selGradeList:[],
      selCourseList:[],
      selRoleData:{},
      selAllGradeCourseList:[], //所有科目
      editPassWordData:{
        dialogShow:false,
        userId:"",
        newPassWord:"",
        teacherName:"",
        teacherCode:""
      },
      editPassWordDataRules:{
        newPassWord:[
            { required: true, message: '请输入新密码', trigger: 'blur' },
        ],
      },
      mainHeight:0,
      tableBodyWrapper: null,
      schoolYearId:'',//学年Id
      schoolYearList:[],//学年列表
      schoolYearGradeId:'',//学年年级Id
      schoolYearGradeList:[],//学年年级列表
      courseId:'',//科目列表
      courseCode:'',//科目code
      courseList:[],//科目列表
      roleId:'',//角色ID
      roleCode:'',//角色code
      roleList:[],//角色列表
      tableHeight:0,//表格高度
    }
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.HandleResize); //监听窗口大小变化
  },
  mounted(){
    this.SetTableHeight(); //设置表格高度
    window.addEventListener("resize", this.HandleResize); //监听窗口大小变化
    this.GetUserPermissionList();
    
  },
  methods:{

    // 监听窗口大小变化，重新计算表格高度 使用节流防止频繁改变窗口大小导致计算量过大而页面卡顿
    HandleResize: throttle(function () {
        this.SetTableHeight();
    }, 500), // 节流 500 毫秒内最多执行一次
    //设置表格高度
    SetTableHeight() 
    {
        let windowViewHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        
        this.$nextTick(() => {
            this.tableHeight=windowViewHeight - 320;
        });
    },

    //获取人员权限列表设置数据
    GetUserPermissionList()
    {
      let param={
        accountName:this.teacherName,//姓名 账号
        classId:'',//班级id
        courseCode:this.courseCode,//科目code
        roleId:this.roleId,//角色ID
        roleCode:this.roleCode,//角色code
        schoolYearId:this.schoolYearId,//学年Id
        schoolYearGradeId:this.schoolYearGradeId,//年级ID
        pageNum:this.pageInfo.pageNum,//页码
        pageSize:10,//每页条数
      };
      this.$api.user.getUserPermissionList(param).then((res) => {
        console.log("打印人员权限设置列表数据",res)
        if(res.code == 200 && res.data!=null)
        {
          this.tableData=res.data.pcTeacherTblVOS.records || [];
          if(res.data.pcSchoolYearVOS)
          {
            this.schoolYearList=res.data.pcSchoolYearVOS || [];//学年列表
            this.schoolYearId=res.data.schoolYearId || '';

            const selectedSchoolYear= this.schoolYearList.find(year => year.id === this.schoolYearId);
            this.schoolYearGradeList = selectedSchoolYear.schoolYearGradeVOS || [];
          }
          if(res.data.roleBOS)
          {
            this.roleList=res.data.roleBOS || [];//角色列表
          }
          if(res.data.courseVOS)
          {
            this.courseList=res.data.courseVOS || [];//科目列表
          }
        }
      })
    },

    //切换角色
    ChangeRole()
    {
      console.log("打印当前角色",this.roleList);
      const roleItem=this.roleList.find(item=>item.id==this.roleId);
      this.roleCode=roleItem.roleCode;
      console.log("打印当前角色",roleItem);
      this.ChangeFilter();
    },

    //通用筛选改变事件
    ChangeFilter()
    {
      this.pageInfo.pageNum=1;
      this.GetUserPermissionList();
    },
    updateMainHeight() {
        let mainElement = document.querySelectorAll('.layout')[0].parentElement;
        let resetElement = document.querySelectorAll('.headerBox')[0].offsetHeight;
        // 计算主高度
        if (mainElement) {
            this.mainHeight = mainElement.offsetHeight - (6.35*resetElement);
        } else {
            this.mainHeight = window.innerHeight - (6.35*resetElement);
        }
        // 动态设置 .el-table__body-wrapper.is-scrolling-none 的高度
        if (this.tableBodyWrapper) {
            this.tableBodyWrapper.style.height = this.mainHeight +'px';
        }
    },


    //删除教师
    DeleteTeacher(item)
    {
      this.$confirm(`此操作将永久删除该条记录, 是否继续?`, '提示', {
         distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass:'page_dialog',
        }).then(() => {
          let param={
            roleCode:this.roleCode,//角色code
            tchCourseId:item.tchCourseId,
          };
          this.$api.user.deleteTeacherPermissionInfo(param).then(res=>{
            console.log("打印删除教师权限结果",res);
            if(res.code==200)
            {
              this.$message.success("删除成功!");
              this.GetUserPermissionInfo();//获取人员权限设置数据
            }
          })
           
        }).catch(() => {

        });
      
    },

    selGradeChange(e){
      console.log(e,"-=-");
      this.selCourseList = [];
      this.editTeacherData.gradeId = e;
      let item = this.selGradeList.find(item=>item.gradeInfoId == e);
      this.selCourseList=item.courseInfoBOList;
      console.log(this.selCourseList);
    },
    selCourseChange(e){
      this.editTeacherData.courseId = e;
    },
    getRoleList(){
      this.$api.school.getRoleList().then((res) => {
        if (res.code == 200) {
          this.selRole.arr = res.data;
          let it = {
            id:"",
            identityName:"所有角色"
          }
          this.selRole.arr.unshift(it);
        } 
      })
    },
    getGradeCourse(){
      this.$api.school.getSchoolGradeCourse().then((res)=>{
        // console.log(res,"res");
        if(res.code == 200){
          this.selGradeList = res.data;
        }else{
          this.$message.error(res.msg);
        }
        
      });
    },
    //获取学年学期
    getGradeTerm(){
      let param = { validStatus: false}
      this.$api.school.getGradeYearTearm(param).then((res) => {
        // console.log(res)
        if (res.code == 200 && res.data.length>0) {
          this.selGradeYear.arr = res.data;
          this.selGradeYear.value = res.data[0].id;
          // let selItem = res.data.find(item=>item.currentStatus==true)
          // this.selTermList.arr = selItem.infoBOList;
          // let it = {
          //   schoolGradeId:"",
          //   gradeName:"所有年级"
          // }
          // this.selTermList.arr.unshift(it);
          
          this.getManaPersonList();
        }else{
          // this.$message.error(res.msg);
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    selGradeYearChange(){
      this.pageInfo.pageNum = 1;
      this.getManaPersonList();
    },
    getManaPersonList(){
      let {pageNum,pageSize} = this.pageInfo;
      let params = {
        pageNum,
        pageSize,
        queryStr:this.teacherName,
        schoolYearId:this.selGradeYear.value,
        schoolTeacherIdentityId:this.selRole.value,
        schoolCourseId:this.selTermSubject.value,
        schoolGradeId:this.selTermList.value

      }
      this.$api.school.getManaPersonList(params).then((res)=>{
        if(res.code == 200){
          this.manaPersonData = res.data.records;
          this.pageInfo.total = res.data.total;
        }
      }).catch((err)=>{console.log(err)})
    },
    checkedGrade(e){
      console.log(e)
    },
    addTeacher(type,rowData){
      
      if(type == 'edit'){
        this.editTeacherData = {
          isEdit:true,
          courseId: rowData.schoolCourseId,
          gradeId: rowData.schoolGradeId,
          identityId:rowData.schoolTeacherIdentityId,
          userId:rowData.teacherUserInfoId,
          schoolYearId:"",
          id:rowData.id,
          dialogShow:false,
        }
        this.roleAddSelTeacher.username = rowData.teacherName;
        this.roleAddSelTeacher.loginName = rowData.teacherCode;
        this.selRoleData.identityName = rowData.schoolTeacherIdentityName;
        
        if(rowData.schoolTeacherIdentityCode == 2){
          let item = this.selGradeList.find(item=>item.gradeInfoId == rowData.schoolGradeId);
          this.selCourseList=item.courseInfoBOList;
        }else if(rowData.schoolTeacherIdentityCode == 3){
          this.selCourseList = this.selAllGradeCourseList;
        }

      }else{
        this.editTeacherData={
          "dialogShow":false,
          "courseId": "",
          "gradeId": "",
          "id": "",
          "identityId": "",
          "schoolYearId": "",
          "userId": ""
        }
      }
      this.editTeacherData.dialogShow = true;
    },
    getTeacherList(){
      this.$api.school.getTeacherList().then((res)=>{
        if(res.code == 200){
          this.teacherList = res.data;
        }
      }).catch((err)=>{})
    },
    
    searchTeacher(e){
      this.teacherName = e;
      this.pageInfo.pageNum = 1;
      throttle(this.getManaPersonList(),60)
      
    },
    getTeacherRole(){
      
      this.$api.school.getTeacherRole().then((res)=>{
        if(res.code == 200){
          this.selRoleList = res.data;
        }
      }).catch((err)=>{})
    },
    roleAddSelectTeacher(e){
      console.log(e,"e--=")
      this.roleAddSelTeacher = e;
      this.editTeacherData.userId = e.id;
    },
    //页面改变
    changePage(e){
      this.pageInfo.pageNum = e;
      this.getManaPersonList();
      // console.log(e,"==-00d")
    },
    selRoleChange(e){
      console.log(e,"==-00d")
      this.selRole.value = e;
      this.pageInfo.pageNum = 1;
      this.getManaPersonList();
    },
    confirmTeacherAdd(){
      this.$refs["editTeacherData"].validate((valid) => {
        if(valid){
          let param = this.editTeacherData;
          param.schoolYearId = this.selGradeYear.value;
          console.log(this.editTeacherData)
          this.$api.school.setTeacherRole(param).then((res)=>{
            if(res.code == 200){
              this.editTeacherData = {};
              this.pageInfo.pageNum = 1;
              this.getManaPersonList();
              
              this.$message({
                message: '添加成功',
                type: 'success'
              })
            }
          }).catch((err)=>{})
        }
      })
      
    },
    showSetPw(rowData){
      this.editPassWordData={
        dialogShow:true,
        userId: rowData.teacherUserInfoId,
        newPassWord:"",
        teacherName:rowData.teacherName,
        teacherCode:rowData.teacherCode
      } 
    },
    //重置密码
    resetPassWord(){
      this.$refs["editPassWordData"].validate((valid) => {
        if(valid){
          let param = {
            userId: this.editPassWordData.userId,
            randomPassword: this.editPassWordData.newPassWord
          }
          this.$api.school.updateTeacherPassWord(param).then((res)=>{
            if(res.code ==200){
              this.$message.success("重置成功！")
              this.editPassWordData.dialogShow = false;
            }else{
              this.$message.error("重置失败！")
            }
          }).catch((err)=>{})
        }
      })
      
    },
    selRoleChange1(e){
      console.log(e,"==-00d");
      this.editTeacherData.identityId = e.id;
      this.selRoleData = e;
      this.editTeacherData.courseId="";
      this.editTeacherData.gradeId="";
      this.selCourseList =  [];
      if(e.identityCode ==3){
        //备课
        this.selCourseList = this.selAllGradeCourseList;
      }
      //角色 年级组长
      // if(e.identityCode ==4){
      //   this.editTeacherData.courseId="";
      // }else if(e.identityCode ==5){
      //   //校长
      //   this.editTeacherData.courseId="";
      //   this.editTeacherData.gradeId="";
      // }else if(e.identityCode ==3){
      //   //科目
      //   this.editTeacherData.courseId="";
      //   this.editTeacherData.gradeId="";
      // }else if(e.identityCode ==2){
      //   //备课
      // }

    },
  },
}
</script>
<style lang="scss" scoped>



</style>