<template>
  <h2 class="contentTitle" v-if="classDown">
    <div class="Levelone">
      {{ lang.lang == 'hk' ? lang.ssAiTeachRes : lang.ssCourseList }}
    </div>
  </h2>
  <div class="grandTitle2" v-if="lang.lang != 'hk'">{{ lang.ssAiGeneral }}</div>
  <div class="course_select" v-if="lang.lang != 'hk'">
    <span class="grandTitle">{{ lang.ssCourseType }}</span>
    <el-button v-for="item in yearList" 
    :key="item.value" :class="activeyear == item.value ? 'el_button_active' : ''" 
    @click="clickYear(item.value)">{{ item.label }}</el-button>
    <!-- <el-button :class="!courseTypeShow ? 'el_button_active' : ''" @click="SwitchCourseType(false)">AI通识课2024版</el-button> -->
  </div>
  <div class="course_select">
    <span class="grandTitle">{{ lang.ssGrade }}</span>
    <el-button 
      v-for="item in classList" :key="item.value" 
      :class="activegrade == item.value ? 'el_button_active' : ''" 
      @click="clickGrand(item.value)">
      {{ item.label }}
    </el-button>
  </div>
  <div class="course_select">
    <template v-if="lang.lang != 'hk'">
      <span class="grandTitle">{{ lang.ssTerm }}</span>
      <el-button :class="activeterm == 0 ? 'el_button_active' : ''" @click="activeterm = 0,getCourseList()">{{ lang.ssTermUp }}</el-button>
      <el-button :class="activeterm == 1 ? 'el_button_active' : ''"
        @click="activeterm = 1,getCourseList()">{{ lang.ssTermDown }}</el-button>
    </template>
   


      <!-- 课程上下册区域 -->
    <div v-loading="courseLoading">
      <el-row :gutter="20" v-if="activeCurrentData.length > 0">
        <el-col :span="6" v-for="item in activeCurrentData" :key="item.id" style="margin-top: 10px;">
          <div class="grid-content ep-bg-purple">
            <img :src="getImageUrl(item.json.url)" alt="">
            <div class="course_content">
              <div class="div_title">
                <span v-if="lang.lang != 'hk'">{{ lang.ssTermUp }}</span>
                  <el-tooltip class="item" effect="dark" :content="item.json.title" placement="top">
                    <div class="div_title_text">{{ item.json.title }}</div>
                  </el-tooltip>
                
                <!-- v-if="isupdateCourse" -->
                <!-- v-if="isupdateCourse && item.courseType == '1'" -->
                <el-popover v-if="isupdateCourse" placement="bottom" :width="210"
                  trigger="click" :show-after="500" @hide="checked1 = false">
                  <template #reference>
                    <img :src="DownloadImg" v-if="item.json.courseType == '2'" alt="">
                    <img :src="DownloadImg" v-else alt="" @click="getDate(item.json.dataId)">
                  </template>
                  <div>
                    <div>
                      <span>{{ lang.ssResList.replace(/\*/g, item.json.dataList.length) }}</span>
                      <el-checkbox style="position: relative;top: 0;left: 35px;height: 30px;" v-model="checked1"
                        :label="lang.ssSelectAll" size="large" @click="checkedAll(item.json.dataId)" />
                    </div>
                    <div v-if="item.json.dataList.length > 0">
                      <div class="div_hover" v-for="dataitem in item.json.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>
                        <span v-if="!checked1" class="el_popover_a" style="position: relative;left: 20px;top: 5px;"
                          @click="downloadOne(dataitem.url, dataitem.name)">
                          <img :src="DownloadImg" alt="">
                        </span>
                        <el-checkbox v-if="checked1" v-model="dataitem.checked" :label="lang.ssSelectAll" size="large" />
                      </div>
                      <el-button style="margin-top: 10px;" v-if="checked1"
                        @click="DownloadProcessing()">{{ lang.ssBatchDown }}</el-button>
                    </div>
                    <div v-else>
                      {{ lang.ssNoData }}
                    </div>
                  </div>
                </el-popover>
              </div>
            </div>
            <div class="class_button" v-if="isupdateCourse">
              <!-- <el-popover v-if="item.courseType == '1'" placement="bottom" trigger="hover">
                <template #reference> -->
                <el-button
                @click="getCourseid(item.json.id)"
                  style="width: 50%;background: rgba(255, 255, 245, 1);color: rgba(0, 0, 0, 0.6);">
                  {{ lang.ssPrep }}</el-button>
                <!-- </template>
                <ul class="beike">
                  <li @click="openCourseDetail(item.id)">查看</li>
                  <li @click="updateCourse(item.id, item)">修改</li>
                  <li @click="ReductionCourse(item.id)">还原</li>
                </ul>
              </el-popover> -->
              <el-button style="width: 50%;" class="el_button_active"
                @click="openCourseDetail(item.json.id, item.json)">{{ lang.ssInClass }}</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
      <div v-else>
        <el-empty :description="lang.ssNoCrsGrdTip" />
      </div>
    </div>
    <!-- <div v-if="currentData && currentData.xia.length > 0 && !volumes">
      <el-row :gutter="20">
        <el-col :span="6" v-for="item in currentData.xia" :key="item.title" style="margin-top: 10px;">
          <div class="grid-content ep-bg-purple">
            <img :src="getImageUrl(item.url)" alt="">
            <div class="course_content">
              <div class="div_title" style="">
                <span>下册</span>
                 <el-tooltip class="item" effect="dark" :content="item.title" placement="top">
                  <div class="div_title_text">{{ item.title }}</div>
                </el-tooltip>

                <el-popover v-if="isupdateCourse" placement="bottom" :width="210"
                  trigger="click" :show-after="500" @hide="checked1 = false">
                  <template #reference>
                    <img :src="DownloadImg" v-if="item.courseType == '2'" alt="">
                    <img :src="DownloadImg" v-else 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>
                        <span v-if="!checked1" class="el_popover_a" style="position: relative;left: 20px;top: 5px;"
                          @click="downloadOne(dataitem.url, dataitem.name)">
                          <img :src="DownloadImg" alt="">
                        </span>
                        <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">
              <el-button
                @click="getCourseid(item.id)"
                  style="width: 50%;background: rgba(255, 255, 245, 1);color: rgba(0, 0, 0, 0.6);">
                  备课</el-button>
              <el-button style="width: 50%;" class="el_button_active"
                @click="openCourseDetail(item.id, item)">上课</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div> -->
  </div>
  <template v-if="false">
    <div style="margin-top: 20px;">
      <span class="grandTitle2" v-if="gotype.gotype == 'bjs'">人工智能竞赛课</span>
      <span class="grandTitle2" v-else>竞赛主题课程</span>
    </div>
    <div class="course_select">
      <span class="grandTitle">课程类型：</span>
      <el-button  @click="cutmod(0)" :class="[cutmodpage == 0 ? 'el_button_active' :'']">
        <span v-if="gotype.gotype == 'bjs'">智能体课程</span>
        <span v-else>智能体设计与应用课程</span>
      </el-button>
      <el-button @click="cutmod(1)" :class="[cutmodpage == 1 ? 'el_button_active' :'']">
        <span>创意智造课程</span>
      </el-button>
      <!-- <el-button :class="!courseTypeShow ? 'el_button_active' : ''" @click="SwitchCourseType(false)">AI通识课2024版</el-button> -->
    </div>
    <div class="course_select">
      <span class="grandTitle">模块：</span>
      <el-button :class="selectmod == '模块一' ? 'el_button_active' : ''" @click="clickmod('模块一')">模块一</el-button>
      <el-button v-if="cutmodpage == 0" :class="selectmod == '模块二' ? 'el_button_active' : ''" @click="clickmod('模块二')">模块二</el-button>
      <el-button v-if="cutmodpage == 0" :class="selectmod == '模块三' ? 'el_button_active' : ''" @click="clickmod('模块三')">模块三</el-button>
      <el-button v-if="gotype.gotype == 'bjs' && cutmodpage == 0" :class="selectmod == '模块四' ? 'el_button_active' : ''" @click="clickmod('模块四')">模块四</el-button>
    </div>
    <div class="course_select" v-if="gotype.gotype == 'bjs' && cutmodpage == 0">
      <div v-if="currentmodData && currentmodData.shang.length > 0">
        <el-row :gutter="20">
          <el-col :span="6" v-for="item in currentmodData.shang" :key="item.title" style="margin-top: 10px;">
            <div class="grid-content ep-bg-purple">
              <img :src="getImageUrl(item.url)" alt="">
              <div class="course_content">
                <div class="div_title">
                  <el-tooltip class="item" effect="dark" :content="item.title" placement="top">
                    <div class="div_title_text">{{ item.title }}</div>
                  </el-tooltip>
                </div>
              </div>
              <div class="class_button" v-if="isupdateCourse">
                <el-button :style="item.courseType == '1' ? 'width: 50%;' : 'width: 100%;'" class="el_button_active"
                  @click="openCourseDetail(item.id, item)">上课</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="course_select" v-if="cutmodpage == 1">
      <div v-if="currentAI6TwoData && currentAI6TwoData.shang.length > 0">
        <el-row :gutter="20">
          <el-col :span="6" v-for="item in currentAI6TwoData.shang" :key="item.title" style="margin-top: 10px;">
            <div class="grid-content ep-bg-purple">
              <img :src="getImageUrl(item.url)" alt="">
              <div class="course_content">
                <div class="div_title">
                  <el-tooltip class="item" effect="dark" :content="item.title" placement="top">
                    <div class="div_title_text">{{ item.title }}</div>
                  </el-tooltip>
                </div>
              </div>
              <div class="class_button" v-if="isupdateCourse">
                <el-button :style="item.courseType == '1' ? 'width: 50%;' : 'width: 100%;'" class="el_button_active"
                  @click="openCourseDetail(item.id, item)">上课</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="course_select" v-if="gotype.gotype != 'bjs' && cutmodpage == 0">
      <div v-if="currentAI6Data && currentAI6Data.shang.length > 0">
        <el-row :gutter="20">
          <el-col :span="6" v-for="item in currentAI6Data.shang" :key="item.title" style="margin-top: 10px;">
            <div class="grid-content ep-bg-purple">
              <img :src="getImageUrl(item.url)" alt="">
              <div class="course_content">
                <div class="div_title">
                  <el-tooltip class="item" effect="dark" :content="item.title" placement="top">
                    <div class="div_title_text">{{ item.title }}</div>
                  </el-tooltip>

                </div>
              </div>
              <div class="class_button" v-if="isupdateCourse">
                <el-button :style="item.courseType == '1' ? 'width: 50%;' : 'width: 100%;'" class="el_button_active"
                  @click="openCourseDetail(item.id, item)">上课</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </template>

  <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>

  <selectTeachingClassDialog 
  ref="DialogRef" />

</template>
<script setup>
import { ref, onMounted, watchEffect, inject } from 'vue';
import { userCurrentRole, userInfoStore, userCurrent,pageGotype } 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 courseDataJson from '@/assets/course.json'
import selectTeachingClassDialog from '../dialog/selectTeachingClassDialog.vue'
// import { Value } from 'sass';
// import { dataType } from 'element-plus/es/components/table-v2/src/common';
import axios from 'axios';

const lang = inject('lang')

const props = defineProps({
  classDown: {
    type: Boolean,
    default: true
  }
})
const volumes = ref(false)
const user = userInfoStore()
const CurrentRole = userCurrentRole()
const Current = userCurrent()
const selectGrand = ref(lang.ssGradeThree)
const selectmod = ref(lang.ssModuleOne)
const gotype = pageGotype()

const classList = ref(lang.lang != 'hk' ? [
  {value: 3, label: lang.ssGradeThree},
  {value: 4, label: lang.ssGradeFour},
  {value: 5, label: lang.ssGradeFive},
  {value: 6, label: lang.ssGradeSix},
  {value: 7, label: lang.ssGradeSeven},
  {value: 8, label: lang.ssGradeEight},
  {value: 9, label: lang.ssGradeNine}
] : [
  {value: 4, label: lang.ssGradeFour},
  {value: 5, label: lang.ssGradeFive},
  {value: 6, label: lang.ssGradeSix},
  {value: 7, label: lang.ssGradeSeven},
  {value: 8, label: lang.ssGradeEight},
  {value: 9, label: lang.ssGradeNine}
])

const activeyear = ref(2025)
const courseLoading = ref(false)
const yearList = ref([
  {value: 2025, label: 'AI通识课2025版'},
])

const clickYear = (val) => {
  activeyear.value = val
  getCourseList()
}

const isupdateCourse = ref(false)
const currentData = ref(courseDataJson.new.三年级)
const currentmodData = ref(courseDataJson.mod.模块一)
const currentAI6Data = ref(courseDataJson.AI6one.模块一)
const currentAI6TwoData = ref(courseDataJson.AI6Two.模块一)

const cutmodpage = ref('0')

const dialogVisible = ref(false)
const updateReductionId = ref("")
const checked1 = ref(false)
// const visible = ref(false)
const getUpdateCourseId = ref("")
const courseTypeShow = ref(true) // old 旧版 new 纲要
const setIntervalNum = ref(null)
const DialogRef = ref(null)
const courseData = ref(courseDataJson.new)
const modData = ref(courseDataJson.mod)
const AI6Data = ref(courseDataJson.AI6one)
const AI6TwoData = ref(courseDataJson.AI6Two)

const activegrade = ref(lang.lang != 'hk' ? '3' : '4')
const activeterm = ref('1')
const activeCurrentData = ref([])

onMounted(() => {
  currentData.value = courseData.value["三年级"]
  getTimeCourse(1, 1)
  getCourseList() // 获取课程列表
})

const getCourseList = () => {
  courseLoading.value = true
  let params = {
    ter: activeterm.value,
    gra: activegrade.value,
    ar: lang.lang,
    typ: gotype.gotype == 'bjs' ? 0 : 0,
    yea: activeyear.value
  }
  axios.get('https://pbl.cocorobo.cn/api/pbl/selectaisixCourse', { params })
  .then(res => {
    // console.log(res);
    let data = res.data[0]
    data.forEach(item => {
      item.json = JSON.parse(item.json)
    })
    activeCurrentData.value = data
    courseLoading.value = false
    console.log('activeCurrentData.value',activeCurrentData.value);
  })
  .catch(err => {
    console.error(err);
    courseLoading.value = false
  });
};
const clickGrand = val => {
  activegrade.value = val
  getCourseList()
  // console.log('courseData.value',courseData.value);
  
  // currentData.value = courseData.value[val]
}
const handleClose =(done)=>{
  done()
}
const cutmod = (val) => {
    cutmodpage.value = val
    clickmod(selectmod.value)
}
const clickmod = val => {
  selectmod.value = val
  if (gotype.gotype === 'bjs' && cutmodpage.value == 0) {    
    currentmodData.value = modData.value[val]
  } else if (cutmodpage.value == 1) {
    currentAI6TwoData.value = AI6TwoData.value[val]
  } else if (gotype.gotype != 'bjs' && cutmodpage.value == 0){
    currentAI6Data.value = AI6Data.value[val]
  }
}
// const SwitchCourseType = (val) => {
//   courseTypeShow.value = val
//   if (val) {
//     courseData.value = courseDataJson.new
//     volumes.value = true
//   } else {
//     courseData.value = courseDataJson.old
//   }
//   currentData.value = courseData.value[selectGrand.value]
// }
const getImageUrl = (url) => {
  return new URL(url, import.meta.url).href
}

// 新课备课 获取id
const getCourseid = (id) => {
// 会返回复制得课程
  let params ={id: id +','+ user.user.userid};
  axios.post('https://pbl.cocorobo.cn/api/pbl/getcopyCourseByUseridSz', params, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    withCredentials: true
  })
    .then(res => {
        console.log(res);
        console.log(res.data[0]);
        // console.log(res.data[0][0].courseId);
        if (res.data[0].length > 0) {
          DialogRef.value.getClasslist(res.data[0][0])
        } else {
          getCourseid2(id, "studyDetail")
        }
    })
    .catch(err=>{
        console.log(err);
    })
}

// 复制课程并获取id
const getCourseid2 = (id, type) => {
  let params ={id: id +','+ user.user.userid};
  axios.post('https://pbl.cocorobo.cn/api/pbl/copyCourseSz', params, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    withCredentials: true
  })
    .then(res => {
      console.log(res);
      // console.log(res.data[0][0].courseId);
      DialogRef.value.getClasslist(res.data[0][0])

    })
    .catch(err=>{
      console.log(err);
    })
}

const openCourseDetail = (id) => {
  console.log(user.user)
  axios.post('https://pbl.cocorobo.cn/api/pbl/getcopyCourseByUseridSz', {id: id +','+ user.user.userid}, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    withCredentials: true
  })
  .then(res => {
    console.log('openCourseDetail',res)
    if (res.data[0].length > 0) {
      // let isSave = res.value[0].filter(x => {
      //   return x.courseId == id
      // })
      //这个是打开指定的课程接口
      	let url = '';
				if (lang.lang == 'hk') {
					url = "https://pbl.cocorobo.hk"
				}else if (lang.lang == 'en') {
					url = "https://pbl.cocorobo.com"
				}else{
					url = "https://pbl.cocorobo.cn"
				}
      // https://pbl.cocorobo.cn/pbl-student-table/dist/#/courseDetail?userid=0c3735c9-a2ef-11ef-9b30-005056b86db5&oid=414f2361-ad04-11ed-b13d-005056b86db5&org=0fec3a8a-ad04-11ed-b13d-005056b86db5&courseId=91886917-2f3b-11f1-bcd9-005056924926&tType=1&cid=&screenType=2
      
      let url2 = `${url}/pbl-student-table/dist/#/courseDetail?userid=${user.user.userid}&oid=${user.user.organizeid}&org=${user.user.org}&courseId=${res.data[0][0].courseId}&tType=1&cid=&screenType=2`
      console.log(url2, "url2")
      // top.U.MD.D.I.openInApplication("studyDetail", res.value[0][0].courseId, 2, user.user.type);
      top.U.MD.D.I.openInApplication('setUrl',{url:url2,title:'课程详情',id:new Date().getTime()})
    } else {
      updateCourseId(id, "studyDetail")
    }
  })
  .catch(err => {
    console.log(err)
  })
  // 会返回复制得课程
  // top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/getcopyCourseByUseridSz", [id, user.user.userid], function (res) {
  //   console.log(res)
  //   if (res.value[0].length > 0) {
  //     // let isSave = res.value[0].filter(x => {
  //     //   return x.courseId == id
  //     // })
  //     //这个是打开指定的课程接口
  //     	let url = '';
	// 			if (lang.lang == 'hk') {
	// 				url = "https://pbl.cocorobo.hk"
	// 			}else if (lang.lang == 'en') {
	// 				url = "https://pbl.cocorobo.com"
	// 			}else{
	// 				url = "https://pbl.cocorobo.cn"
	// 			}
  //     // https://pbl.cocorobo.cn/pbl-student-table/dist/#/courseDetail?userid=0c3735c9-a2ef-11ef-9b30-005056b86db5&oid=414f2361-ad04-11ed-b13d-005056b86db5&org=0fec3a8a-ad04-11ed-b13d-005056b86db5&courseId=91886917-2f3b-11f1-bcd9-005056924926&tType=1&cid=&screenType=2
      
  //     let url2 = `${url}/pbl-student-table/dist/#/courseDetail?userid=${user.user.userid}&oid=${user.user.organizeid}&org=${user.user.org}&courseId=${res.value[0][0].courseId}&tType=1&cid=&screenType=2`
  //     // top.U.MD.D.I.openInApplication("studyDetail", res.value[0][0].courseId, 2, user.user.type);
  //     top.U.MD.D.I.openInApplication('setUrl',{url:url2,title:'课程详情',id:new Date().getTime()})
  //   } else {
  //     updateCourseId(id, "studyDetail")
  //   }
  // }, [], { "type": "POST", "withCredentials": true });

}
const getTimeCourse = (id, item) => {
  if (setIntervalNum.value) {
    clearInterval(setIntervalNum.value)
  }
  try {
    setIntervalNum.value = setInterval(() => {
      top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/addOperationTimeT", [user.user.userid, id, '5', 30], function (res) {
        console.log(res, "22222222222222222");
      }, [], { "type": "POST", "withCredentials": true });

    }, 30000)
  } catch (e) {
    console.log(e)
  }
  // 
  const middleTime = Math.random() * 2 + 6;
  const interValtTime = Math.floor(middleTime * 60) * 1000 + 30000;
  const params = {
    serverName: "深教AI6",
    dataType: 0,
    teacherName: user.user.name,
    teacherAccount: "",
    eduId: userInfo.user.eduid || userInfo.user.sessionid,
    schoolName: user.user.schoolName,
    schoolType: "",
    area: "",
    coursePackageName: "AI课程",
    courseId: id,
    courseName: item.title,
    courseGrade: selectGrand.value,
    courseTime: Math.round(middleTime),
    startTime: new Date().toLocaleString().replace(/\//g, "-"),
    endTime: "",
  }
  setTimeout(() => {
    params.endTime = new Date().toLocaleString().replace(/\//g, "-")
    console.log(params, interValtTime)
    axios.post("//pbl.cocorobo.cn/api/szdjg/sync/class", JSON.stringify(params), {
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(res => {
      console.log(res)
    })
  }, interValtTime);
}
// const updateCourse = (id, item) => {
//   // 会返回courseId和state 两个参数  然后打开
//   getTimeCourse(id, item)
//   top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/getcopyCourseByUseridSz", [id, user.user.userid], 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) => {
  axios.post('https://pbl.cocorobo.cn/api/pbl/copyCourseSz', {id: id +','+ user.user.userid}, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    withCredentials: true
  })
  .then(res => {

  // top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/copyCourseSz", [id, user.user.userid], function (res) {
    console.log(res)
    if (res.data[0][0].courseId != "") {
      if (type == "openCourseNewUpdate") {
        top.U.MD.D.I.openInApplication("openCourseNewUpdate", res.data[0][0].courseId)
      } else {
        let url = '';
				if (lang.lang == 'hk') {
					url = "https://pbl.cocorobo.hk"
				}else if (lang.lang == 'en') {
					url = "https://pbl.cocorobo.com"
				}else{
					url = "https://pbl.cocorobo.cn"
				}
        // https://pbl.cocorobo.cn/pbl-student-table/dist/#/courseDetail?userid=0c3735c9-a2ef-11ef-9b30-005056b86db5&oid=414f2361-ad04-11ed-b13d-005056b86db5&org=0fec3a8a-ad04-11ed-b13d-005056b86db5&courseId=91886917-2f3b-11f1-bcd9-005056924926&tType=1&cid=&screenType=2
        
        let url2 = `${url}/pbl-student-table/dist/#/courseDetail?userid=${user.user.userid}&oid=${user.user.organizeid}&org=${user.user.org}&courseId=${res.data[0][0].courseId}&tType=1&cid=&screenType=2`
        // top.U.MD.D.I.openInApplication("studyDetail", res.value[0][0].courseId, 2, user.user.type);
        top.U.MD.D.I.openInApplication('setUrl',{url:url2,title:'课程详情',id:new Date().getTime()})
        // top.U.MD.D.I.openInApplication("studyDetail", res.value[0][0].courseId, 3, user.user.type);
      }
    }
  })
  .catch(err => {
    console.log(err)
  })
}

// const ReductionCourse = id => {
//   // updateReductionId.value = id
//   top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/getcopyCourseByUseridSz", [id, user.user.userid], 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 = () => {
  axios.post('https://pbl.cocorobo.cn/api/pbl/revertCourseSz', {id: updateReductionId.value}, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    withCredentials: true
  })
  .then(res => {
    console.log(res, "还原")
    dialogVisible.value = false
  })
  .catch(err => {
    console.log(err, "还原")
    dialogVisible.value = false
  });
}

const getDate = async (id) => {
  // currentData
  let dataList = [];

  return new Promise((resolve, reject) => {
    axios.post('https://pbl.cocorobo.cn/api/pbl/selectCourseDetailSz', {id: id}, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      withCredentials: true
    })
    .then(res => {
      console.log(res);
      console.log(res);
      if (!res || !res.data || res.data[0].length === 0 || res.data[0][0].chapters.length === 0) {
        reject(new Error("Invalid response or no chapters found"));
        return;
      }

      const datachapters = JSON.parse(res.data[0][0].chapters);

      for (let i = 0; i < datachapters.length; i++) {
        const data = datachapters[i];
        for (let j = 0; j < data.chapterInfo.length; j++) {
          const dataChapterInfo = data.chapterInfo[j];
          for (let k = 0; k < dataChapterInfo.taskJson.length; k++) {
            const DatahapterData = dataChapterInfo.taskJson[k];
            for (let l = 0; l < DatahapterData.chapterData.length; l++) {
              const obj = DatahapterData.chapterData[l];
              obj.checked = false;
              dataList.push(obj);
            }
          }
        }
      }

      resolve(dataList);
    })
    .catch(err => {
      console.error("Error fetching data:", err);
    });
  })
    .then((dataList) => {
      getUpdateCourse(dataList, id);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const getUpdateCourse = async (dataList, id) => {
  let m = currentData.value

  if (volumes.value) {
    await m.shang.map(x => {
      if (x.dataId == id) {
        x.dataList = dataList
      }
      return x
    })
  } else {
    await m.xia.map(x => {
      if (x.dataId == id) {
        x.dataList = dataList
      }
      return x
    })
  }
  currentData.value = m
  getUpdateCourseId.value = id
}

const checkedAll = (id) => {
  let data = currentData.value
  if (volumes.value) {
    data.shang.map(x => {
        x.dataList.map(y => {
          y.checked = false
        })
    })
    data.shang.map(x => {
      if (x.dataId == id) {
        x.dataList.map(y => {
          y.checked = !checked1.value
        })
      }
      return x
    })
  } else {
    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 downloadOne = async (url, fileName) => {
  try {
    console.log("urls", [user.user.userid, getUpdateCourseId.value, '4', 1])
    top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/addOperationTimeT", [user.user.userid, getUpdateCourseId.value, '4', 1], function (res) {
      console.log(res, '11111111111')
    }, [], { "type": "POST", "withCredentials": true });
  } catch (error) {
    console.log(error);
  }

  try {
    // 使用fetch获取文件，然后创建blob下载
    const response = await fetch(url);
    const blob = await response.blob();

    // 创建blob URL
    const blobUrl = window.URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = blobUrl;
    a.download = fileName || 'download.pdf';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);

    // 清理blob URL
    setTimeout(() => {
      window.URL.revokeObjectURL(blobUrl);
    }, 100);
  } catch (error) {
    console.log('Fetch下载失败:', error);
    // 回退方案：直接在新窗口打开，让用户手动保存
    window.open(url, '_blank');
  }
}
const DownloadProcessing = async () => {
  let data = currentData.value
  let urls = []
  if (volumes.value) {
    await data.shang.map(x => {
      // console.log(x)
      x.dataList.length > 0 && x.dataList.map(m => {
        if (m.checked) {
          urls.push(m)
        }
        return m
      })
      return x
    })
  } else {
    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
    })
  }

  try {
    console.log("urls", [user.user.userid, getUpdateCourseId.value, '4', urls.length])
    top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/addOperationTimeT", [user.user.userid, getUpdateCourseId.value, '4', urls.length], function (res) {
      console.log(res, '11111111111')
    }, [], { "type": "POST", "withCredentials": true });
  } catch (error) {
    console.log(error);
  }

  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.type != 2) {
      isupdateCourse.value = true
    }
  }
})
</script>
<style lang="scss" scoped>
.course_select {
  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;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        display: flex;
        gap: 5px;
        justify-content: space-between;
        align-items: center;
        .div_title_text{
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        span {
          // display: inline-block;
          flex-shrink: 0;
          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: 15px;
    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;
}

.beike {
  li {
    padding: 8px 5px;
    border-radius: 5px;
  }

  li:hover {
    background: rgba(0, 0, 0, 0.1);
    cursor: pointer;
  }
}
.Levelone{
  width: 120px;
  background: #E0EAFB;
  border-radius: 5px;
  color: #5D8AFB;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 33px;
  font-size: 16px;
  font-weight: 500;
}
.grandTitle2 {
  font-size: 16px;
  font-weight: 600 !important;
  line-height: 28px;
  letter-spacing: 0em;
  // text-align: center;
}
.grandTitle3{
  margin-top: 0;
}
</style>