<template>
  <div class="page_user page_search">
    <div class="page_jg_20"></div>
    <div class="search_content">
      <div class="content_left">
        <el-checkbox v-model="isEffective" @change="ChangeShowEffectGrade" >只显示有效学年</el-checkbox>
      </div>
      <div class="content_right">
        <el-button type="primary" @click="EditTermYear('add')" >
              <img src="@/assets/icon/add_icon.webp" />新增学年
        </el-button>
       
      </div>
    </div>
    <div v-for="(item,index) in gradeData" :key="item.index">
      <div class="page_jg_10" v-if="index==0"></div>
      <div class="page_jg_20" v-else></div>
      <div  class="search_content" style="margin-top: 10px;">
        <div class="content_left">
          <span class="grade_title">{{item.schoolYearName }}</span>
          <span >开始时间：{{item.schoolYearStartDate }}  结束时间：{{item.schoolYearEndDate }}</span>
        </div>
        <div class="content_right el_button">
          <el-tooltip  effect="dark" content="删除后，学年下的班级年级数据将会被清除，请谨慎操作！" placement="top" v-if="!GetIsDisabled(item)">
            <el-button class="delete_item"  @click="DeleteTermYear(item)" type="text" plain >删除学年</el-button>
          </el-tooltip>
          <!-- <el-button  type="text" class="delete_item" plain @click="(item)">删除学年</el-button> -->
          <!-- <el-button  type="text" class="editor_item" plain @click="EditTermYear(item)">编辑学年</el-button> -->
          <el-button class="add_button" @click="EditTermYear(item)">编辑学年</el-button>
        </div>
      </div>
      <div class="page_jg_20"></div>
      <div class="page_table">
        <el-table :data="item.schoolYearGradeVOS" border stripe >
          <el-table-column prop="gradeName" label="年级" align="center">
          </el-table-column>
          <el-table-column prop="schoolEnrolDate" label="入学年份" align="center">
          </el-table-column>
          <el-table-column prop="graduates" label="毕业年份" align="center">
          </el-table-column>
          <el-table-column prop="classNum" label="班级数" align="center">
          </el-table-column>
          <el-table-column prop="studentNum" label="学生数" align="center">
          </el-table-column>
          <el-table-column prop="teacherNum" label="教师数" align="center">
          </el-table-column>
          <el-table-column prop="gradeStartDate" label="开始时间" align="center">
          </el-table-column>
          <el-table-column prop="gradeEndDate" label="结束时间" align="center">
          </el-table-column>
          <el-table-column width="200" label="操作" align="center" :fit="true">
            <template slot-scope="scope">
              <div class="table_row_option">
                <el-button type="text"
                  @click="EditGradeItem(item, scope.row)">编辑</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
    </div>
    <div class="page_dialog">
      <!-- 编辑年级 -->
      <el-dialog title="编辑年级" center :visible.sync="addGradeData.dialogShow" width="480px">
        <div class="dialog_center padding_20">
          <el-form :model="addGradeData" style="flex:1;" :rules="addGradeDataRules" ref="addGradeData">
            <el-form-item label="所在学年：" label-width="100px" prop="gradeYearName">
              <el-input v-model="addGradeData.gradeYearName" disabled></el-input>
            </el-form-item>
            <el-form-item label="年级：" label-width="100px" prop="gradeName">
              <el-input v-model="addGradeData.gradeName" disabled></el-input>
            </el-form-item>
            <el-form-item label="入学年份 ：" label-width="100px" prop="enterYear">
              <el-input v-model="addGradeData.schoolEnrolDate" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="学期名称：" label-width="100px" prop="schoolSemesterName">
              <el-input v-model="addGradeData.schoolSemesterName" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="开始时间：" label-width="100px" prop="gradeStartDate">
              <el-date-picker v-model="addGradeData.gradeStartDate" type="date" format="yyyy-MM-dd"
                value-format="yyyy-MM-dd" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间：" label-width="100px" prop="gradeEndDate">
              <el-date-picker v-model="addGradeData.gradeEndDate" type="date" format="yyyy-MM-dd"
                value-format="yyyy-MM-dd" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addGradeData.dialogShow = false">取 消</el-button>
          <el-button type="primary" @click="ConfirmGraderYearEdit">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑学年 -->
      <el-dialog :title="editTermGrade.title" center :visible.sync="editTermGrade.dialogShow" width="480px">
        <div class="dialog_center padding_20">
          <el-form :model="editTermGrade" style="flex:1;" :rules="editTermGradeRules" ref="editTermGrade">
            <el-form-item label="学年名称：" label-width="100px" prop="schoolYearName">
              <!-- <el-input v-model="editTermGrade.schoolYearName"></el-input> -->
              <el-select class="select_width" v-model="editTermGrade.schoolYearCode" placeholder="请选择学年" @change="ChangeSchoolYear" >
                <el-option
                  v-for="item in schoolGradeList"
                  :key="item.value"
                  :label="item.value+'学年'"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="开始时间：" label-width="100px" prop="schoolYearStartDate">
              <el-date-picker v-model="editTermGrade.schoolYearStartDate" type="date" placeholder="选择日期"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间：" label-width="100px" prop="schoolYearEndDate">
              <el-date-picker v-model="editTermGrade.schoolYearEndDate" type="date" placeholder="选择日期" format="yyyy-MM-dd"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editTermGrade.dialogShow = false">取 消</el-button>
          <el-button type="primary" @click="ConfirmTermYearEdit">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="page_jg_20"></div>
  </div>
</template>
<script>
import { throttle } from "lodash";
export default {
  data() {
    return {
      gradeData: [],
      schoolGradeList:[],//学年列表选择
      gradeAllData: [],
      showEffectGrade: true,
      addSchoolYearData: {
        dialogShow: false,
        schoolYearName: '',
        schoolYearCode: '',
        schoolYearStartDate: '',
        schoolYearEndDate: ''
      },
      editTermGrade: {
        dialogShow: false,
        schoolYearName: "",
        schoolYearCode: '',
        schoolYearStartDate: "",
        schoolYearEndDate: "",
      },
      editTermGradeRules: {
        
        schoolYearStartDate: [
          { required: true, message: '请输入开始时间', trigger: 'blur' },
        ],
        schoolYearEndDate: [
          { required: true, message: '请输入结束时间', trigger: 'blur' },
        ],
      },
      
      addGradeData: {
        dialogShow: false,
        gradeYearName: "",//所在学年
        gradeName:"",//年级名称
        gradeYearCode: "",//学年code
        schoolEnrolDate: "",//入学年份
        id: "",//年级id
        schoolSemesterName: "",//学期名称
        gradeStartDate: "",//年级开始时间
        gradeEndDate: "",//年级结束时间
        schoolYearStartDate:'',//学年开始时间
        schoolYearEndDate:'',//学年结束时间

      },//编辑年级相关参数
      addGradeDataRules: {
       
        schoolSemesterStartDate: [
          { required: true, message: '请输入开始时间', trigger: 'blur' },
        ],
        schoolSemesterEndDate: [
          { required: true, message: '请输入结束时间', trigger: 'blur' },
        ],
      },
      gradeTypes: {
        "0": "全学期",
        "1": "半期（上学期）",
        "2": "半期（下学期）"
      },
      gradeArr: {
        value: "",
        arr: [

        ],
      },
      yearDataTerm: {},
      courseDataInfo: [],
      isEffective: true,//是否显示有效学年
      tableHeight:0,//表格高度
    }
  },
  mounted() {
    this.GetSchoolTermList();//获取学年学期列表
    this.GetSchoolGradeList();//获取年级列表
    this.SetTableHeight(); //设置表格高度
    window.addEventListener("resize", this.HandleResize); //监听窗口大小变化
  },
  beforeDestroy() {
      // 组件销毁移除监听 防止内存泄漏
      window.removeEventListener("resize", this.HandleResize);
  },
  watch: {
    
  },
  methods: {

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



    //获取学年学期列表
    GetSchoolTermList()
    {
      let param = { 
        effective:this.isEffective,//是否显示有效学年
      };
      this.$api.user.getSchoolTermList(param).then((res) => {
        console.log("打印学年学期列表",res);
        if (res.code == 200) {
          this.gradeData = res.data;
        }

      })
    },

    //获取学年列表
    GetSchoolGradeList()
    {
      let param = { 
       
      };
      this.$api.user.getSchoolGradeList(param).then((res) => {
        console.log("打印学年列表",res);
        if (res.code == 200) {
          this.schoolGradeList = res.data;
        }

      })
    },

    //选择有效学年事件
    ChangeShowEffectGrade() 
    {
      this.GetSchoolTermList();//重新加载数据
    },

    //切换学年
    ChangeSchoolYear()
    {
      console.log("切换学年",this.editTermGrade.schoolYearCode);
      console.log("切换学年",this.editTermGrade);
      let gradeYearList=this.editTermGrade.schoolYearCode.split('-');

  
      this.editTermGrade.schoolYearStartDate=gradeYearList[0]+'-08-15';
      this.editTermGrade.schoolYearEndDate=gradeYearList[1]+'-08-14';
      
      
    },


    
    // 编辑学年
    EditTermYear(item) 
    {
      if (item != 'add') 
      {
        //编辑学年
        this.editTermGrade = {
          dialogShow: true,
          isEdit: true,
          title: "编辑学年",
          schoolYearName: item.schoolYearName,
          schoolYearCode: item.schoolYearCode,
          schoolYearStartDate: item.schoolYearStartDate,
          schoolYearEndDate: item.schoolYearEndDate,
          id: item.id
        }

      } 
      else 
      {
        //新增学年 规则  如果是8月之后的  按下一个月学年  之前的为上一个学年
        let currentYear = new Date().getFullYear();
        let currentMonth = new Date().getMonth() + 1;
        
        let startYear=currentYear;
        let endYear=currentYear;
        if (currentMonth >= 8) {
          startYear=currentYear;
          endYear=currentYear+1;
        }
        else
        {
          startYear=currentYear-1;
          endYear=currentYear;
        }
        this.editTermGrade = {
          dialogShow: true,
          isEdit: false,
          title: "新增学年",
          schoolYearName: `${startYear}-${endYear}学年`,
          schoolYearCode: `${startYear}-${endYear}`,
          schoolYearStartDate: `${startYear}-08-15`,
          schoolYearEndDate: `${endYear}-08-14`,
        }
      }
    },

    //编辑年级
    EditGradeItem(item, gradeItem) 
    {
      console.log("打印item",item);
      console.log("打印gradeItem",gradeItem);
      this.addGradeData = {
        dialogShow: true,
        gradeYearName: item.schoolYearName,//所在学年
        gradeName:gradeItem.gradeName,//年级名称
        schoolEnrolDate: gradeItem.schoolEnrolDate,//入学年份
        id: gradeItem.id,//id
        schoolSemesterName:item.schoolYearName+gradeItem.gradeName+'全学期',//学期名称
        gradeStartDate: gradeItem.gradeStartDate,//年级开始时间
        gradeEndDate: gradeItem.gradeEndDate,//年级结束时间
        schoolYearStartDate:item.schoolYearStartDate,//学年开始时间
        schoolYearEndDate:item.schoolYearEndDate,//学年结束时间
      };
      console.log("打印addGradeData",this.addGradeData);
      this.addGradeData.dialogShow = true;
    },

    //判断是否可以删除
    GetIsDisabled(item)
    {
      let result=false;
      console.log("打印item",item);
      // 检查是否有学生数大于0的情况
      if(item.schoolYearGradeVOS)
      {
        const hasStudentNumGreaterThanZero = item.schoolYearGradeVOS.some(grade => grade.studentNum > 0);
        //验证 如果该学年下有数据则不允许删除
        console.log("item",item)
        if (hasStudentNumGreaterThanZero) {
          result=true;
        }
        // 检查是否有班级数大于0的情况
        const hasTeacherNumGreaterThanZero = item.schoolYearGradeVOS.some(grade => grade.teacherNum > 0);
        if (hasTeacherNumGreaterThanZero) {
          result=true;
        }
      }
      
      return result;
    },

    //删除学年
    DeleteTermYear(item) 
    {

      if(item.schoolYearGradeVOS)
      {
        // 检查是否有学生数大于0的情况
        const hasStudentNumGreaterThanZero = item.schoolYearGradeVOS.some(grade => grade.studentNum > 0);
        //验证 如果该学年下有数据则不允许删除
        console.log("item",item)
        if (hasStudentNumGreaterThanZero) {
          this.$message.error("该学年下有学生数据，不能删除！");
          return;
        }
        // 检查是否有班级数大于0的情况
        const hasTeacherNumGreaterThanZero = item.schoolYearGradeVOS.some(grade => grade.teacherNum > 0);
        if (hasTeacherNumGreaterThanZero) {
          this.$message.error("该学年下有教师数据，不能删除！");
          return;
        }
        
      }
      this.$confirm('确定要删除当前学年吗？删除后，学年下的班级年级数据将会被清除，请谨慎操作!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'page_dialog',
        }).then(() => {
        
          
      
          let params = {
            id: item.id
          }
          this.$api.user.deleteSchoolTerm(params).then((res) => {
            console.log(res)
            if (res && res.code == 200) {
            
              this.$message({
                type: 'success',
                message: '删除成功！'
              });
              this.GetSchoolTermList();
            }
            else
            {
              this.$message({
                type: 'error',
                message: '删除失败！'+res.msg
              });
            }
            
          }, (err) => {
        
          }).then((err) => {
            
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除！'
          });
        });
      
      console.log(item)
    },

    //确认新增或者编辑学年
    ConfirmTermYearEdit() 
    {
      if(this.editTermGrade.schoolYearCode=='')
      {
        this.$message.error("请选择学年名称!");
        return;
      }
      this.$refs["editTermGrade"].validate((valid) => {
        if (valid) {

          //判断时间验证
          if(this.editTermGrade.schoolYearEndDate<this.editTermGrade.schoolYearStartDate)
          {
            this.$message.error("结束时间不能小于开始时间!");
            return;
          }
          let param={
              "schoolYearEndDate": this.editTermGrade.schoolYearEndDate,
              "schoolYearCode": this.editTermGrade.schoolYearCode,
              "schoolYearName": this.editTermGrade.schoolYearName,
              "schoolYearStartDate": this.editTermGrade.schoolYearStartDate,
          };

          
          if (this.editTermGrade.isEdit) 
          {
            //编辑
            param={
              "id":this.editTermGrade.id,
              "schoolYearEndDate": this.editTermGrade.schoolYearEndDate,
              "schoolYearCode": this.editTermGrade.schoolYearCode,
              "schoolYearName": this.editTermGrade.schoolYearCode+'学年',
              "schoolYearStartDate": this.editTermGrade.schoolYearStartDate,
            };
          }
          else
          {
            //新增
            param={
              "schoolYearEndDate": this.editTermGrade.schoolYearEndDate,
              "schoolYearCode": this.editTermGrade.schoolYearCode,
              "schoolYearName": this.editTermGrade.schoolYearCode+'学年',
              "schoolYearStartDate": this.editTermGrade.schoolYearStartDate,
            };
          }
          
          this.$api.user.saveSchoolTerm(param).then((res) => {
            console.log("保存新增学年返回信息",res);
            if (res && res.code == 200) {
              
              this.$message.success("保存成功");
              this.GetSchoolTermList();//获取学年学期列表
              this.editTermGrade.dialogShow = false;
            }
            else
            {
              this.$message.error(res.msg);
            }
            
          })
        } else {
         
          return false;
        }
      });
    },

    //确认编辑年级
    ConfirmGraderYearEdit() 
    {
      console.log("打印addGradeData",this.addGradeData);
      
        if(!this.addGradeData.gradeStartDate)
        {
          this.$message.error("请选择开始时间!");
          return
        }

        if(!this.addGradeData.gradeEndDate)
        {
          this.$message.error("请选择结束时间!");
          return
        }
      
      
        //判断时间验证
        if(this.addGradeData.gradeStartDate<this.addGradeData.schoolYearStartDate)
        {
          this.$message.error("开始时间不能小于学年的开始时间!");
          return;
        }

        //判断时间验证
        if(this.addGradeData.gradeEndDate>this.addGradeData.schoolYearEndDate)
        {
          this.$message.error("结束时间不能大于学年的结束时间!");
          return;
        }

        //判断时间验证
        if(this.addGradeData.gradeStartDate>this.addGradeData.gradeEndDate)
        {
          this.$message.error("开始时间不能小于结束时间!");
          return;
        }
        let param={
            "gradeEndDate": this.addGradeData.gradeEndDate,
            "gradeStartDate": this.addGradeData.gradeStartDate,
            "id": this.addGradeData.id
        };
        this.$api.user.saveGraderInfo(param).then((res) => {
          console.log("保存编辑年级返回信息",res);
          if (res && res.code == 200) {
            
            this.$message.success("保存成功");
            this.GetSchoolTermList();//获取学年学期列表
            this.addGradeData.dialogShow = false;
          }
          else
          {
            // this.$message.error(res.msg);
          }
          
        })
        
     

    },

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