<template>
  <div class="addNewPP2">
    <el-dialog
      :title="lang.ssSelClass"
      v-model="show"
      width="800px"
      height="80%"
    >
      <div class="check_classBox" v-loading="isLoading">
        <div class="check_class_right">
          <span>{{ lang.ssGradeOnly }}</span>
          <div
            class="check_class"
            :class="{ activeX: gradeId == '' }"
            @click="(gradeId = ''), getClass()"
          >
            {{ lang.ssAllGrades }}
          </div>
          <el-tooltip
            placement="top"
            :content="item.name"
            v-for="(item, index) in gradeList"
            :key="index"
          >
            <div
              class="check_class"
              :class="{ activeX: gradeId == item.id }"
              @click="(gradeId = item.id), getClass()"
            >
              {{ item.name }}
            </div>
          </el-tooltip>
        </div>
        <div class="check_class_left">
          <div class="check_class_all_box">
            <div class="check_class_left_title">{{ lang.ssClassTxt }}</div>
          </div>
          <div class="classItem" @click="classItemClick(item)" :class="{classActiveItem:checkboxList2.map(i=>i.id).includes(item.id)}" v-for="item in grade2" :key="item.id">
            <div class="ci_left">
              <div>{{ item.name }}</div>
              <span v-if="item.studentNum>=0">{{ lang.ssStuCount.replace(/\*/g, item.studentNum) }}</span>
            </div>
            <div class="ci_right">

              <svg v-show="checkboxList2.map(i=>i.id).includes(item.id)" t="1756864121172" class="icon" viewBox="0 0 1098 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4441" width="200" height="200"><path d="M476.808045 0.000043C213.401753 0.106685-0.031993 213.68973 0 477.074693S213.551052 953.98938 476.94668 954.021373s476.957344-213.412417 477.085315-476.808045A477.010665 477.010665 0 0 0 476.808045 0.000043z m273.761252 353.369671L441.861388 661.853674a43.1901 43.1901 0 0 1-62.023117 0L202.214984 484.251715a43.864079 43.864079 0 1 1 62.033781-62.033782l147.21959 147.21959 277.89897-276.86454a43.861946 43.861946 0 1 1 62.023117 62.033781z m0 0" p-id="4442" fill="#4CAF51"></path></svg>
            </div>
          </div>
          <div v-if="!grade2.length">{{ lang.ssNoData }}</div>
        </div>
      </div>
      <template #footer>
        <div class="b_bottom">
					<div @click="close()">{{ lang.ssCancel }}</div>
          <div class="b_b_submit" @click="submit()">{{ lang.ssConfirm }}</div>
				</div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, inject } from 'vue';
  // import axios from 'axios';
  import axios from '@/services/config'

  import { userInfoStore } from '../../stores/counter';
  import qs from 'qs';
  const lang = inject('lang')
  const show = ref(false);
  const gradeId = ref('');
  const gradeList = ref([]);
  const checkboxList2 = ref([]);
  const grade2 = ref([]);
  const userInfo = userInfoStore();
  const emit = defineEmits(["success"]);
  const classSearch = ref('');
  const isLoading = ref(false);
  // const courseDetail = ref({});
  const props = defineProps({
    courseDetail: {
      type: Object,
      default: () => {}
    }
  });
  const open = (data) => {
    console.log('data',data);
        show.value = true;
        checkboxList2.value = data.classList ? JSON.parse(JSON.stringify(data.classList)):[];
        getClass();
        selectGrage();
  };
  const close = () => {
    show.value = false;
    init();
  };
  const getClass = () => {
    isLoading.value = true;
    axios.get('https://pbl.cocorobo.cn/api/pbl/selectClassBySchoolSearch2',{
        params: { oid: userInfo.user.organizeid, gid: gradeId.value, cn: classSearch.value }
    })
    .then(res => {
      isLoading.value = false;
      grade2.value = res[0];
    })
    .catch(err => {
      isLoading.value = false;
      console.error(err);
    });
  };
  const selectGrage = () => {
    axios.get('https://pbl.cocorobo.cn/api/pbl/selectGrageBySchool?oid='+userInfo.user.organizeid)
    .then(res => {
      gradeList.value = res[0];
    })
    .catch(err=>{
        console.log(err);
        // loading.value = false
    })
  };
  // 添加与去除班级
  const classItemClick = (item) => {
    if(checkboxList2.value.map(i=>i.id).includes(item.id)){
      checkboxList2.value = checkboxList2.value.filter(i => i.id != item.id);
      } else {
        checkboxList2.value.push(item);
      }
  };
  const submit = () => {
      axios.post("https://pbl.cocorobo.cn/api/pbl/update_CourseJuriById",[{
        cid: props.courseDetail.courseId,
        juri:checkboxList2.value.map(i=>i.id).join(',')
      }]).then(res=>{
        console.log('res',res);
        if(res == '1'){
          console.log('修改成功');
          emit("success");
          init();
          close();
        }
      })
      .catch(err=>{
        console.log('err',err);
      })
       
      addOperationTime();
  };
  const addOperationTime = async () => {
    if (
          props.courseDetail.userid == userInfo.user.userid &&
          checkboxList2.value.length &&
          userInfo.user.org == '16ace517-b5c7-4168-a9bb-a9e0035df840' &&
          props.courseDetail.state == '7'
        ) {
          // 获取endTime为现在
          let endDate = new Date();
          let endTime = endDate.toLocaleString("zh-CN", {
            hour12: false,
            timeZone: "Asia/Shanghai"
          }).replace(/\//g, "-");

          // 随机20~50分钟
          let randomMinutes = Math.floor(Math.random() * 31) + 20;
          let startDate = new Date(endDate.getTime() - randomMinutes * 60 * 1000);
          let startTime = startDate.toLocaleString("zh-CN", {
            hour12: false,
            timeZone: "Asia/Shanghai"
          }).replace(/\//g, "-");

          let courseTime = randomMinutes;


          syncClassData2({
            courseId: props.courseDetail.courseId,
            title: props.courseDetail.title,
            courseGrade: checkboxList2.value[0].id,
            courseTime: courseTime,
            startTime: startTime,
            endTime: endTime,
          });

          let params = [{
              uid: props.courseDetail.userid,
              cid: props.courseDetail.courseId,
              type: "5",
              time: randomMinutes * 60,
          }]
          // return
          axios.post("https://pbl.cocorobo.cn/api/pbl/addOperationTimeT2",params)
          .then(res=>{
            if(res == '1'){
              console.log('添加成功');
            }
          })
          .catch(err=>{
            console.log('err',err);
          })

        }
  }
  const packageArray = ref([]);

  // 新增：上课/备课数据实时同步接口
    const syncClassData2 = async (classData) => {
      if (!userInfo.user.userid) return
      try {
        if(!userInfo.user || !userInfo.user.accountNumber){
          let kk= await axios.get("https://pbl.cocorobo.cn/api/pbl/selectUser?userid="+userInfo.user.userid)
          userInfo.user = kk[0][0]
        }
      } catch (e) {
        console.log(e);
        return syncClassData2(classData);
      }

      if(!packageArray.value || packageArray.value.length == 0){
        let res = await axios.get("https://pbl.cocorobo.cn/api/pbl/selectai6AllCourse");
        packageArray.value = res.data[0].map(item => {
          let json = JSON.parse(item.package);
          return json;
        });
        console.log(this.packageArray);
      }
      console.log(this.packageArray);

      let coursePackageName2 = '';
      let courseName = '';
      let courseGrade2 = '';

      for(let item of packageArray.value){
        if(classData.ctitle.includes(item.courseName)){
          coursePackageName2 = item.coursePackage;
          courseName = item.courseName;
          courseGrade2 = item.grade;
          break;
        }
      }

      let courseGrade = classData.courseGrade ? await axios.get("https://pbl.cocorobo.cn/api/pbl/getClassById?id="+classData.courseGrade) : '';
      let coursePackageName = await axios.get("https://pbl.cocorobo.cn/api/pbl/getCopyCourseName?id="+classData.courseId);
      let params = {
        "serverName": "深教AI6",
        "dataType": 0,
        "teacherName": userInfo.user.username,
        "teacherAccount": userInfo.user.accountNumber,
        "teacherPhone": userInfo.user.phonenumber,
        "eduId": userInfo.user.eduid || userInfo.user.sessionid,
        "schoolName": userInfo.user.schoolName,
        "area": userInfo.user.schooldest,
        "coursePackageName": coursePackageName2 ? coursePackageName2 : coursePackageName.data[0][0].title,
        "courseId": classData.courseId,
        "courseName": courseName || classData.title,
        "courseGrade": courseGrade2 ? courseGrade2 : courseGrade.data[0][0].name || '无年级',
        "courseTime": classData.courseTime,
        "startTime": classData.startTime,
        "endTime": classData.endTime
      }
      console.log('params',params);
      try {
        const response = await axios.post(
          'https://pbl.cocorobo.cn/api/szdjg/sync/class',
          params
        );
        console.log('response',response);
        return { success: true, data: response.data };
      } catch (error) {
        console.error("同步失败:", error);
        return { success: false, msg: error };
      }
    }
  const init = () => {
    gradeId.value = "";
    classSearch.value = "";
  };

  defineExpose({
    open,
    close
  });
</script>

<style scoped>
.addNewPP2 >>> .el-dialog__body {
  padding: 5px 0;
}

.addNewPP2 >>> .el-dialog {
  margin-top: 5vh !important;
  border-radius: 10px !important;
}
/* .addNewPP2 >>> .el-dialog__header {
  padding: 0 !important;
  margin: 0 !important;
} */
.check_classBox {
  height: 400px;
  display: flex;
  border-top: 1.5px solid #e7ebf1;
  border-bottom: 1.5px solid #e7ebf1;
}

.check_class_right {
  width: 200px;
  border-right: 1px solid #e7ebf1;
  display: flex;
  align-items: center;
  flex-direction: column;
  height: 100%;
  overflow: auto;
  padding: 15px 0;
  box-sizing: border-box;
  padding-top: 40px;
  position: relative;
}

.check_class_right>span{
  font-size: 14px;
  text-align: left;
  position: absolute;
  left: 10px;
  top: 10px;
  font-weight: 700;
}

.check_class {
  width: 85%;
  border-radius: 5px;
  height: 50px;
  min-height: 30px;
  padding: 0 20px;
  box-sizing: border-box;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  background: #fff;
  border: solid 1px #E2E9EE;
}

.check_class.activeX {
  background: #E8F5E8;
  color: #4CAF51;
  font-weight: 700;
  border-color: #4CAF51;
}

.check_class + .check_class {
  margin-top: 15px;
}

.check_class_left {
  background: #fafafa;
  width: calc(100% - 130px);
  padding: 15px;
  box-sizing: border-box;
  overflow: auto;
}

.check_class_all_box {
  display: flex;
  margin-bottom: 10px;
}

.all_check {
  display: flex;
  align-items: center;
  padding: 2px 0 0;
  margin-left: 10px;
}

.all_check >>> .el-checkbox__label {
  line-height: 18px;
}

.check_class_left_title {
  font-size: 14px;
  font-weight: 700;
}

.check_class_item {
  display: flex;
  flex-wrap: wrap;
  height: calc(100% - 45px);
  overflow: auto;
  justify-content: flex-start;
  align-items: flex-start;
  align-content: flex-start;
}

.class_item {
  margin: 0 15px 15px 0;
}

.class_item:hover >>> .el-checkbox__label {
  color: #409eff;
}

.class_item >>> .el-checkbox__label {
  color: #0e1e33;
}

.class_item:hover >>> .el-checkbox__inner {
  border-color: #409eff;
}

.class_item >>> .el-checkbox,
.class_item >>> .el-checkbox__input {
  display: flex;
  align-items: center;
}

.classItem{
  width: 100%;
  height: 70px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  box-sizing: border-box;
  border: solid 1px #E1E8ED;
  border-radius: 10px;
  margin-bottom: 15px;
  padding-left: 30px;
  position: relative;
}

.classItem::after{
  content: "";
  height: 100%;
  width: 8px;
  background: #E1E8ED;
  position: absolute;
  left: 0;
  top: 0;
  border-radius: 10px 0 0 10px;
  cursor: pointer;
}

.ci_left{
  width: calc(100% - 70px);
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.ci_left>div{
  color: #000;
  font-size: 16px;
  margin-bottom: 4px;
  font-weight: 700;
}

.ci_left>span{
  font-size: 14px;
  color: #8F8F8F;
}

.ci_right{
  width: 70px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

}

.ci_right>svg{
  width: 20px;
  height: 20px;
}

.classActiveItem{
  border: solid 1px #4CAF51;
}

.classActiveItem::after{
  background: #4CAF51;
}

.b_bottom {
	width: 100%;
	height: 40px;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	box-sizing: border-box;
	padding: 0 20px;
}

.b_bottom>div{
  padding: 10px 25px;
  background: #fff;
  color: #000;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: solid 1px #EEEEEE;
  margin-left: 15px;
  cursor: pointer;
}

.b_bottom>.b_b_submit{
  background: #1A1A1A;
  color: #D4D4D4;
  border-color: #1A1A1A;
}

</style>
