<template>
  <div class="page_user page_search">
    <div class="page_jg_20"></div>
    <div class="search_content">
      <div class="content_left">
      </div>
      <div class="content_right">
        <el-button type="primary" @click="OpenEditorDialog()" >
              <img src="@/assets/icon/add_icon.webp" />配置年级
        </el-button>
      </div>
    </div>
    <div class="page_jg_20"></div>
    <template v-for="level in gradeCourseList">
      <div class="year_subject" v-for="item in level.pcSchoolGradeVOS"  v-if="item.pcGradeCourseVOS.length>0">
        <div class="year_header">
          <span class="header_left"
            >{{ item.gradeName }}（共{{ item.pcGradeCourseVOS.length }}科）</span
          >
          <span class="header_right" @click="OpenEditorDialog(item)">
            编辑
          </span>
        </div>
        <div class="subject_content">
          <div class="subject_title">科目：&nbsp;</div>
          <div class="subject_list">
              <div v-for="tag in item.pcGradeCourseVOS" :key="tag.id"  class="list_item">
                <span>{{ tag.courseName }}</span>   
                <img src="@/assets/icon/close_tag.webp" @click="OpenDeleteDialog(item,tag)">
              </div>
          </div>
        </div>
      </div>
    </template>
    
    <div class="page_dialog">
      <el-dialog title="提示" :visible.sync="showDeleteDialog" width="400px">
        <div class="dialog_message">
          您是否要删除当前的年级科目({{deleteCourseItem.courseName || '' }})?
        </div>
        <div slot="footer" class="dialog_footer">
          <div class="footer_left">
              
          </div>
          <div class="footer_right">
            <el-button @click="showDeleteDialog = false">取 消</el-button>
            <el-button type="primary" @click="EnterDeleteCourse">确 定</el-button>
          
          </div>
        </div>
      </el-dialog>

      <el-dialog
        :title="dialogTitle"
        :visible.sync="showEditorDialog" width="800px"
      >
        <div class="content_course_tree padding_20" >

          <div class="tree_item">
              <p class="header_title">年级</p>
              <div class="item_content" style="overflow-y: auto;">
                  <div class="page_tree">
                    <el-tree
                      ref="tree"

                      default-expand-all
                      :default-expanded-keys="selectedKeys"
                      :current-node-key="currentNodeKey"
                      :highlight-current="true"
                      node-key="id"
                      :props="defaultProps"
                      :data="gradeCourseList"
                      @node-click="TreeNodeClick"
                    ></el-tree>
                  </div>
              </div>
              
          </div>
          <div class="tree_item">
              <p class="header_title">可选科目</p>
              <div class="item_content">
                <div class="check_all">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="HandleCheckAllChange">全选</el-checkbox>
                </div>
                <div class="check_content">
                  <el-checkbox-group
                    v-model="checkCourseList"
                    @change="HandleCheckedCitiesChange"
                  >
                    <el-checkbox
                      v-for="course in courseList"
                      :label="course.courseCode"
                      :key="course.courseCode"
                      >{{ course.courseName }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
          </div>
          <div class="tree_item">
              <p class="header_title">已选科目</p>
              <div class="item_content" style="overflow-y: auto;">
                
                  <div v-for="course in selectCourseList" :key="course.courseCode" class="select_item">
                    <span>{{ course.courseName }}</span>
                    <i
                      class="el-icon-circle-close"
                      @click="DeleteSelectCourse(course)"
                    ></i>
                  </div>
                
              </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showEditorDialog=false">取 消</el-button>
          <el-button type="primary" @click="SaveGradeCourseInfo()"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
    
  </div>
</template>
<script>
export default {
  data() {
    return {
      //新版参数
      gradeCourseList:[],//年级科目列表  页面使用

      defaultProps: {
        label: 'label',
        children: 'pcSchoolGradeVOS',
        isLeaf: 'leaf'
      },//tree自定义节点
      courseList:[],//开通的科目列表  可选科目 弹窗使用
      gradeList: [], //  年级tree数据  开通的年级列表  弹窗使用

      checkCourseList:[],//选择的科目code
      selectCourseList:[],//已选择的科目列表  临时使用

      checkAll: false,//是否选择全部
      isIndeterminate: false,

      showDeleteDialog:false,//删除弹窗
      showEditorDialog:false,//编辑弹窗 或者新增弹窗
      dialogTitle:'配置年级',//弹窗标题
      deleteCourseItem:{},//删除的item
      selectedKeys:[],//选中的key
      currentNodeKey:'9',//当前选中的节点key
      currentGrandeItem:{},//当前设置的年级

    };
  },
  mounted() 
  {
    this.GetSchoolGradeAndCourse();
  },
  watch: {
    selectCourseList()
    {
     
      this.GetIsCheckAll();
    }
  },
  methods: {

    // 将 levelVOS 转换为 el-tree 所需的格式
    TransformToTreeFormat(levelVOS) 
    {
      return levelVOS.map(level => ({
        levelName: level.levelName,
        levelCode: level.levelCode,
        label:level.levelName,
        id:level.levelCode,
        pcSchoolGradeVOS: level.pcSchoolGradeVOS.map(grade => ({
          gradeCode:grade.gradeCode,
          gradeName: grade.gradeName,
          graduationYears: grade.graduationYears,
          levelCode:grade.levelCode,
          levelFirst:grade.levelFirst,
          levelName:grade.levelName,
          schoolId:grade.schoolId,
          label:grade.gradeName,
          id:grade.id,
          pcGradeCourseVOS: grade.pcGradeCourseVOS.map(course => ({
            courseName: course.courseName, 
            courseCode: course.courseCode,
            courseLeaders: course.courseLeaders,
            id: course.id
          }))
        }))
      }));
    },

    //获取学校年级科目信息
    GetSchoolGradeAndCourse()
    {
      this.$api.user.getSchoolGradeAndCourse().then(res => {
        console.log("打印获取的学校年级科目信息", res);
        if (res.code == 200 && res.data) 
        {

          this.courseList=res.data.adminCourseVOS || [];//科目list
          
          this.gradeCourseList=this.TransformToTreeFormat(res.data.levelVOS || []);//年级courselist
          console.log("打印科目列表",this.gradeCourseList);
        }
      })
    },

    // 弹窗删除已选的科目
    DeleteSelectCourse(item) 
    {
      const index=this.checkCourseList.findIndex(selectCourse=>selectCourse===item.courseCode);
      if(index !==-1)
      {
        this.checkCourseList.splice(index,1);
        //删除对应的源数据
        this.selectCourseList=this.courseList.filter(course=>this.checkCourseList.includes(course.courseCode));
      }
    },

    //更新全选或者半选的状态
    GetIsCheckAll()
    {
      if(this.checkCourseList.length>0)
      {
        
        this.checkAll=true;
        if(this.checkCourseList.length<this.courseList.length)
        {

          this.isIndeterminate=true;
        }
        else
        {
          this.isIndeterminate=false;
        }
      }
      else 
      {
        this.checkAll=false;
        this.isIndeterminate=false;
      }
      console.log("打印this.isIndeterminate",this.isIndeterminate);
      console.log("打印this.checkAll",this.checkAll);
    },

    //页面删除科目
    OpenDeleteDialog(item,course)
    {
      console.log("item",item);
      this.deleteCourseItem=course;
      this.$confirm(`您是否要删除当前的年级科目  ${course.courseName}吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass:'page_dialog',
      }).then(() => {
          let param={
            id:course.id,
          };
          this.$api.user.deleteGredeCourse(param).then((res) => {
              if (res.code == 200) 
              {

                
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.GetSchoolGradeAndCourse();//更新数据
              }
            });
          
      }).catch(() => {
          //取消         
      });

      
    },

    //确认删除科目
    EnterDeleteCourse()
    {
      let param={
        id:this.deleteCourseItem.id,
      };
      this.$api.user.deleteGredeCourse(param).then((res) => {
          if (res.code == 200) 
          {
            this.showDeleteDialog = false;
            
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.GetSchoolGradeAndCourse();//更新数据
          }
        });
    },

    //保存年级科目信息
    SaveGradeCourseInfo()
    {

      console.log("打印当前选择的年级科目信息",this.currentGrandeItem);
      console.log("打印当前选择的科目信息数据",this.selectCourseList);

      if(!this.currentGrandeItem.gradeName)
      {
        this.$message({
          message: "请选择年级!",
          type: "warning",
        });
        return
      }
      if(this.selectCourseList.length==0)
      {
        this.$message({
          message: "请至少选择一个科目!",
          type: "warning",
        });
        return;
      }
      let param=[];
      let gradeCourseInfo={
        
          gradeCode: this.currentGrandeItem.gradeCode,
          gradeName: this.currentGrandeItem.gradeName,
          levelCode: this.currentGrandeItem.levelCode,
          levelName: this.currentGrandeItem.levelName,
          pcGradeCourseDTOS:this.selectCourseList,
          schoolGradeId: this.currentGrandeItem.id,
          schoolId: this.currentGrandeItem.schoolId,
      };
      param.push(gradeCourseInfo);
      
      this.$api.user.saveGradeCourseInfo(param).then((res) => {
        console.log("打印保存的结果",res);
        if(res.code==200)
        {
          this.$message({
            message: '保存成功',
            type: 'success'
          });
          //更新数据并关闭弹窗
          this.showEditorDialog=false;
          this.GetSchoolGradeAndCourse();
        }
        

      });
    },


    // 配置/编辑年级
    OpenEditorDialog(item) 
    {
      this.showEditorDialog=true;
      console.log("打印item",item);
      if(item)
      {
        //编辑
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(item.id); // 设置当前选中的节点
        });
        this.currentGrandeItem=item;//设置选择的年级
        this.checkCourseList=item.pcGradeCourseVOS.map((course) => course.courseCode);
        this.selectCourseList=this.courseList.filter(course=>this.checkCourseList.includes(course.courseCode));
        
      }
      else
      {
        this.currentGrandeItem={};//当前设置的年级 清空
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(null); // 设置当前选中的节点
        });
        this.checkCourseList=[];
        this.selectCourseList=[];//已选择的科目
        this.indeterminate=false;
        this.checkAll=false;
      }
      this.GetIsCheckAll();//更新全选的状态
    },
    // 科目全选
    HandleCheckAllChange() {
      if (this.checkAll) 
      {
        this.checkCourseList = this.courseList.map(item => {
            return item.courseCode;
        });
        this.selectCourseList=this.courseList.filter(course=>this.checkCourseList.includes(course.courseCode));
      } 
      else 
      {
        this.checkCourseList=[];
        this.selectCourseList=[];
        this.isIndeterminate=false;
      }
    },
    // 从可选添加到已选
    HandleCheckedCitiesChange(value) 
    {
      console.log("打印value",value);
      this.selectCourseList=this.courseList.filter(course=>value.includes(course.courseCode));

      console.log("打印选择的科目",this.selectCourseList);

    },


    // tree点击
    TreeNodeClick(gradeItem) 
    {
      console.log("打印gradeItem",gradeItem);

      if (gradeItem.gradeCode) 
      {
        this.currentGrandeItem=gradeItem;
        this.checkCourseList=gradeItem.pcGradeCourseVOS.map((course) => course.courseCode);
        this.selectCourseList=this.courseList.filter(course=>this.checkCourseList.includes(course.courseCode));
        
      }
      
      this.GetIsCheckAll();//更新全选的状态
      
      
    },
  },
};
</script>
<style lang="scss" scoped>

.year_subject
{
  width: 100%;
  height: auto;
  background: #FFFFFF;
  border-radius: 10px 10px 10px 10px;
  border: 1px solid #E4E7ED;
  margin-bottom: 20px;

  .year_header
  {
    width: calc(100% - 40px);
    margin: auto;
    border-bottom: 1px solid #E4E7ED;
    height: 57px;
    line-height: 57px;
    display: flex;
    justify-content: space-between;
    .header_left
    {
      font-weight: 600;
      font-size: 18px;
      color: #000000;
    }

    .header_right
    {
      font-weight: 400;
      font-size: 14px;
      color: #2E64FA;
      cursor: pointer;
    }

  }

  .subject_content
  {
    width: calc(100% - 40px);
    margin: auto;
    display: flex;
    justify-content: space-between;
    padding-top: 20px;
    padding-bottom: 20px;
    .subject_title
    {
      width: 60px;
      height: auto;
      font-weight: 400;
      font-size: 16px;
      color: #000000;
      line-height: 36px;
      align-self: flex-start; /* 默认情况下，多行时靠顶部对齐 */
      display: flex;
      align-items: center; /* 一行时垂直居中 */
      min-height: 36px; /* 设置一个最小高度，确保一行时有足够的空间垂直居中 */

    }
    .subject_list
    {
      width: calc(100% - 60px);
      height: auto;
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      gap:20px ;

      .list_item
      {

        background: rgba(46,100,250,0.1);
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #2E64FA;
        width: auto;
        height: 34px;
        line-height: 34px;
        padding: 0 10px;
        font-weight: 400;
        font-size: 14px;
        color: #2E64FA;

        display: flex;
        justify-content: space-between;
        align-items: center;

        span
        {
          margin-right: 8px;
        }

        img
        {
          width: 16px;
          height: 16px;
          cursor: pointer;
        }
        img:hover
        {
          opacity: 0.8;
        }
      }
    }
  }
}
</style>
