<template>
  <div class="layoutCon">
    <div class="tableTopWrap heightSet">
      <!-- <div>
        <div>
          <vxe-toolbar ref="xToolbar1">
            <template #buttons>
              <div class="leftHeadBox">
                <el-radio-group  v-model="colShowTeacher" @change="getTeacherInfo" size="mini" style="margin-left: 10px;">
                  <el-radio-button v-for="item in gradeClassArr" :label="item.value" :key="item.value">{{item.label}}</el-radio-button>
                </el-radio-group>
              </div>
            </template>
          </vxe-toolbar>
        </div>
      </div> -->
      <el-tabs style="margin-top: -14px;" v-model="teachingTabType" @tab-click="handleTabClick">
        <el-tab-pane label="授课关系" name="relation">
          <div class="iflexJustBet">
            <aside class="asideMainStyle">
              <el-input size="small" :value="teacherName" @input="teacherNameChange" placeholder="教师姓名，编号"><el-button slot="append" icon="el-icon-search"></el-button></el-input>
              <div class="module_table" style="width: 100%;">
                <el-table style="margin-top: 12px;" :data="teacherTreeList" border :cell-class-name="cellClassName" :highlight-current-row="true"
                  @row-click="checkedTeacher" size="mini" width="100%" class="treeList" stripe v-loading="loading">
                  <el-table-column prop="studentRegistrationCode" label="账号" align="center"></el-table-column>
                  <el-table-column prop="username" label="教师" align="center">
                  </el-table-column>
                </el-table>
              </div>
            </aside>
            <div class="lyMainRight">
              <div class="mainTableTopWrap">
                <div class="iflexJustBet">
                  <div>
                    <el-select :popper-append-to-body="false" :value="selGradeYear.value" @change="selGradeYearChange" size="small" placeholder="请选择" class="selectyear">
                      <el-option v-for="item in selGradeYear.arr" :key="item.id" :label="item.schoolYearName" :value="item.id">
                      </el-option>
                    </el-select>
                    <el-select :popper-append-to-body="false" :value="selTermList.value" @change="selTermChange" size="small" placeholder="请选择" class="selecGrade">
                      <el-option v-for="item in selTermList.arr" :key="item.id" :label="item.gradeName" :value="item.id">
                      </el-option>
                    </el-select>
                  </div>
                  <div>
                    <!-- <el-button size="mini" @click="resetMultiplePW" v-show="colShowTeacher">密码重置</el-button> -->
                    <!-- <el-button size="mini" @click="chooseTeacherFile" v-show="colShowTeacher">批量导入</el-button> -->
                    <el-button size="mini" @click="clearCurse" type="danger" plain v-show="!colShowTeacher" style="color:#F56C6C;border:1px solid #F56C6C;">清空授课</el-button>
                    <el-button size="mini" @click="exportTeacherList">批量导出</el-button>
                  </div>
                </div>
                <div class="tableTopRight checkTeacher" ref="showTeachList">
                  <el-button style="margin-right:10px; color:#999;" v-if="selectedTeacher.teacherId && checkedTeacherToSet && !colShowTeacher" type="text" size="small">{{ selectedTeacher.teacherName }}</el-button>
                  <el-switch
                    style="display: block"
                    v-if="!colShowTeacher"
                    v-model="checkedTeacherToSet"
                    active-text="选中教师配置任课关系"
                    inactive-text=""
                    >
                  </el-switch>
                  <!-- <el-checkbox v-model="checkedTeacherToSet" style="margin-right:15px;" v-if="!colShowTeacher">选中教师配置任课关系</el-checkbox> -->
                  <!-- <el-button size="small" round @click="resetMultiplePW">密码重置</el-button> -->
                </div>
              </div>
              <el-tabs v-model="classTabType" v-show="!colShowTeacher">
                <el-tab-pane class="xzb" label="行政班" name="first">
                  <div class="module_table" style="width: 100%;">
                    <el-table stripe :data="administrativeClassList" :cell-class-name="cellClassName" border @cell-click="addTags" style="width:100%;" size="small" class="borderRadiusStyle">
                      <!-- <el-table-column fixed label="编号" prop="classCode" width="100" align="center">
                        <templage slot-scope="scope">
                        </templage>
                      </el-table-column> -->
                      <el-table-column fixed min-width="80" label="班级" align="center">
                        <template slot-scope="scope">
                          <div style="white-space: pre-line;">{{scope.row?.className=="年级组长/备课组长"?'年级组长\n备课组长':scope.row.className }}</div>
                        </template>
                      </el-table-column>
                      <el-table-column v-for="(item, index) in classTableHeader1" :key="index" min-width="113" :prop="item.id"  :label="item.titleName"  align="center">
                        <template slot-scope="scope">
                          <div v-if="checkedTeacherToSet">
                            <div class="tagWrap" v-if="scope.row[item.id] && scope.row[item.id].length>0">
                              <el-tag class="custom-tag" v-for="(it,idx) in scope.row[item.id]" :key="idx" @close.stop="deleteTeacherBindRole(scope.$index, item.id, idx,it.id)" closable>{{ it.teacherName}}</el-tag>
                            </div>
                            <div v-else><span class="tagWrapFalse" v-if="checkedTeacherToSet">请选择教师</span><span v-else class="defaultnbsp">-</span></div>
                            </div>
                          <div v-else>
                            <div v-for="(it,idx) in scope.row[item.id]" :key="idx">{{ it.teacherName}}</div>
                          </div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </el-tab-pane>
                <el-tab-pane class="jxb"  label="教学班" name="second">
                  <el-table stripe :data="classificationClassList" border :cell-class-name="cellClassName" @cell-click="addTags" style="width:100%;" class="borderRadiusStyle jxbTeach">
                    <template v-for="(headerGroup, groupIndex) in mergedHeader">
                      <el-table-column
                      :key="groupIndex"
                      :label="headerGroup.label"
                      :colspan="headerGroup.children.length"
                      align="center"
                      >
                        <template v-for="(child, childIndex) in headerGroup.children">
                            <el-table-column
                                :key="childIndex"
                                :prop="child.prop"
                                :courseId="child.courseId"
                                :label="child.label"
                                align="center"
                                min-width="110"
                            >
                                <template slot-scope="scope">
                                  <div v-if="childIndex % 2 == 0" :style="{ color: scope.row[child.prop]?.className ? '' : scope.$index !== 0 ? '#c0c4cc' : '' }">
                                    {{ scope.row[child.prop]?.className ? scope.row[child.prop]?.className : scope.$index !== 0 ? '-' : scope.$index === 0 ? '备课组长' : '' }}
                                  </div>
                                  <div v-else>
                                    <div v-if="checkedTeacherToSet">
                                      <div class="tagWrap" v-if="scope.row[child.prop]?.teacherList && scope.row[child.prop]?.teacherList.length > 0">
                                        <el-tag
                                        class="custom-tag"
                                        v-for="(it, idx) in scope.row[child.prop]?.teacherList"
                                        :key="idx"
                                        @close.stop="deleteTeacherBindRole(scope.$index, child.prop, idx, it.id)"
                                        closable
                                        >
                                          {{ it.teacherName }}
                                        </el-tag>
                                      </div>
                                      <div v-else>
                                        <span class="tagWrapFalse" v-if="(checkedTeacherToSet && scope.row[child.prop]?.className && scope.row[child.prop]?.classId)||(scope.$index == 0 && checkedTeacherToSet)">请选择教师</span>
                                        <span v-else class="defaultnbsp">-</span>
                                      </div>
                                    </div>
                                    <div v-else>
                                      <div v-for="(it, idx) in scope.row[child.prop]?.teacherList" :key="idx">{{ it.teacherName }}</div>
                                    </div>
                                  </div>
                                </template>
                            </el-table-column>
                        </template>
                      </el-table-column>
                    </template>
                   </el-table>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="授课列表" name="list">
          <div class="iflexJustBet">
            <div>
              <el-select :popper-append-to-body="false" :value="selGradeYear.value" @change="selGradeYearChange" size="small" placeholder="请选择" class="selectyear">
                <el-option v-for="item in selGradeYear.arr" :key="item.id" :label="item.schoolYearName" :value="item.id">
                </el-option>
              </el-select>
              <el-select :popper-append-to-body="false" :value="selTermList.value" @change="selTermChange" size="small" placeholder="请选择" class="selecGrade">
                <el-option v-for="item in selTermList.arr" :key="item.id" :label="item.gradeName" :value="item.id">
                </el-option>
              </el-select>
              <el-select :popper-append-to-body="false" :value="selTermList.value" @change="selTermChange" size="small" placeholder="请选择" class="selecGrade">
                <el-option v-for="item in selTermList.arr" :key="item.id" :label="item.gradeName" :value="item.id">
                </el-option>
              </el-select>
              <el-select :popper-append-to-body="false" :value="selTermList.value" @change="selTermChange" size="small" placeholder="请选择" class="selecGrade">
                <el-option v-for="item in selTermList.arr" :key="item.id" :label="item.gradeName" :value="item.id">
                </el-option>
              </el-select>
              <el-select :popper-append-to-body="false" :value="selTermList.value" @change="selTermChange" size="small" placeholder="请选择" class="selecGrade">
                <el-option v-for="item in selTermList.arr" :key="item.id" :label="item.gradeName" :value="item.id">
                </el-option>
              </el-select>
              <el-input style="width: 180px;" size="small" :value="teacherName" @input="teacherNameChange" placeholder="教师姓名，编号"><el-button slot="append" icon="el-icon-search"></el-button></el-input>
            </div>
            <div>
              <!-- <el-button size="mini" @click="resetMultiplePW" v-show="colShowTeacher">密码重置</el-button> -->
              <!-- <el-button size="mini" @click="chooseTeacherFile" v-show="colShowTeacher">批量导入</el-button> -->
              <el-button size="mini" @click="clearCurse" type="danger" plain v-show="!colShowTeacher" style="color:#F56C6C;border:1px solid #F56C6C;">清空授课</el-button>
              <el-button size="mini" @click="exportTeacherList">批量导出</el-button>
            </div>
          </div>
          <div style="width: 100%; margin-top: 16px;" class="module_table">
            <el-table :data="colShowTeacherClassList" stripe :cell-class-name="cellClassName" border  style="width:100%;" size="small" class="borderRadiusStyle teacherTableStyle">
              <el-table-column  label="序号" type="index" prop="classCode" width="80" align="center">
              </el-table-column>
              <el-table-column  min-width="120" prop="teacherCode" label="教师编号" align="center">
              </el-table-column>
              <el-table-column  min-width="100" prop="teacherName" label="教师姓名" align="center">
              </el-table-column>
              <el-table-column  min-width="100" prop="schoolTeacherIdentityName" label="角色" align="center">
              </el-table-column>
              <el-table-column  min-width="100" prop="schoolCourseName" label="任课科目" align="center">
              </el-table-column>
              <el-table-column  min-width="100" prop="schoolClassCode" label="班级编号" align="center">
              </el-table-column>
              <el-table-column  min-width="100" prop="schoolClassName" label="班级名称" align="center">
              </el-table-column>
              <el-table-column width="150" label="操作" align="center" :fit="true">
                <template slot-scope="scope">
                  <div class="tableButton">
                    <el-button type="text" size="small" style="padding:0;" @click="resetPassWord('only',scope.row)">重置密码</el-button>
                    <el-button type="text" size="small" style="padding:0;color:#F56C6C;" @click="deleteChooseTeacherId(scope.row)">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div class="tableTopRight">
        <!-- <el-button size="mini" @click="addTeacher">新增教师</el-button>
        <el-button size="mini" @click="addTeacher('edit')">教师编辑</el-button>
        <el-button size="mini" @click="deleteChooseTeacher">教师删除</el-button>
        <el-button size="mini" @click="resetPassWord">重置密码</el-button> -->
        <div>
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content">当前导入的为教师用户的基本信息，表头包含教师编号,教师姓名,院系组编号,院系组名称,手机号,职务，默认密码<br/>
  可参考批量导出的表头信息，其中教师编号和教师姓名为必需项，<br/>
  如果不设置默认密码，则用户的默认密码为学校编号+@+教师编号，如：19000@15800000000</div>
              <!-- <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-success="batchImport"
                :limit="1">
              
            </el-upload> -->
          </el-tooltip>
          <input type="file" ref="uploadStudents" @change="importTeacherList" enctype="multipart/form-data" style="display:none;"/>
        </div>
      </div>
    </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-input v-model="editTeacherData.teacherCode"></el-input>
          </el-form-item>
          <el-form-item label="教师名称:" prop="username">
            <el-input v-model="editTeacherData.username" ></el-input>
          </el-form-item>
          <el-form-item label="院系组编号:" prop="teacherDepartmentCode">
            <el-input v-model="editTeacherData.teacherDepartmentCode" ></el-input>
          </el-form-item>
          <el-form-item label="院系组名称:" prop="teacherDepartmentName">
            <el-input v-model="editTeacherData.teacherDepartmentName" ></el-input>
          </el-form-item>
          <!-- <el-form-item label="手机号:" prop="phone">
            <el-input v-model="editTeacherData.phone" ></el-input>
          </el-form-item> -->
          <el-form-item label="职务:" prop="teacherDuty">
            <el-input v-model="editTeacherData.teacherDuty" ></el-input>
          </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 :visible.sync="editPassWordData.dialogShow" custom-class="editCourseDialog">
      <el-form :model="editPassWordData" label-width="90px" :rules="editPassWordDataRules" ref="editPassWordData">
        <el-form-item label="教师编号">
          <el-input v-model="editPassWordData.teacherCode" disabled/>
        </el-form-item>
        <el-form-item label="教师姓名">
          <el-input v-model="editPassWordData.teacherName" disabled/>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassWord">
          <el-input v-model="editPassWordData.newPassWord"/>
        </el-form-item>
      </el-form>
      <!-- <div style="color:#999; font-size:12px;line-height:16px;margin-top:10px;">注：多个教师编号用逗号隔开，可一一对应多个新密码用逗号隔开，如果密码不存在逗号，则所有教师的密码都为一样，如果为唯一密码，且中间存在*，则密码会把*替换成教师编号
</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">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 重置密码 批量设置 -->
    <el-dialog title="重置密码" center width="450px" :visible.sync="editMultiplePassWordData.dialogShow">
      <el-form :model="editMultiplePassWordData" label-width="80px" :rules="editMultiplePassWordDataRules" ref="editMultiplePassWordData">
        <el-form-item label="教师编号:" prop="teacherIds">
          <el-input type="textarea"
            :rows="4"
            v-model="editMultiplePassWordData.teacherIds"/>
        </el-form-item>
        <el-form-item label="新密码:" prop="newPassWord">
          <el-input v-model="editMultiplePassWordData.newPassWord"/>
        </el-form-item>
      </el-form>
      <div style="color:#999; font-size:12px;line-height:16px;margin-top:10px;">注：多个教师编号用逗号隔开，可一一对应多个新密码用逗号隔开，如果密码不存在逗号，则所有教师的密码都为一样，如果为唯一密码，且中间存在*，则密码会把*替换成教师编号

</div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="editMultiplePassWordData.dialogShow = false">取 消</el-button>
        <el-button size="small" type="primary" @click="confirmMultiplePassWord">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { throttle } from '@/utils/common';
import base from '@/http/common/base';

export default {
  data() {
    return {
      teachingTabType: "relation", //relation授课关系 list授课列表
      uploadUrl:base.baseUrl + `/api/v1/teach/schoolTeacherInfo/importTeacherInfo`,
      selGradeYear: {
        value: "",
        arr: []
      },
      selTermList: {
        value: "",
        arr: []
      },
      teacherName: "",
      teacherTreeList: [],
      classData: [],
      defaultPropsClass: {
        children: 'teacherList',
        label: 'username',
        labelId: 'id'
      },
      checkedTeacherToSet:false,
      colShowTeacher:false,
      selectedTeacher:{},
      administrativeClassList:[],  //行政班数据
      colShowTeacherClassList:[],//教师任课详情
      classificationClassList:[], //分层班数据
      classTabType:"first", //1 行政班 2:分层班
      classTableHeader1:[
        // {
        //     "id":"classManagerList",
        //     "titleName":"班主任"
        // },
       
    ],
      classTableHeader2:[],
      mergedHeader: [],
      
      // [
      //   {
      //     prop: "physicalClassData",
      //     label: ""
      //   },
      //   {
      //     prop: "physicalClassTeacher",
      //     label: "物理"
      //   },
      //   {
      //     prop: "geographyClassData",
      //     label: ""
      //   },
      //   {
      //     prop: "geographyClassTeacher",
      //     label: "地理"
      //   },
      // ],
      editTeacherData:{   //教师数据 编辑添加
        dialogShow:false,
        teacherCode:"",
        username:"",
        teacherDepartmentCode:"",
        teacherDepartmentName:"",
        teacherDuty:""
      },
      editTeacherDataRules:{
        teacherCode:[
            { required: true, message: '请输入教师编号', trigger: 'blur' },
          ],
          username:[
            { required: true, message: '请输入教师名称', trigger: 'blur' },
        ],
      },
      editPassWordData:{
        dialogShow:false,
        newPassWord:"",
        teacherName:"",
        userInfoId:"",
        teacherCode:""
      },
      editPassWordDataRules:{
        newPassWord:[
          { required: true, message: '请输入新密码', trigger: 'blur' },
        ],
      },
      editMultiplePassWordData:{
        dialogShow:false,
        teacherIds:"",
        newPassWord:""
      },
      editMultiplePassWordDataRules:{
        teacherIds:[
          { required: true, message: '请输入老师编号', trigger: 'blur' }
        ],
        newPassWord:[
          { required: true, message: '请输入新密码', trigger: 'blur' },
        ],
      },
      teacherDetails:[{
        teacherId:"1",
        teacherName:"11",
        classLeader:"22",
        courseName:"3",
        classNumber:"4",
        className:"5",
      }],
      gradeClassArr:[
        {
          label:"授课关系",
          value:false
        },
        {
          label:"授课列表",
          value:true
        }
      ],
      loading: true,
      activeTab: 'admin',
      mainHeight:0,
      tableBodyWrapper: null,
      // 防抖函数
      debouncedUpdateMainHeight: this.debounce(this.updateMainHeight, 100)
    }
  },
  mounted() {
    this.initData();
  },
  beforeDestroy() {
     window.removeEventListener('resize', this.debouncedUpdateMainHeight);
  },
  methods: {
    setActiveTab(tab) {
      this.activeTab = tab;
      if(tab=='admin'){
        this.classTabType = 'first'
      }else if(tab=='teaching'){
        this.classTabType = 'second'
      }else{
         this.classTabType = 'first'
      }
    },
    initData() {
      this.getTeacherList();
      this.getGradeTerm();
      this.$nextTick(()=>{
        this.tableBodyWrapper = document.querySelector('.xzb .el-table__body-wrapper');
        this.updateMainHeight();
        window.addEventListener('resize', this.debouncedUpdateMainHeight);
    })
      
    },
    updateMainHeight() {
        let mainElement = document.querySelectorAll('.layout')[0].parentElement;
        let mainElement1 = document.querySelectorAll('.asideMainStyle .el-table__body-wrapper')[0];  
        let mainElement2 = document.querySelectorAll('.jxb .el-table__body-wrapper')[0];  
        let mainElement3 = document.querySelectorAll('.xzb .el-table__fixed-body-wrapper')[0];  
        let mainElement4 = document.querySelectorAll('.teacherStyle .borderRadiusStyle.teacherTableStyle .el-table__body-wrapper')[0];  
        let resetElement = document.querySelectorAll('.headerBox')[0].offsetHeight;
        let height=0;
        // 计算主高度
        if (mainElement) {
            this.mainHeight = mainElement.offsetHeight - (6.5*resetElement);
            height = mainElement.offsetHeight - (4.77*resetElement);
        } else {
            this.mainHeight = window.innerHeight - (6.5*resetElement);
            height = window.innerHeight - (4.77*resetElement);
        }
        // 动态设置 .el-table__body-wrapper.is-scrolling-none 的高度
        if (this.tableBodyWrapper) {
            this.tableBodyWrapper.style.height = this.mainHeight +'px';
        }
        if(mainElement1) mainElement1.style.height = height +'px';
        if(mainElement2) mainElement2.style.height = this.mainHeight +'px';
        if(mainElement3) mainElement3.style.height = this.mainHeight +'px';
        if(mainElement4){
          mainElement4.style.height = this.mainHeight+0.8*resetElement +'px';
        }
    },
    debounce(func, wait) {
        let timeout;
        return function (...args) {
            const context = this;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), wait);
        };
    },
    handleTabClick(tab) {
      if(tab.name == 'relation'){
        this.initData()
      }else{
        this.teacherClassDetailsList()
      }
      console.log('tabName:',tab.name)
      // this.teacherClassDetailsList()
    },
    getTeacherInfo(){
      if(this.colShowTeacher){
        this.$refs.showTeachList.style.top='0px';
        setTimeout(()=>{
          this.updateMainHeight();
        },200)
        this.teacherClassDetailsList();
      }else{
        this.$refs.showTeachList.style.top='60px';
      }
    },
    teacherClassDetailsList(flag){
      this.$api.school.teacherClassDetailsList({schoolSemesterId:this.selTermList.value}).then((res)=>{
        if(res.code==200){
          this.colShowTeacherClassList = res.data;
        }
      })
    },
    //行政班
    getAdminClass(){
      let param = {
        semesterId:this.selTermList.value
      }
      this.$api.school.getCourseAdminClassList(param).then((res)=>{
        if(res.code==200){
          let arr = [
             {
                "id":"classManagerList",
                "titleName":"班主任"
            }
          ]
          this.classTableHeader1 = res.data.titleDataList?[...arr,...res.data.titleDataList]:[];
          this.administrativeClassList = res.data.tableDataList?res.data.tableDataList:[];
          
        }
      })
    },
    getSectionClassCourseData(){
      let param = {
        "semesterId":this.selTermList.value
      }
      this.$api.school.getSectionClassCourse(param).then((res)=>{
        if(res.code == 200){
          this.classTableHeader2 = res.data.titleList;
          this.classificationClassList = res.data.dataList;
          this.prepareMergedHeader()
        }
      }).catch((err)=>{
        console.log(err)
      })
    },
    prepareMergedHeader() {
      // 处理标题以合并相同的 courseId
      const headerMap = {};
      this.classTableHeader2.forEach(item => {
              const { courseId } = item;
              if (!headerMap[courseId]) {
                  headerMap[courseId] = [];
              }
              headerMap[courseId].push(item);
          });
          this.mergedHeader = Object.values(headerMap).map(group => {
              return {
                  label: group[0].label || group[1]?.label || '',
                  children: group.map(item => ({
                      prop: item.prop,
                      label: item.label || ''
                  }))
              };
          });
    },
    //获取学年学期
    getGradeTerm(){
      let param = { validStatus: false}
      this.$api.school.getGradeYearTearm(param).then((res) => {
        console.log(res)
        if (res.code == 200 && res.data.length>0) {
          let selItem = res.data.find(item=>item.currentStatus==true)
          this.selGradeYear.arr = res.data;
          this.selGradeYear.value =selItem.id;
          this.selTermList.arr = selItem.infoBOList;
          this.selTermList.value = selItem.infoBOList[0].id;
          // this.getClassTreeList(res.data[0].infoBOList[0].id);
          this.getAdminClass();
          this.getSectionClassCourseData();
        }else{
          this.$message.error(res.msg);
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    getTeacherList(){
      let param = {userName:this.teacherName}
      this.$api.school.getTeacherList(param).then((res) => {
        if(res.code == 200){
          this.teacherTreeList = res.data;
          this.loading=false;
        }
      })
    },
    checkedTeacher(e) {
      console.log(e,"e-=")
      this.selectedTeacher = {
        teacherId: e.id,
        identityCode:e.identity,
        teacherName: e.username,
        // teacherDepartmentCode:e.teacherDepartmentCode,
        // teacherDepartmentName:e.teacherDepartmentName,
        // schoolClassId:"",
        identityName:e.identityName,
      }
    },
    cellClassName({row,column,rowIndex,columnIndex}){
      row.index = rowIndex;
      column.index = columnIndex;
    },
    addTags(row, column){
      
      if(!this.checkedTeacherToSet || !this.selectedTeacher.teacherId)return;
      let rowIndex = row.index;
      let cellKey = column.property;
      console.log(row,column,"rowc--=")
        // console.log(rowIndex,cellKey,item,"----/n",this.administrativeClassList[rowIndex][cellKey]);
      let {teacherId,teacherName} = this.selectedTeacher;
      let identityCode = 0;

      
        //行政班
      if(this.classTabType == "first"){
        //是否重复
        if(this.administrativeClassList[rowIndex][cellKey]&&this.administrativeClassList[rowIndex][cellKey].some(item => item.teacherId == teacherId)){
          this.$message.error("该教师已存在！");
          return;
        }
        if(row.index  ==  0){
          identityCode = cellKey == "classManagerList"?4:2;
        }else{
          identityCode = cellKey == "classManagerList"?1:0;
        }
        // let item = this.administrativeClassList[rowIndex][cellKey];
        let params = {
          "identityCode": identityCode,
          "schoolClassId": row.id,
          "schoolClassType": 0,
          "schoolCourseId": column.property=="classManagerList"?"":column.property,
          "schoolSemesterId": this.selTermList.value,
          "schoolTeacherIdentityType": 0,
          "teacherUserInfoId": teacherId,
        }
        let item = {
          teacherId,
          teacherName,
          identityCode,
        };
        
        this.$api.school.teacherBindRole(params).then((res)=>{
          if(res.code == 200){
            if(!this.administrativeClassList[rowIndex][cellKey]){
              this.$set(this.administrativeClassList[rowIndex],cellKey,[item]);
            }else{
              this.administrativeClassList[rowIndex][cellKey].push(item);
            }
            this.getAdminClass();
            // this.$message.success("添加成功");
          }
        })
      }else{
         //是否重复
      if(this.classificationClassList[rowIndex][cellKey].teacherList.some(item => item.teacherId == teacherId)){
        this.$message.error("该教师已存在！");
        return;
      }
        let culmIndex = column.index;
        let courseId = this.classTableHeader2[culmIndex].courseId;
        let classId =  row[cellKey].classId?row[cellKey].classId:"";
        let params = {
          "identityCode": row.index ==0 ? 2 :identityCode,
          "schoolClassId": classId,
          "schoolClassType": 1,
          "schoolCourseId": courseId,
          "schoolSemesterId": this.selTermList.value,
          "schoolTeacherIdentityType": 0,
          "teacherUserInfoId": teacherId,
        }
        let item = {
          teacherId,
          teacherName,
          identityCode,
        };
        this.$api.school.teacherBindRole(params).then((res)=>{
          if(res.code == 200){
            if(this.classificationClassList[rowIndex][cellKey]){
              this.classificationClassList[rowIndex][cellKey].teacherList.push(item);
            }else{
              this.classificationClassList[rowIndex][cellKey].teacherList=[item];
            }
            // this.$message.success("添加成功");
            this.getSectionClassCourseData();
          }
        })
      }
    },
    clearTeachingInfo() {
        // 聚合所有需要删除的教师 IDs
        let params;
        if(this.classTabType == "first"){
            params = {
              ids: this.administrativeClassList.reduce((accumulator, classItem) => {
                  Object.values(classItem).forEach(item => {
                      if (Array.isArray(item)) {
                          item.forEach(teacher => {
                              accumulator.push(teacher.id);
                          });
                      }
                  });
                  return accumulator;
              }, [])
          };
        }else{
          // 过滤掉包含 teacherList 属性的对象
            params = {
              ids:[]
            }
            this.classificationClassList.forEach(element => {
              Object.values(element).forEach(value => {
                  if (value.teacherList && value.teacherList.length > 0) {
                      value.teacherList.forEach(teacher => {
                          params.ids.push(teacher.id);
                      });
                  }
              });
          });
        }

        // 调用 API 删除教师绑定角色
        this.$api.school.deleteTeacherBindRole(params)
            .then(res => {
                if (res.code == 200) {
                    this.$message.success("清空成功");
                    this.getAdminClass();
                    this.getSectionClassCourseData();
                } else {
                    this.$message.error("清空失败"); // 错误处理
                }
            })
            .catch(error => {
                console.error("API 调用出错:", error);
                this.$message.error("删除过程中出现错误"); // 错误处理
            });
    },
    clearCurse(){
      if(!this.selGradeYear.value || !this.selTermList.value){
          this.$message.warning('未选择学年学期！');
          return;
      }
      this.$confirm(`确认要清空授课信息吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass:'page_dialog',
      }).then(() => {
          // 执行清空操作
          this.clearTeachingInfo(); // 假设有一个方法用来清空信息
      }).catch(() => {
          this.$message({
              type: 'info',
              message: '取消清空授课信息'
          });
      });

      
      // window.location.reload();
    },
    deleteTeacherBindRole(index, prop, idx,id){
      console.log(index,prop, idx,id);
      //行政班
      if(this.classTabType == "first"){
        if(this.administrativeClassList[index][prop].length>0){
          let params = {
            ids:[id],
          }
          this.$api.school.deleteTeacherBindRole(params).then((res)=>{
            if(res.code == 200){
              this.administrativeClassList[index][prop].splice(idx,1);
              // this.$message.success("删除成功");
            }
          })
          // console.log(this.administrativeClassList,"this.administrativeClassList");
        }
      }else{
        if(this.classificationClassList[index][prop].teacherList.length>0){
          this.classificationClassList[index][prop].teacherList.splice(idx,1);
        }
        let params = {
            ids:[id],
          }
          this.$api.school.deleteTeacherBindRole(params).then((res)=>{
            if(res.code == 200){
              // this.$message.success("删除成功");
            }
          })
      }
      this.getAdminClass();
      this.getSectionClassCourseData();
    },
    addTeacher(type){
      if(type == 'edit'){
        if(!this.selectedTeacher.teacherId){
          this.$message.warning("请选择老师");
          return;
        }
        let param = {
          id:this.selectedTeacher.teacherId
        }
        this.$api.school.getTeacherDetail(param).then((res)=>{
          if(res.code == 200){
            this.editTeacherData = {
              isEdit:true,
              teacherCode: res.data.teacherCode,
              id:res.data.id,
              username: res.data.username,
              teacherDepartmentCode:res.data.teacherDepartmentCode,
              teacherDepartmentName:res.data.teacherDepartmentName,
              teacherDuty:res.data.teacherDuty,
              dialogShow:true,
            }
          }
        })
      }else{
        this.editTeacherData = {
              teacherCode: "",
              teacherName: "",
              teacherDepartmentCode:"",
              teacherDepartmentName:"",
              teacherDuty:"",
              dialogShow:false,
            }
        this.editTeacherData.dialogShow = true;
      }
      
    },
    confirmPassWord(){
      if(!this.editPassWordData.newPassWord){
        this.$message.warning("请输入新密码");
        return;
      }
      let param = {
        userId:this.editPassWordData.userInfoId,
        randomPassword:this.editPassWordData.newPassWord,
        type:1
      }
      this.$api.school.resetPassword(param).then((res)=>{
        if(res.code == 200){
          this.$message.success("密码修改成功");
          this.editPassWordData.dialogShow = false;
        }
      })
    },
    deleteChooseTeacherId(data){
      this.$confirm('您确定删除当前信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass:'page_dialog',
        }).then(() => {
          this.$api.school.deleteTeacherBindRole({ids:[data.id]}).then((res)=>{
            if(res.code == 200){
              this.getTeacherInfo();
              this.teacherClassDetailsList();
              // this.$message.success("删除成功");
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    deleteChooseTeacher(){
      if(!this.selectedTeacher.teacherId){
        this.$message('请先选择一个老师....');
        return;
      }
      this.$confirm(`您是否要删除${this.selectedTeacher.teacherName}老师？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass:'page_dialog',
        }).then(() => {
          let param = {
            ids:[this.selectedTeacher.teacherId]
          }
          this.$api.school.deleteTeacher(param).then((res)=>{
            if(res.code == 200){
              this.$message.success("删除成功");
              this.getTeacherList();
              this.getAdminClass();
              this.getSectionClassCourseData();
            }
          })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      
      
    },
    //添加老师
    confirmTeacherAdd(){
      let {teacherCode,teacherDepartmentCode,teacherDepartmentName,username,teacherDuty} = this.editTeacherData;
      let param = {
        teacherCode,
        teacherDepartmentCode,
        teacherDepartmentName,
        teacherDuty,
        username
      }
      this.$refs["editTeacherData"].validate((valid) => {
        if(valid){
          if(this.editTeacherData.isEdit){
            param.id = this.editTeacherData.id;
            this.$api.school.editTeacher(param).then((res)=>{
              if(res.code == 200){
                this.$message.success('修改成功....');
                this.getTeacherList();
                this.getAdminClass();
                this.getSectionClassCourseData();
              }
              this.editTeacherData.dialogShow = false;
            }).catch((err)=>{

            })
            return;
          }
          //新增
          this.$api.school.addTeacher(param).then((res)=>{
            if(res.code == 200){
              this.$message.success('添加成功....');
              this.getTeacherList();
              this.getAdminClass();
              this.getSectionClassCourseData();
            }
          })
          this.editTeacherData.dialogShow = false;
        }
      })
      
    },
    //重置密码
    resetPassWord(type,data){
      // if(!this.selectedTeacher.teacherId){
      //   this.$message('请先选择一个老师....');
      //   return;
      // }
      if(type=="only"){
        this.editPassWordData.teacherName = data.teacherName;
        this.editPassWordData.userInfoId = data.userInfoId;
        this.editPassWordData.teacherCode = data.teacherCode;
      }
      this.editPassWordData.dialogShow = true;

    },
    //批量导入
    batchImport(){

    },
    //批量导出
    batchExport(){

    },
    //多老师重置密码
    resetMultiplePW(){
      this.editMultiplePassWordData.dialogShow = true;
    },
    confirmMultiplePassWord(){
      let param = {
            userId:this.editMultiplePassWordData.teacherIds,
            randomPassword:this.editMultiplePassWordData.newPassWord,
            type:1
        }
        this.$api.school.resetPassword(param).then((res)=>{
            if(res.code ==200){
                this.$message.success("重置成功");
                this.editMultiplePassWordData.dialogShow = false;
            }

        }).catch((err)=>{})
                  
      console.log(this.editMultiplePassWordData)
    },
    //课程批量导入
    courseBatchImport(e){
      console.log(e,"e~")
    },
    selGradeYearChange(e){
      this.selGradeYear.value = e;
      let selItem = this.selGradeYear.arr.find(item=>item.id == e)
      this.selTermList.arr = selItem.infoBOList;
      this.selTermList.value = selItem.infoBOList[0].id;
      this.getAdminClass();
      this.getSectionClassCourseData();
    },
    selTermChange(e){
      this.selTermList.value = e;
      this.getAdminClass();
      this.getSectionClassCourseData();
    },
    teacherNameChange(e){
      this.teacherName = e;
      throttle(this.getTeacherList(),60)
    },
    importTeacherList(){
      let formdata = new FormData();
      formdata.append("file",this.$refs.uploadStudents.files[0]);
      this.$api.school.importTeacherList(formdata).then((res)=>{
        if(res.code == 200){
          //刷新
          this.$message.success("导入成功");
          
          this.getTeacherList();
        }
        this.$refs.uploadStudents.value = '';
      })
    },
    chooseTeacherFile(){
      this.$refs.uploadStudents.click();
    },
    exportTeacherList(){
      if(!this.selGradeYear.value || !this.selTermList.value){
          this.$message.warning('未选择学年学期！');
          return;
      }
      this.$api.school.exportTeacherInfos({schoolSemesterId:this.selTermList.value}).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();
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.tableTopWrap{
  align-items: center;
}
.lyMainRight {
  flex: 1;
  padding-left: 20px;
  overflow-x:auto;
}
.mainTableTopWrap{
  padding:1px 0 0px 0;
  position: relative;
  .tableTopRight{
    &:nth-child{
      margin-right: 10px;
    }
  }
}
.tablePageBox {
  padding-top: 10px;
}
.tableTitle{
  color: #303133;
  line-height: 32px;
  font-size: 16px;
  font-weight: 500;
  padding-right: 15px;
}
.tagWrap{
  display: flex;
  flex-wrap: wrap;
  justify-content: center;     /* 控制主轴上的对齐方式 */
  line-height: 33px;
  margin-bottom: -10px;
  margin-right: -10px;
  .el-tag {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
:deep() .el-checkbox__label{
  color:#909399;
  font-size:12px;
}
:deep() .el-checkbox__input.is-checked + .el-checkbox__label{
  color:#909399;
  font-size:12px;
}
:deep() .el-input--small .el-input__inner{
  height: 36px;
}
:deep() .el-table thead {
  color: #303133;
  font-weight: 500;
  font-size: 16px !important;
  height: 52px;
}
:deep() .el-table tr th.el-table__cell{
  background: #F0F2F5;
}
:deep() .el-table tbody td{
  color:rgba(0,0,0,.9);
  font-weight: 400;
  font-size: 14px !important;
  height: 52px;
}
:deep() .el-dialog__headerbtn .el-dialog__close {
  color:#909399;
}
:deep() .el-dialog__header{
  text-align: left;
}
:deep() .dialog-footer{
  text-align: right;
}
:deep() .el-table__body-wrapper::-webkit-scrollbar {
/*  width: 5px;  设置滚动条宽度 */
  height:8px;
}

.treeList{
  border-radius: 6px;
}
:deep() .treeList .el-table__body-wrapper{
  overflow-y: auto;
}
:deep() .el-button.is-plain{
  background:rgba(0,0,0,0) !important;
}
:deep() .el-button--primary.is-plain:hover, :deep().el-button--primary.is-plain:focus{
  color:#2e64fa !important;
}
:deep() .xzb .el-table__body-wrapper,:deep().xzb .el-table__fixed-body-wrapper{
  overflow-y: auto;
}
:deep() .jxb .el-table__body-wrapper,:deep().jxb .el-table__fixed-body-wrapper{
  overflow: auto;
}
:deep() .teacherStyle .el-table__body-wrapper{
  overflow-y: auto;
}
:deep() .el-table__body-wrapper.is-scrolling-right ,:deep() .el-table__body-wrapper.is-scrolling-middle,:deep() .el-table__body-wrapper.is-scrolling-left{
  overflow: auto;
}
:deep() .heightSet .el-button,:deep() .heightSet input{
  height:36px !important;
  font-size:14px !important;
}
:deep() .heightSet .el-input-group__append{
  padding-left:10px;
  padding-right:9px;
}
:deep() .el-tag{
  font-size:14px !important;
  height: 36px;
  line-height: 33px;
  padding-left: 10px;
  padding-right: 15px;
}
.tagWrapFalse{
  display:inline-block;
  font-size: 14px;
  font-weight: 400;
  text-align: center;
  width:90px;
  height: 36px;
  background: #f6f6f6;
  color:#ccc;
  border-radius: 4px;
  line-height: 36px;
}
.tabTitle{
  padding: 6px 10px;
  font-size: 16px;
  color: #909399;
  margin-right: 5px;
  cursor: pointer;
  display: inline-block;
  gap: 6px;
}
.tabTitle.active {
  background: rgba(46,100,250,0.1); /* 浅蓝色背景 */
  color: #2e64fa; /* 激活字体蓝色 */
  box-shadow: 0px -2px 0px 0px #2E64FA inset;
}
.asideMainStyle{
  width: 200px; 
  height: 3rem;
}
.selectyear{width:150px;margin-right:10px;}
.selecGrade{width:90px;margin-right:10px;}
.defaultnbsp{
  color: #c0c4cc;
  font-size: 14px;
}
.tableButton button{
  font-size:14px;
}
.marginBottomStyle{
  margin-bottom: 20px;
}
:deep() .treeList .el-table__body-wrapper .el-table__body tbody tr td{
  height: 40px !important;
  padding: 0 !important;
}
:deep() .el-table .caret-wrapper{
  height: 34px;
  width: 16px;
}
.borderRadiusStyle{
  border-radius:6px;
}
:deep() .editCourseDialog{
  width: 450px;
}
.checkTeacher{
  display: inline-flex; 
  align-items: center;
  position: absolute;
  right: 0;
  top: 55px !important;
  z-index: 8888;
  button{
    padding: 0px !important;
  }
}
:deep() .jxbTeach .el-table__header-wrapper .el-table__header thead tr:nth-child(2){
  display: none !important; /* 隐藏第二列表头 */
}
:deep() .el-radio-button__inner{
  width: 100px;
  font-size: 14px;
  height: 36px;
  line-height: 22px;
}
:deep() .el-radio-group{
  margin-left: 0px !important;
}
.teacherStyle{
  margin-top: 20px;
}
:deep() .el-switch__label.is-active{
  color:#909399;
}
:deep() .el-switch__label>span{
  font-size:12px !important;
  color:#909399;
}
:deep() .el-switch__core{
  width: 24px !important;
  height: 14.4px;
}
:deep() .el-switch__core:after{
  width: 12px;
  height: 12px;
  top: 0.4px;
}
:deep() .el-switch.is-checked .el-switch__core::after{
  margin-left: -13px;
}
:deep() .el-switch__core:after{
  left:-0.5px
}
.custom-tag {
  width: 90px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  box-sizing: border-box;
  position: relative;
  text-align: left;
}
:deep() .custom-tag.el-tag .el-icon-close {
  position: absolute;          /* 将关闭按钮固定在右侧 */
  top: 10px;
  right: 3px;
}
:deep() .vxe-toolbar{
  padding:0
}
.el-tabs{
  margin-top: 10px;
}
</style>