<template>
    <!-- <h2 class="contentTitle" v-if="classDown">课程列表</h2> -->
    <div class="downloadCourse">
      <span class="grandTitle">年级：</span>
      <el-button :class="selectGrand == '三年级' ? 'el_button_active' : ''" @click="clickGrand('三年级')">三年级</el-button>
      <el-button :class="selectGrand == '四年级' ? 'el_button_active' : ''" @click="clickGrand('四年级')">四年级</el-button>
      <el-button :class="selectGrand == '五年级' ? 'el_button_active' : ''" @click="clickGrand('五年级')">五年级</el-button>
      <el-button :class="selectGrand == '六年级' ? 'el_button_active' : ''" @click="clickGrand('六年级')">六年级</el-button>
      <el-button :class="selectGrand == '七年级' ? 'el_button_active' : ''" @click="clickGrand('七年级')">七年级</el-button>
      <el-button :class="selectGrand == '八年级' ? 'el_button_active' : ''" @click="clickGrand('八年级')">八年级</el-button>
    </div>
    <div class="downloadCourse">
      <span class="grandTitle">{{ value }}</span>
      <div v-if="currentData && currentData.xia.length > 0">
        <el-row :gutter="20">
          <el-col :span="6" v-for="item in currentData.xia" :key="item.title">
            <div class="grid-content ep-bg-purple">
              <img :src="getImageUrl(item.url)" alt="">
              <div class="course_content">
                <div class="div_title">
                  <span>下册</span>
                  {{ item.title }}
                  <!-- v-if="isupdateCourse" -->
                  <el-popover placement="bottom" :width="210" trigger="click" show-after="500"
                    @hide="checked1 = false">
                    <template #reference>
                      <img :src="DownloadImg" alt="" @click="getDate(item.dataId)">
                    </template>
                    <div>
                      <div>
                        <span>资源列表（{{ item.dataList.length }}）</span>
                        <el-checkbox style="position: relative;top: 0;left: 35px;height: 30px;" v-model="checked1"
                          label="全选" size="large" @click="checkedAll(item.dataId)" />
                      </div>
                      <div v-if="item.dataList.length > 0">
                        <div class="div_hover" v-for="dataitem in item.dataList" :key="dataitem.dataId">
                          <span style="display: inline-block;width: 130px;" :title="dataitem.name">{{
                            dataitem.name.length > 10 ?
                              dataitem.name.substring(0, 8) + '...' : dataitem.name }}</span>
                          <a :href="dataitem.url" :download="dataitem.name" v-if="!checked1" class="el_popover_a"
                            style="position: relative;left: 20px;top: 5px;">
                            <img :src="DownloadImg" alt="">
                          </a>
                          <el-checkbox v-if="checked1" v-model="dataitem.checked" label="全选" size="large" />
                        </div>
                        <el-button style="margin-top: 10px;" v-if="checked1"
                          @click="DownloadProcessing()">批量下载</el-button>
                      </div>
                      <div v-else>
                        暂无数据
                      </div>
                    </div>
                  </el-popover>
                </div>
              </div>
              <!-- <div class="class_button" v-if="isupdateCourse && classDown">
                <el-button style="width: 30%;background: rgba(240, 242, 245, 1);color: rgba(0, 0, 0, 0.6);"
                  @click="ReductionCourse(item.id)">还原</el-button>
                <el-button style="width: 30%;background: #fff" @click="updateCourse(item.id)">修改</el-button>
                <el-button style="width: 30%;" class="el_button_active" @click="openCourseDetail(item.id)">查看</el-button>
              </div> -->
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :before-close="handleClose" width=500>
      <template #header>
        <div class="dialog-header img_text_middle">
          <img :src="WarningImg" alt="">
          <span class="warning_text">操作警告</span>
        </div>
      </template>
      <span>启用还原功能将重置当前修改，并将课程内容恢复至标准版本。请确认是否继续执行相关操作。</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="updateReduction()">
            确认修改
          </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  <script setup>
  import { ref, onMounted, watchEffect,defineProps } from 'vue';
  import { userCurrentRole, userInfoStore } from '../../stores/counter'
  import JSZip from 'jszip';
  import { saveAs } from 'file-saver';
  import DownloadImg from '@/assets/img/download.png'
  import PDFImg from '@/assets/img/PDF.png'
  import WarningImg from '@/assets/icon/icon.png'
  import san1 from '../../assets/img/三下1.png'
  import san2 from '@/assets/img/三下2-1.png'
  import san3 from '@/assets/img/三下3-1.png'
  import san4 from '@/assets/img/三下4-1.png'
  import si1 from '@/assets/img/四下1.png'
  import si2 from '@/assets/img/四下2.png'
  import si3 from '@/assets/img/四下3-1.png'
  import si4 from '@/assets/img/四下4-1.png'
  import wu1 from '@/assets/img/五下1-1.png'
  import wu2 from '@/assets/img/五下2-1.png'
  import wu3 from '@/assets/img/五下3-1.png'
  import wu4 from '@/assets/img/五下4-1.png'
  import liu1 from '@/assets/img/六下1.png'
  import liu2 from '@/assets/img/六下2.png'
  import liu3 from '@/assets/img/六下3-1.png'
  import liu4 from '@/assets/img/六下4-1.png'
  import qi1 from '@/assets/img/七下1-1.png'
  import qi2 from '@/assets/img/七下2-1.png'
  import qi3 from '@/assets/img/七下3-1.png'
  import qi4 from '@/assets/img/七下4-1.png'
  import ba1 from '@/assets/img/八下1.png'
  import ba2 from '@/assets/img/八下2.png'
  import ba3 from '@/assets/img/八下3-1.png'
  import ba4 from '@/assets/img/八下4-1.png'
  import axios from 'axios';
  
  const props = defineProps({
    classDown:{
      type:Boolean,
      default:true
    }
  })
  
  const user = userInfoStore()
  const CurrentRole = userCurrentRole()
  const selectGrand = ref('三年级')
  const isupdateCourse = ref(false)
  const currentData = ref({
    shang: [
    ],
    xia: [
      {
        id: "a1d5bf2b-f4a1-11ee-b534-005056b86db5",
        title: "初识人工智能",
        url: san1,
        dataId: "8047e404-efd0-11ee-b534-005056b86db5",
        dataList: [
        ]
      }, {
        id: "0b7610fa-f4a3-11ee-b534-005056b86db5",
        title: "机器的眼睛",
        url: san2,
        dataId: "9ccc8631-efd0-11ee-b534-005056b86db5",
        dataList: []
      }, {
        id: "058840d5-f4a4-11ee-b534-005056b86db5",
        title: "机器的耳朵",
        url: san3,
        dataId: "f4887494-ee78-11ee-b534-005056b86db5",
        dataList: []
      }, {
        id: "3b877b4c-fa1a-11ee-b534-005056b86db5",
        title: "多功能相机",
        url: san4,
        dataId: "c89e5214-ee79-11ee-b534-005056b86db5",
        dataList: []
      }
    ]
  })
  const dialogVisible = ref(false)
  const updateReductionId = ref("")
  const checked1 = ref(false)
  const visible = ref(false)
  
  const courseData = {
    "三年级": {
      shang: [
      ],
      xia: [
      {
        id: "a1d5bf2b-f4a1-11ee-b534-005056b86db5",
        title: "初识人工智能",
        url: san1,
        dataId: "8047e404-efd0-11ee-b534-005056b86db5",
        dataList: [
        ]
      }, {
        id: "0b7610fa-f4a3-11ee-b534-005056b86db5",
        title: "机器的眼睛",
        url: san2,
        dataId: "9ccc8631-efd0-11ee-b534-005056b86db5",
        dataList: []
      }, {
        id: "058840d5-f4a4-11ee-b534-005056b86db5",
        title: "机器的耳朵",
        url: san3,
        dataId: "f4887494-ee78-11ee-b534-005056b86db5",
        dataList: []
      }, {
        id: "3b877b4c-fa1a-11ee-b534-005056b86db5",
        title: "多功能相机",
        url: san4,
        dataId: "c89e5214-ee79-11ee-b534-005056b86db5",
        dataList: []
      }
      ]
    },
    "四年级": {
      shang: [
      ],
      xia: [
        {
          id: "442c41c8-f3ec-11ee-b534-005056b86db5",
          title: "人工智能进阶",
          url: si1,
          dataId: "421fda95-f327-11ee-b534-005056b86db5",
          dataList: []
        }, {
          id: "b01fae58-f3ec-11ee-b534-005056b86db5",
          title: "情绪识别",
          url: si2,
          dataId: "29120fad-ed73-11ee-b534-005056b86db5",
          dataList: []
        }, {
          id: "2c32abc1-f3ee-11ee-b534-005056b86db5",
          title: "情绪小怪兽",
          url: si3,
          dataId: "203adf26-f02a-11ee-b534-005056b86db4",
          dataList: []
        }, {
          id: "9f6d6f69-f3f0-11ee-b534-005056b86db5",
          title: "灯光交互",
          url: si4,
          dataId: "66e88b33-f02a-11ee-b534-005056b86db4",
          dataList: []
        }
      ]
    },
    "五年级": {
      shang: [
      ],
      xia: [
        {
          id: "61dde5e8-f1a9-11ee-b534-005056b86db5",
          title: "游戏与生活的概率",
          url: wu1,
          dataId: "60f4c4ef-ee7a-11ee-b534-005056b86db5",
          dataList: []
        }, {
          id: "81d3e3ad-f1ac-11ee-b534-005056b86db5",
          title: "手势识别",
          url: wu2,
          dataId: "1bfaf06d-ee7b-11ee-b534-005056b86db5",
          dataList: []
        }, {
          id: "66bc069a-f1ae-11ee-b534-005056b86db5",
          title: "猜拳机器人",
          url: wu3,
          dataId: "00cbfa57-ee7c-11ee-b534-005056b86db5",
          dataList: []
        }, {
          id: "02c626b9-f65c-11ee-b534-005056b86db5",
          title: "猜拳大对战",
          url: wu4,
          dataId: "a5056071-f32a-11ee-b534-005056b86db5",
          dataList: []
        },
      ]
    },
    "六年级": {
      shang: [
      ],
      xia: [
        {
          id: "12734ea5-f58a-11ee-b534-005056b86db5",
          title: "人脸检测知多少",
          url: liu1,
          dataId: "3bbb9a9d-02d6-11ef-b534-005056b86db5",
          dataList: []
        }, {
          id: "63494f9d-f58d-11ee-b534-005056b86db5",
          title: "人脸检测全流程",
          url: liu2,
          dataId: "ccff27f7-02d5-11ef-b534-005056b86db5",
          dataList: []
        }, {
          id: "7187af69-f590-11ee-b534-005056b86db5",
          title: "人脸检测功能实现",
          url: liu3,
          dataId: "d8ec4180-02d3-11ef-b534-005056b86db5",
          dataList: []
        }, {
          id: "29ebe57f-f7c7-11ee-b534-005056b86db5",
          title: "人脸追踪向日葵功能实现",
          url: liu4,
          dataId: "0001b587-02d2-11ef-b534-005056b86db5",
          dataList: []
        },
      ]
    },
    "七年级": {
      shang: [
      ],
      xia: [
        {
          id: "16ed7a65-f186-11ee-b534-005056b86db5",
          title: "机器学习",
          url: qi1,
          dataId: "c39dcb26-f163-11ee-b534-005056b86db5",
          dataList: []
        }, {
          id: "6db889c2-f187-11ee-b534-005056b86db5",
          title: "萌宠生活（一）",
          url: qi2,
          dataId: "d8ef862a-f329-11ee-b534-005056b86db5",
          dataList: []
        }, {
          id: "328cb885-f188-11ee-b534-005056b86db5",
          title: "萌宠生活（二）",
          url: qi3,
          dataId: "a6b99c8f-efd1-11ee-b534-005056b86db5",
          dataList: []
        }, {
          id: "a03b3cd5-facc-11ee-b534-005056b86db5",
          title: "萌宠生活（三）",
          url: qi4,
          dataId: "137e2644-efd1-11ee-b534-005056b86db5",
          dataList: []
        }
      ]
    },
    "八年级": {
      shang: [
      ],
      xia: [
        {
          id: "ecd08b4f-f1b1-11ee-b534-005056b86db5",
          title: "探秘人工智能",
          url: ba1,
          dataId: "e92603e5-efd1-11ee-b534-005056b86db5",
          dataList: []
        }, {
          id: "93069885-f1b4-11ee-b534-005056b86db5",
          title: "无所不在的人工智能",
          url: ba2,
          dataId: "9a0959c8-f02a-11ee-b534-005056b86db4",
          dataList: []
        }, {
          id: "ea32c84d-f3e4-11ee-b534-005056b86db5",
          title: "机器翻译鸟（上）",
          url: ba3,
          dataId: "d99be3d6-f02a-11ee-b534-005056b86db5",
          dataList: []
        }, {
          id: "8012207b-f64c-11ee-b534-005056b86db5",
          title: "机器翻译鸟（下）",
          url: ba4,
          dataId: "1428638e-f02b-11ee-b534-005056b86db5",
          dataList: []
        },
      ]
    }
  }
  onMounted(() => {
    currentData.value = courseData["三年级"]
  })
  const clickGrand = val => {
    selectGrand.value = val
    currentData.value = courseData[val]
  
  }
  const getImageUrl = (url) => {
    return new URL(url, import.meta.url).href
  }
  
  const openCourseDetail = (id) => {
    console.log(user.user)
    // 会返回复制得课程
    top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/getcopyCourseSz", [id], function (res) {
      console.log(res)
      if (res.value[0].length > 0) {
        // let isSave = res.value[0].filter(x => {
        //   return x.courseId == id
        // })
        //这个是打开指定的课程接口
        top.U.MD.D.I.openInApplication("studyDetail", res.value[0][0].courseId, 2, user.user.type);
      } else {
        updateCourseId(id, "studyDetail")
      }
    }, [], { "type": "POST", "withCredentials": true });
  
  }
  const updateCourse = id => {
    // 会返回courseId和state 两个参数  然后打开
    top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/getcopyCourseSz", [id], function (res) {
      console.log(res)
      if (res.value[0].length > 0) {
        // let isSave = res.value[0].filter(x => {
        //   return x.courseId == id
        // })
        top.U.MD.D.I.openInApplication('openCourseNewUpdate', res.value[0][0].courseId); //这个是打开指定的课程接口
      } else {
        updateCourseId(id, "openCourseNewUpdate")
      }
    }, [], { "type": "POST", "withCredentials": true });
  }
  
  const updateCourseId = (id, type) => {
    top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/copyCourseSz", [id, user.user.userid], function (res) {
      console.log(res)
      if (res.value[0][0].courseId != "") {
        if (type == "openCourseNewUpdate") {
          top.U.MD.D.I.openInApplication("openCourseNewUpdate", res.value[0][0].courseId)
        } else {
          top.U.MD.D.I.openInApplication("studyDetail", res.value[0][0].courseId, 3, user.user.type);
        }
      }
    }, [], { "type": "POST", "withCredentials": true });
  }
  
  const ReductionCourse = id => {
    // updateReductionId.value = id
    top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/getcopyCourseSz", [id], function (res) {
      console.log(res)
      if (res.value[0].length > 0) {
        // let isSave = res.value[0].filter(x => {
        //   return x.courseId == id
        // })
        dialogVisible.value = true
        updateReductionId.value = res.value[0][0].courseId
      } else {
        ElMessage({
          message: '该课程就是最初课程，不能还原',
          type: 'warning',
        })
      }
    }, [], { "type": "POST", "withCredentials": true });
  }
  
  const updateReduction = () => {
    top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/revertCourseSz", [updateReductionId.value], function (res) {
      console.log(res, "还原")
      dialogVisible.value = false
    }, [], { "type": "POST", "withCredentials": true });
  }
  
  const getDate = async (id) => {
    // currentData
    let dataList = []
    let m = currentData.value
    await top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/selectCourseDetailSz", [id], function (res) {
      console.log(res)
      if (res.value[0].length > 0 && res.value[0][0].chapters.length > 0) {
        let datachapters = JSON.parse(res.value[0][0].chapters)
        for (let i = 0; i < datachapters.length; i++) {
          let data = datachapters[i]
          for (let j = 0; j < data.chapterInfo.length; j++) {
            let dataChapterInfo = data.chapterInfo[j]
            for (let k = 0; k < dataChapterInfo.taskJson.length; k++) {
              let DatahapterData = dataChapterInfo.taskJson[k]
              for (let l = 0; l < DatahapterData.chapterData.length; l++) {
                let obj = DatahapterData.chapterData[l]
                // let obj = chapterDatas
                obj.checked = false
                dataList.push(obj)
              }
            }
          }
        }
      }
    }, [], { "type": "POST", "withCredentials": true });
  
    await m.xia.map(x => {
      if (x.dataId == id) {
        x.dataList = dataList
      }
      return x
    })
    currentData.value = m
    // console.log("currentData", currentData)
  }
  
  const checkedAll = (id) => {
    let data = currentData.value
    data.xia.map(x => {
      if (x.dataId == id) {
        x.dataList.map(y => {
          y.checked = !checked1.value
        })
      }
      return x
    })
    console.log(id, checked1.value)
    console.log(data)
    currentData.value = data
    // checked1.value = true
  }
  
  const download = (url, fileName) => {
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }
  
  const DownloadProcessing = async () => {
    let data = currentData.value
    let urls = []
    await data.xia.map(x => {
      console.log(x)
      x.dataList.length > 0 && x.dataList.map(m => {
        if (m.checked) {
          urls.push(m)
        }
        return m
      })
      return x
    })
    console.log("urls", urls)
    for (let i = 0; i < urls.length; i++) {
      fetch(urls[i].url)
        .then(response => response.blob())  // 获取文件数据流
        .then(blob => {
          const url = window.URL.createObjectURL(blob);  // 生成文件在浏览器中的链接
          const a = document.createElement('a');
          a.href = url;
          a.download = urls[i].name;  // 文件名
          a.style.display = 'none';
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);  // 清除文件链接
        })
        .catch(console.error);
    }
  }
  // 获取课程下载资料
  // top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/selectCourseDetailSz", ['课程id'], function (res) {}, [], { "type": "POST", "withCredentials": true });
  
  watchEffect(() => {
    if (JSON.stringify(user.user) != "{}") {
      if (CurrentRole.currentRole == "edupersonnel" || CurrentRole.currentRole == "areaAdministrator" || CurrentRole.currentRole == "userAdministrator" || CurrentRole.currentRole == "securityAuditor" || CurrentRole.currentRole == "schoolAdministrator" || CurrentRole.currentRole == "schoolSecurityAuditor" || CurrentRole.currentRole == "teacher" || user.user.type != 2) {
        isupdateCourse.value = true
      }
    }
  })
  </script>
  <style lang="scss" scoped>
  .downloadCourse {
    margin-top: 10px;
  
    .grid-content {
      border-radius: 4px;
      min-height: 36px;
      background: #fff;
      padding: 12px;
  
      // height: 300px;
      img {
        width: 100%;
        border-radius: 5px;
      }
  
      .course_content {
        .div_title {
          margin-top: 10px;
  
          span {
            // display: inline-block;
            padding: 2px 8px;
            background: rgba(224, 234, 251, 1);
            border-radius: 5px;
            font-size: 12px;
            color: rgba(54, 129, 252, 1);
          }
  
          img {
            width: 28px;
            cursor: pointer;
            float: right;
          }
        }
      }
    }
  
    .Screening {
      font-size: 20px;
      font-weight: 400;
      line-height: 28px;
      letter-spacing: 0em;
      text-align: center;
      color: rgba(0, 0, 0, 0.9);
    }
  
    .grandTitle {
      font-size: 20px;
      font-weight: 400;
      line-height: 28px;
      letter-spacing: 0em;
      text-align: center;
  
    }
  
    .el-button {
      // background:  rgba(54, 129, 252, 1);
      color: rgba(54, 129, 252, 1);
    }
  
    .el_button_active {
      background: rgba(54, 129, 252, 1);
      color: #fff;
    }
  
    .class_button {
      margin-top: 15px;
      display: flex;
      justify-content: space-between;
    }
  }
  
  .el-row {
    margin-top: 20px;
    margin-bottom: 20px;
  }
  
  .el-row:last-child {
    margin-bottom: 0;
  }
  
  .el-col {
    border-radius: 4px;
  }
  
  .warning_text {
    font-weight: bold;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.9);
    margin-left: 8px;
  }
  
  .div_hover {
    // padding: 8px 0 10px;
    height: 35px;
    line-height: 35px;
  }
  
  .div_hover:hover {
    background: rgb(240, 242, 245);
  }
  
  .el_popover_a {
    display: none;
  }
  
  .div_hover:hover .el_popover_a {
    display: inline-block;
  }
  </style>