<template>
  <div class="page-container courseManagement-studyCourses">
    <div class="top-button-box">
      <p @click="addBigItem()" v-show="!showType">添加课件</p>
      <p>共计 {{num1}} 个知识点，{{num2}} 个课件，要求时长 {{num3}} 分钟，可得 {{num4}} 学时</p>
    </div>
    <div class="content-box scrollbar-box">
      <!-- 大项列表 -->
      <p v-if="!dataList[0]" style="color:#999;font-size:16px; line-height:200px;text-align: center;">请添加课件</p>
      <div
        class="for-max-box"
        v-for="(item, index) in dataList"
        :key="index"
        @dragstart="onBigDragStart($event, index)"
        @dragover.prevent="onBigDragOver($event, index)"
        @drop="onBigDrop($event, index)"
        @dragend="onDragEndBig"
      >
        <div class="max-big-name-box">
          <p @click="showButton(index)" :class="item.showType?'el-icon-arrow-up':'el-icon-arrow-down'"></p>
          <p>{{item.data1}}</p>
          <p>共 {{item.data2}} 个课件，要求时长 {{item.data3}} 分钟，可得 {{item.data4}} 学时</p>
          <p class="el-icon-delete-solid" v-show="!showType" @click="delBigItem(index)"></p>
          <!-- 大项拖拽手柄 -->
          <p class="el-icon-rank drag-handle" draggable="true" v-show="!showType" title="拖动排序"></p>
          <p class="el-icon-circle-plus" v-show="!showType" @click="addMinItem(item,index)"></p>
        </div>

        <div class="max-big-title-box" v-show="item.showType">
          <div class="big-title-box">
            <p>课件名称</p><p>来源</p><p>课件类型</p><p>要求时长</p><p>可获学时</p><p v-show="!showType">操作</p>
          </div>

          <!-- 小项列表 -->
          <div
            class="for-text-box"
            v-for="(minItem, minIndex) in item.minList"
            :key="minIndex"
            @dragstart="onSmallDragStart($event, index, minIndex)"
            @dragover.prevent="onSmallDragOver($event, minIndex)"
            @drop="onSmallDrop($event, index, minIndex)"
            @dragend="onDragEnd"
          >
            <p>{{minItem.minData1}}</p>
            <p>{{minItem.minData2}}</p>
            <p>{{minItem.minData3==1?'视频':(minItem.minData3==3?'文档':(minItem.minData3==4?'文章':''))}}</p>
            <p>{{minItem.minData4}}</p>
            <p>{{minItem.minData5}}</p>
            <p class="el-icon-delete-solid" v-show="!showType" @click="delItem(index, minIndex)"></p>
            <!-- 小项拖拽手柄 -->
            <p class="el-icon-rank drag-handle" draggable="true" v-show="!showType" title="拖动排序"></p>
            <p class="el-icon-view" v-show="!showType" @click="lookItem(minItem)"></p>
          </div>
        </div>
      </div>
    </div>
    <el-drawer
      size="100%"
      custom-class="courseManagement-drawer"
      :append-to-body="true"
      title="选择课件"
      ref="drawer"
      :visible.sync="drawer"
      direction="rtl">
      <drawerItem ref="drawerItem" v-if="drawer" :drawerItemPropsData="drawerItemPropsData"></drawerItem>
    </el-drawer>
    <fullScreenFileLook ref="fullScreenFileLook"></fullScreenFileLook>
  </div>
</template>

<script>
  //import { getDicts } from "@/api/commonality/noPermission";
  //import { systemUserSelect } from "@/api/commonality/permission";
  //import { getInfo } from "@/api/basicsModules/index";
  import fullScreenFileLook from "@/components/fullScreenFileLook/fullScreenFileLook.vue";
  import drawerItem from "./drawerItem.vue";
  import { examElCoursewareDetail } from "@/api/safetyEducationExaminationNew/index";
  export default {
    name: 'studyCourses',
    components: {
      drawerItem,
      fullScreenFileLook
    },
    props:{
      propsData:{},
    },
    data(){
      return{
        newData:{},
        num1:0,
        num2:0,
        num3:0,
        num4:0,
        dataList:[
          // {
          //   showType:true,
          //   data1:'知识点1',
          //   data2:2,
          //   data3:20,
          //   data4:4,
          //   knowledgePointId:'123',
          //   minList:[
          //     {
          //       minData1:'名称1.mp4',
          //       minData2:'化学类',
          //       minData3:'视频',
          //       minData4:'5分钟',
          //       minData5:'0.5',
          //     },
          //     {
          //       minData1:'名称2.mp4',
          //       minData2:'化学类',
          //       minData3:'视频',
          //       minData4:'5分钟',
          //       minData5:'0.5',
          //     },
          //   ],
          // }
        ],
        //拖拽相关
        dragInfo: {
          type: null, // 'big' 或 'small'
          bigIndex: null,
          smallIndex: null
        },
        drawer:false,
        drawerItemPropsData:{
          knowledgePointId:null,
          checkIndex:null,
        },
        showType:false,
      }
    },
    created(){

    },
    mounted(){

    },
    methods:{
      //查看模式
      setShowType(){
        this.$set(this,'showType',true);
      },
      //写入详情
      setDataInfo(list){
        this.$set(this,'dataList',list);
        this.statisticalCalculation();
      },
      //查看课件
      lookItem(item){
        //富文本
        examElCoursewareDetail({id:item.id}).then(response => {
          //预览
          let name=response.data.coursewareName;
          let url='';
          let type='';
          if(response.data.materialType == 1){
            //视频
            type = 'video'
            url = response.data.attachmentPath;
            this.$refs['fullScreenFileLook'].initialize(name,url,type);
          }else if(response.data.materialType == 3){
            //文档
            if(response.data.attachmentType == '.docx'){
              type = 'docx'
            }else if(response.data.attachmentType == '.xlsx'){
              type = 'excel'
            }else if(response.data.attachmentType == '.pdf'){
              type = 'pdf'
            }
            url = response.data.attachmentPath;
            this.$refs['fullScreenFileLook'].initialize(name,url,type);
          }else if(response.data.materialType == 4){
            type = 'text'
            url = response.data.articleContent;
            this.$refs['fullScreenFileLook'].initialize(name,url,type);
          }
        });
      },
      //弹窗返回
      drawerReturnButton(){
        this.$refs.drawer.closeDrawer();
      },
      //弹窗确定
      drawerConfirmButton(data) {
        let self = this;
        // --- 核心修改：计算当前 dataList 下所有 minList 的总数 ---
        let currentTotalMin = 0;
        self.dataList.forEach(item => {
          if (item.minList && item.minList.length) {
            currentTotalMin += item.minList.length;
          }
        });
        // 计算本次操作即将新增的 minList 数量
        let addMinCount = 0;
        if (!data.knowledgePointId) {
          // 大项添加时，新增数量取决于 data.data.minList
          addMinCount = data.data.minList ? data.data.minList.length : 0;
        } else {
          // 子项添加时，新增数量取决于 data.list
          addMinCount = data.list ? data.list.length : 0;
        }

        // 判断是否超过 100 个限制
        if (currentTotalMin + addMinCount > 100) {
          self.msgError(`最多只能添加 100 个子项！当前已有 ${currentTotalMin} 个，本次尝试添加 ${addMinCount} 个。`);
          return; // 超过限制，直接终止后续操作
        }

        // 用于存储最终要显示的提示信息
        let toastMessage = '';

        if (!data.knowledgePointId) {
          // --- 大项添加 ---
          let existingItemIndex = self.dataList.findIndex(item => item.knowledgePointId === data.data.knowledgePointId);

          if (existingItemIndex > -1) {
            // 1. 如果大项已存在，则合并其 minList
            let existingMinList = self.dataList[existingItemIndex].minList || [];
            let newMinList = data.data.minList || [];

            // 统计新增和重复的数量
            let addedCount = 0;
            let duplicateCount = 0;

            let uniqueNewMinList = newMinList.filter(newItem => {
              const isDuplicate = existingMinList.some(existingItem => existingItem.id === newItem.id);
              if (isDuplicate) {
                duplicateCount++;
              } else {
                addedCount++;
              }
              return !isDuplicate;
            });

            // 合并并更新
            self.dataList[existingItemIndex].minList = [...existingMinList, ...uniqueNewMinList];

            // 重新计算统计数据
            let numA = 0;
            let numB = 0;
            let numC = 0;
            for (let o = 0; o < self.dataList[existingItemIndex].minList.length; o++) {
              numA++;
              numB = self.addAndFormat(numB, self.dataList[existingItemIndex].minList[o].minData4);
              numC = self.addAndFormat(numC, self.dataList[existingItemIndex].minList[o].minData5);
            }
            self.dataList[existingItemIndex].data2 = numA;
            self.dataList[existingItemIndex].data3 = numB;
            self.dataList[existingItemIndex].data4 = numC;

            // 生成提示信息
            if (addedCount > 0 && duplicateCount > 0) {
              toastMessage = `${addedCount}个课件已添加，${duplicateCount}个课件重复已过滤`;
            } else if (addedCount > 0) {
              toastMessage = `${addedCount}个课件已添加`;
            } else if (duplicateCount > 0) {
              toastMessage = `${duplicateCount}个课件重复已过滤`;
            }

          } else {
            // 2. 如果大项不存在，则直接添加
            self.dataList.push(data.data);
            // 直接添加，所有都是新增的
            const addedCount = data.data.minList ? data.data.minList.length : 0;
            if (addedCount > 0) {
              toastMessage = `${addedCount}个课件已添加`;
            }
          }

        } else {
          // --- 子项添加 ---
          let targetMinList = self.dataList[data.checkIndex].minList || [];
          let newMinList = data.list || [];

          // 统计新增和重复的数量
          let addedCount = 0;
          let duplicateCount = 0;

          let uniqueNewMinList = newMinList.filter(newItem => {
            const isDuplicate = targetMinList.some(existingItem => existingItem.id === newItem.id);
            if (isDuplicate) {
              duplicateCount++;
            } else {
              addedCount++;
            }
            return !isDuplicate;
          });

          // 合并并更新
          self.dataList[data.checkIndex].minList = [...targetMinList, ...uniqueNewMinList];

          // 生成提示信息
          if (addedCount > 0 && duplicateCount > 0) {
            toastMessage = `${addedCount}个课件已添加，${duplicateCount}个课件重复已过滤`;
          } else if (addedCount > 0) {
            toastMessage = `${addedCount}个课件已添加`;
          } else if (duplicateCount > 0) {
            toastMessage = `${duplicateCount}个课件重复已过滤`;
          }
        }

        // 如果有提示信息，则显示
        if (toastMessage) {
          // 假设你有一个通用的消息提示方法，比如 this.$message.success 或 this.msgSuccess
          // 请根据你项目中实际的消息提示组件进行调整
          self.msgSuccess(toastMessage);
        }

        this.statisticalCalculation();
        this.$refs.drawer.closeDrawer();
      },
      statisticalCalculation(){
        let self = this;
        let numA = 0;
        let numB = 0;
        let numC = 0;
        let numD = 0;
        for(let i=0;i<self.dataList.length;i++){
          let data2 = 0;
          let data3 = 0;
          let data4 = 0;
          numA++
          for(let o=0;o<self.dataList[i].minList.length;o++){
            data2++
            data3 = self.addAndFormat(data3,self.dataList[i].minList[o].minData4)
            data4 = self.addAndFormat(data4,self.dataList[i].minList[o].minData5)
            numB++
            numC = self.addAndFormat(numC,self.dataList[i].minList[o].minData4)
            numD = self.addAndFormat(numD,self.dataList[i].minList[o].minData5)
          }
          self.dataList[i].data2 = data2;
          self.dataList[i].data3 = data3;
          self.dataList[i].data4 = data4;
        }
        this.$set(this,'num1',numA);
        this.$set(this,'num2',numB);
        this.$set(this,'num3',numC);
        this.$set(this,'num4',numD);
      },
      //添加大项
      addBigItem(){
        this.$set(this,'drawerItemPropsData',{
          knowledgePointId:null,
          checkIndex:null,
        });
        this.$set(this,'drawer',true);
      },
      //添加子项
      addMinItem(item,index){
        this.$set(this,'drawerItemPropsData',{
          knowledgePointId:item.knowledgePointId,
          checkIndex:index,
        });
        this.$set(this,'drawer',true);
      },
      //展开收起
      showButton(index){
        this.$set(this.dataList[index],'showType',!this.dataList[index].showType);
      },
      //大项删除
      delBigItem(index){
        let self = this;
        let text = self.dataList[index].data1;
        this.$confirm('确认删除 '+text+' ?', "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
        }).then(() => {
          self.dataList.splice(index,1);
          self.statisticalCalculation();
        }).catch(() => {});
      },
      //小项删除
      delItem(index,minIndex){
        let self = this;
        let text = self.dataList[index].data1+' 下的 '+self.dataList[index].minList[minIndex].minData1;
        this.$confirm('确认删除 '+text+' 课件?', "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
        }).then(() => {
          self.dataList[index].minList.splice(minIndex,1);
          self.statisticalCalculation();
        }).catch(() => {});
      },
      // ========== 大项拖拽逻辑 ==========
      onBigDragStart(e, index) {
        if(this.showType){
         return
        }
        this.dragInfo = { type: 'big', bigIndex: index, smallIndex: null };
        //拖拽优化相关
        const rowEl = e.target.closest('.for-max-box');
        if (rowEl) {
          rowEl.classList.add('dragging');
          e.dataTransfer.setDragImage(rowEl, 1148, 18);
        }
        // 给拖拽中的元素加个样式
        // e.target.classList.add('dragging');
      },
      onBigDragOver(e, index) {
        if(this.showType){
          return
        }
        // 只有当拖拽的是大项时才允许放置
        if (this.dragInfo.type === 'big') {
          e.currentTarget.classList.add('drag-over');
        }
      },
      onBigDrop(e, targetIndex) {
        if(this.showType){
          return
        }
        if (this.dragInfo.type !== 'big') return;
        const sourceIndex = this.dragInfo.bigIndex;
        if (sourceIndex === targetIndex) return;

        // 核心：交换数组元素
        const movedItem = this.dataList.splice(sourceIndex, 1)[0];
        this.dataList.splice(targetIndex, 0, movedItem);
      },

      // ========== 小项拖拽逻辑 ==========
      onSmallDragStart(e, bigIndex, smallIndex) {
        if(this.showType){
          return
        }
        this.dragInfo = { type: 'small', bigIndex: bigIndex, smallIndex: smallIndex };
        //拖拽优化相关
        const rowEl = e.target.closest('.for-text-box');
        if (rowEl) {
          rowEl.classList.add('dragging');
          e.dataTransfer.setDragImage(rowEl, 1148, 18);
        }
        // e.target.classList.add('dragging');
        // 阻止事件冒泡，防止触发大项的拖拽
        e.stopPropagation();
      },
      onSmallDragOver(e, smallIndex) {
        if(this.showType){
          return
        }
        // 只有当拖拽的是小项，且属于同一个大项时才允许放置
        if (this.dragInfo.type === 'small' && this.dragInfo.bigIndex === this.getCurrentBigIndex(e)) {
          e.currentTarget.classList.add('drag-over');
        }
      },
      onSmallDrop(e, targetBigIndex, targetSmallIndex) {
        if(this.showType){
          return
        }
        if (this.dragInfo.type !== 'small') return;
        // 确保只能在同一个大项内拖拽
        if (this.dragInfo.bigIndex !== targetBigIndex) return;

        const sourceSmallIndex = this.dragInfo.smallIndex;
        if (sourceSmallIndex === targetSmallIndex) return;

        const targetList = this.dataList[targetBigIndex].minList;
        const movedItem = targetList.splice(sourceSmallIndex, 1)[0];
        targetList.splice(targetSmallIndex, 0, movedItem);
      },

      // 拖拽结束，清理样式
      onDragEndBig(e) {
        //拖拽优化相关
        const rowEl = e.target.closest('.for-max-box');
        if (rowEl) {
          rowEl.classList.remove('dragging');
        }
        // e.target.classList.remove('dragging');
        document.querySelectorAll('.drag-over').forEach(el => el.classList.remove('drag-over'));
        this.dragInfo = { type: null, bigIndex: null, smallIndex: null };
      },
      // 拖拽结束，清理样式
      onDragEnd(e) {
        //拖拽优化相关
        const rowEl = e.target.closest('.for-text-box');
        if (rowEl) {
          rowEl.classList.remove('dragging');
        }
        // e.target.classList.remove('dragging');
        document.querySelectorAll('.drag-over').forEach(el => el.classList.remove('drag-over'));
        this.dragInfo = { type: null, bigIndex: null, smallIndex: null };
      },

      // 辅助方法：获取当前鼠标悬停的大项索引
      getCurrentBigIndex(e) {
        const minBox = e.currentTarget.closest('.for-max-box');
        return Array.from(this.$el.querySelectorAll('.for-max-box')).indexOf(minBox);
      },
      //检查数据
      checkTheData(){
        let self = this;
        if(!this.dataList[0]){
          this.msgError('请添加课件')
          return
        }
        for (let i=0;i<self.dataList.length;i++) {
          if(!self.dataList[i].minList[0]){
            this.msgError(self.dataList[i].data1+' 未添加课件')
            return
          }
        }
        this.$parent.pageDataB();
      },
      addAndFormat(val1, val2) {
        const num1 = parseFloat(val1) || 0;
        const num2 = parseFloat(val2) || 0;
        return parseFloat((num1 + num2).toFixed(1));
      },
    },
  }
</script>

<style scoped lang="scss">
  .courseManagement-studyCourses{
    flex:1;
    display: flex;
    flex-direction: column;
    padding:20px;
    overflow: hidden;
    .top-button-box{
      height:80px;
      display: flex;
      border-bottom:1px solid #dedede;
      p{
        height:40px;
      }
      p:nth-child(1){
        cursor: pointer;
        background-color: #0183FB;
        color:#fff;
        line-height: 40px;
        padding:0 20px;
        font-size:16px;
        border-radius:4px;
        margin:20px;
      }
      p:nth-child(2){
        background-color: #D9EDFE;
        color:#333;
        font-size:14px;
        line-height: 40px;
        padding:0 20px;
        border-radius:4px;
        margin:20px;
      }
    }
    .content-box{
      flex:1;
      display: flex;
      flex-direction: column;
      padding:20px;
      .for-max-box{
        margin-bottom:20px;
        .max-big-name-box{
          display: flex;
          p{
            line-height:40px;
          }
          p:nth-child(1){
            margin-right:20px;
            cursor: pointer;
            height:40px;
            width:60px;
            line-height:36px;
            font-size:30px;
            text-align: center;
            border-radius: 4px;
            border:1px solid #999;
            color:#333;
            background-color: #dedede;
          }
          p:nth-child(2){
            padding:0 15px;
            font-size:14px;
            border-radius: 4px;
            border:1px solid #999;
            width: 500px;
          }
          p:nth-child(3){
            font-size:14px;
            width: 448px;
            margin:0 20px;
            color:#0183fa;
          }
          p:nth-child(4){
            cursor: pointer;
            color:#D81E06;
            font-size:24px;
            width:40px;
            height:40px;
            text-align: center;
            margin-right:20px;
          }
          p:nth-child(5){
            cursor: pointer;
            color:#999;
            font-size:24px;
            width:40px;
            height:40px;
            text-align: center;
            margin-right:20px;
          }
          p:nth-child(6){
            cursor: pointer;
            color:#0183fa;
            font-size:24px;
            width:40px;
            height:40px;
            text-align: center;
            margin-right:20px;
          }
        }
        .max-big-title-box{
          margin:20px 0;
          .big-title-box{
            display: flex;
            background-color: #dedede;
            border-bottom:1px solid #999;
            padding:0 20px;
            p{
              font-size:14px;
              line-height:40px;
              height:40px;
            }
            p:nth-child(1){
              width:400px;
              text-align: left;
            }
            p:nth-child(2){
              width:200px;
              text-align: center;
            }
            p:nth-child(3){
              width:140px;
              text-align: center;
            }
            p:nth-child(4){
              width:140px;
              text-align: center;
            }
            p:nth-child(5){
              width:140px;
              text-align: center;
            }
            p:nth-child(6){
              flex:1;
              text-align: center;
            }
          }
          .for-text-box{
            border-bottom:1px solid #dedede;
            display: flex;
            padding:0 20px;
            p{
              font-size:14px;
              line-height:40px;
              height:40px;
            }
            p:nth-child(1){
              width:400px;
              text-align: left;
            }
            p:nth-child(2){
              width:200px;
              text-align: center;
            }
            p:nth-child(3){
              width:140px;
              text-align: center;
            }
            p:nth-child(4){
              width:140px;
              text-align: center;
            }
            p:nth-child(5){
              width:140px;
              text-align: center;
            }
            p:nth-child(6){
              margin-left:28px;
              cursor: pointer;
              color:#D81E06;
              font-size:24px;
              width:40px;
              height:40px;
              text-align: center;
              margin-right:20px;
            }
            p:nth-child(7){
              cursor: pointer;
              color:#999;
              font-size:24px;
              width:40px;
              height:40px;
              text-align: center;
              margin-right:20px;
            }
            p:nth-child(8){
              cursor: pointer;
              color:#0183fa;
              font-size:24px;
              width:40px;
              height:40px;
              text-align: center;
              margin-right:20px;
            }
          }
        }
      }
    }
    .drag-handle {
       cursor: move;
       user-select: none; /* 防止拖拽时选中文字 */
     }
    .dragging {
      opacity: 0.5;
      background-color: #f5f7fa;
    }
    .drag-over {
      /*border-top: 2px solid #409EFF !important; !* 放置位置的指示线 *!*/
    }
  }
</style>
<style lang="scss">
.courseManagement-drawer{
  .el-drawer__body{
    padding:0;
  }
  .el-drawer__header{
    margin:0;
  }
}
</style>
