<template>
  <div class="growth-path">
    <div class="nav">
      <ReturnHead text="专业力必修" :gohome="true"></ReturnHead>
      <div class="tabs">
        <div
          class="tabs-item"
          :class="queryParams.type == 1 ? 'active' : ''"
          @click="tabClick(1)"
        >
          <div class="tabs-text">必修</div>
          <div class="tabs-line"></div>
        </div>
        <div
          class="tabs-item"
          :class="queryParams.type == 2 ? 'active' : ''"
          @click="tabClick(2)"
        >
          <div class="tabs-text">选修</div>
          <div class="tabs-line"></div>
        </div>
      </div>
    </div>

    <!-- 占位容器防止塌陷 -->
    <div class="placeholder"></div>

    <div
      class="path-container"
      v-loading="loading"
      :style="stageProcessList.length ? '' : 'height:400px'"
    >
      <template v-if="stageProcessList && stageProcessList.length">
        <div
          class="path-item"
          @click="toFinish(item)"
          v-for="(item, index) of stageProcessList"
          :key="item.id"
        >
          <div class="item-content">
            <div class="icon">
              <template v-if="item.lastStudy">
                <img
                  style="width: 100%; height: 100%"
                  src="@/assets/image/growth/growth-icon4.png"
                />
              </template>
              <template v-else-if="item.completionStatus === '1'">
                <img
                  style="width: 100%; height: 100%"
                  src="@/assets/image/growth/growth-icon1.png"
                />
              </template>
              <template v-else-if="item.completionStatus === '2'">
                <img
                  style="width: 100%; height: 100%"
                  src="@/assets/image/growth/growth-icon2.png"
                />
              </template>
              <template
                v-else-if="
                  item.completionStatus === '0' ||
                  item.completionStatus === '10'
                "
              >
                <img
                  style="width: 100%; height: 100%"
                  src="@/assets/image/growth/growth-icon3.png"
                />
              </template>
            </div>
            <template v-if="item.completionStatus !== '2'">
              <div class="item-text">
                {{
                  `${item.taskName}${
                    item.completionStatus === "10" ? "（未解锁）" : ""
                  }`
                }}
              </div>
            </template>
            <template v-else>
              <div class="item-progress">
                <div
                  :style="{
                    width: `${item.progress}%`,
                  }"
                  class="progress-content"
                >
                  <div class="rocket">
                    <img
                      style="width: 100%; height: 100%"
                      src="@/assets/image/growth/rocket.png"
                    />
                  </div>
                </div>
                <div class="progress-text">{{ item.taskName }}</div>
              </div>
            </template>
          </div>
          <template v-if="index != stageProcessList.length - 1">
            <div
              class="gap"
              :style="{
                height: item.completionStatus !== '2' ? '48px' : '70px',
              }"
            >
              <!-- 虚线不可删除 -->
              <div></div>
            </div>
          </template>
        </div>
      </template>
      <template v-else>
        <el-empty description="暂无数据" />
      </template>
    </div>
    <el-dialog
      top="120px"
      title="开课列表"
      v-model="openCourseVisible"
      style="
        min-height: 320px;
        padding: 0;
        border-radius: 4px;
      "
      width="80%"
    >
      <div style="width: 100%; min-height: 210px; margin-top: 12px">
        <div
          v-for="(item, key) in openCourseList"
          style="
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
            background: rgb(247, 251, 253);
            height: 40px;
            padding: 5px;
            border-radius: 5px;
          "
        >
          <div
            style="
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
              width: 200px;
            "
          >
            {{ item }}
          </div>
          <div
            @click="toOffcoursePlanPage(openCourseIdList[key])"
            style="
              width: 60px;
              height: 30px;
              text-align: center;
              line-height: 30px;
              background: #0078fc;
              border-radius: 5px;
              color: #fff;
              cursor: pointer;
            "
          >
            去上课
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import ReturnHead from "@/components/ReturnHead.vue";
import { computed, reactive, onMounted, onUnmounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useRequest, request } from "@/api/request";
import { growthRequest } from "@/api/growthRequest";
import { GROWTH, TASK_TYPES } from "@/api/CONST";
import { ElMessage } from "element-plus";
import {
  EvaluationToLearn,
  QueryEvaluationTaskStatusOne,
  STUDY_RECORD,
  SubmitExternalExam,
  PROFESSIONAL_STUDENT_TASKLIST,
  PROFESSIONAL_STUDENT_LEARN,
} from "@/api/api";
import { useStore } from "vuex";
import store from "@/store";
const { commit, dispatch, state } = useStore();
const {
  query: { courseId, routerId, type, infoId, chapterOrStageId, id },
} = useRoute();
const router = useRouter();
// 专业力必修详情
const data = computed(() => state.growthInfo);
const userInfo = computed(() => store.state.userInfo);
// 查询条件
const queryParams = reactive({
  type: 1,
});
const tabClick = (type, status) => {
  // 选修/必修
  if (type) {
    queryParams.type = type;
  }
  // 任务状态
  if (status) {
    queryParams.completionStatus = status;
  }
  getList();
};

// 是否加载数据中
const loading = ref(false);
const getList = () => {
  loading.value = true;
  growthRequest(PROFESSIONAL_STUDENT_TASKLIST, {
    growthId: routerId,
    ...queryParams,
  }).then((res) => {
    console.log(res);
    stageProcessList.value = res.data;
    loading.value = false;
  });
};
// 学习任务列表
const stageProcessList = ref([]);
onMounted(() => {
  dispatch("getGrowthInfo", { routerId, type });
  getList();
});
const openCourseVisible = ref(false);
const openCourseList = ref([]);
const openCourseIdList = ref([]);

async function toFinish(d) {
  if (d.completionStatus == 10) {
    ElMessage.warning("当前未解锁");
    return;
  }
  //更新学员当前任务
  await growthRequest(PROFESSIONAL_STUDENT_LEARN, {
    growthId: routerId,
    taskId: d.taskId,
  });

  if (d.courseType === "2") {
    if (!d.targetId) {
      return ElMessage.error("还未添加开课,请联系管理员！");
    }
    if (d.targetId.split(",").length > 1) {
      openCourseList.value = d.targetName?.split(",");
      openCourseIdList.value = d.targetId?.split(",");
      openCourseVisible.value = true;
      return;
    }
  }

  // 作业过期判断
  if (d.courseType == 4) {
    let date1 = new Date(d.info.submitEndTime).getTime();
    let date2 = new Date().getTime();
    if (date1 < date2) {
      dialogVisibleTip.value = "当前作业已结束";
      dialogVisible.value = true;
      //return
    }
  }
  // 直播结束时间
  if (d.courseType == 6) {
    let date1 = new Date(d.info.liveEndTime).getTime();
    let date2 = new Date().getTime();
    if (date1 < date2) {
      dialogVisibleTip.value = "当前直播已结束";
      dialogVisible.value = true;
      //return
    }
  }
  // 考试 停用
  if (d.courseType == 5) {
    // 此处判断外部考试跳转
    if (d.info.examType == 2) {
      // 点击即更新状态 进行中
      request(SubmitExternalExam, {
        chapterId: 0,
        externalId: d.courseId,
        externalName: d.taskName,
        targetId: data.value.id,
        studentNo: userInfo.value.userNo,
      })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
      router.push({
        path: "/externalexam",
        query: {
          courseId: d.courseId ? d.courseId : d.info.id,
          type: GROWTH,
        },
      });
      return;
    }
  }

  // 其他活动 结束时间
  if (d.courseType == 9) {
    let date1 = new Date(d.info.activityEndTime).getTime();
    let date2 = new Date().getTime();
    if (date1 < date2) {
      dialogVisibleTip.value = "当前活动已结束";
      dialogVisible.value = true;
      //return
    }
  }

  // 测评模块 请求接口跳转新的页面 - 新增 暂时未调试 目前无测评数据 2023-02-04
  if (d.courseType == 10) {
    if (d.completionStatus != 1) {
      // 肯定没有完成测评
      // 调用接口 跳转页面
      request(EvaluationToLearn, {
        businessType: "project",
        chapterId: 0,
        courseId: d.courseId,
        quizKid: d.info.evaluationTypeId,
        routerOrProjectId: routerId,
        studentId: userInfo.value.id,
        studentName: userInfo.value.realName,
      })
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            let jumpUrl = res.data.quizUrl;
            // 此处写跳转url
            window.open(jumpUrl, "_top");
          }
        })
        .catch((err) => {
          console.log(err);
        });
      return;
    } else {
      // 进行中 或者 已完成
      // 调用接口 判断当前测评状态 跳转页面
      console.log("我是查询测评跳转链接所传递得参数", {
        quizTaskId: d.quizTaskId,
      });
      request(QueryEvaluationTaskStatusOne, {
        quizTaskId: d.quizTaskId,
      })
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            if (res.data.complete_status == 2) {
              ElMessage.error("您已完成测评");
              return;
            } else {
              // 重新查询跳转
              // 调用接口 跳转页面
              console.log("我是查询测评跳转链接所传递得参数", {
                businessType: "project",
                chapterId: 0,
                courseId: d.courseId,
                quizKid: d.info.evaluationTypeId,
                routerOrProjectId: routerId,
                studentId: userInfo.value.id,
                studentName: userInfo.value.realName,
              });
              request(EvaluationToLearn, {
                businessType: "project",
                chapterId: 0,
                courseId: d.courseId ? d.courseId : d.info.id,
                quizKid: d.info.evaluationTypeId,
                routerOrProjectId: routerId,
                studentId: userInfo.value.id,
                studentName: userInfo.value.realName,
              })
                .then((res) => {
                  console.log(res);
                  if (res.code == 200) {
                    let jumpUrl = res.data.quizUrl;
                    // 此处写跳转url
                    window.open(jumpUrl, "_top");
                  }
                })
                .catch((err) => {
                  console.log(err);
                });
              return;
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
      return;
    }
  }

  if (!TASK_TYPES.path[d.courseType]) {
    ElMessage.error("暂时未开放");
    return;
  }

  if (
    d.courseType == 3 ||
    d.courseType == 7 ||
    (d.courseType == 5 && d.examType == 2)
  ) {
    console.log(d, data.value);
    await request(STUDY_RECORD, {
      studentId: userInfo.value.id,
      targetId: data.value.id,
      logo: GROWTH,
      type: GROWTH,
      stageOrChapterId: 0,
      taskId: d.id,
      taskType: d.courseType,
    });
  }

  if (typeof TASK_TYPES.path[d.courseType] === "string") {
    TASK_TYPES.path[d.courseType] &&
      TASK_TYPES.path[d.courseType].startsWith("http") &&
      window.open(TASK_TYPES.path[d.type] + d.targetId, "_top");
    TASK_TYPES.path[d.courseType] &&
      TASK_TYPES.path[d.courseType].startsWith("/") &&
      router.push({
        path: TASK_TYPES.path[d.courseType],
        query: {
          id: d.id,
          type: GROWTH,
          projectId: d.courseId,
          infoId: data.value.id,
          courseId: d.courseId ? d.courseId : d.info.id,
          pName: data.value.growthName,
          sName: d.taskName,
          chapterOrStageId: 0,

          // id: d.id,
          // type: PROJECT,
          // infoId: data.value.projectId,
          // courseId: d.courseId,
          // pName: data.value.name,
          // sName,
          // chapterOrStageId: chapterOrStageId,
          // studentId: userInfo.value.id,
          // status: d.status,
          // targetId: d.targetId,
          // evaType: d.evaType,
          // btype: 1,
          // quizTaskId: d.quizTaskId,
        },
      });
  } else if (typeof TASK_TYPES.path[d.courseType] === "function") {
    if (d.courseType == 5) {
      let params = {
        examType: d.info.examType,
      };
      window.open(
        TASK_TYPES.path[d.courseType](params) + d.info.examinationPaperId,
        "_top"
      );
    } else {
      let params = {
        courseId: d.courseId ? d.courseId : d.info.id,
        targetId: d.targetId ? d.targetId : "",
      };
      TASK_TYPES.path[d.courseType](params);
    }
  }
}
function toOffcoursePlanPage(id) {
  window.open(
    `${location.protocol}//${location.host}${
      import.meta.env.VITE_BASE_API
    }/stu/project/redirectDetail?courseId=${id}`,
    "_top"
  );
}
</script>

<style lang="scss" scoped>
.growth-path {
  min-height: 100vh;
  background-color: #ffffff;

  :deep(.el-dialog__body){
    padding-top: 0px;
  }
  .path-item {
    .item-content {
      display: flex;
      align-items: center;
      .progress-content {
        position: relative;
        height: 15px;
        border-radius: 16px;
        height: 15px;
        background: linear-gradient(90deg, #fecd49 0%, #e13915 100%);
        .rocket {
          position: absolute;
          width: 36px;
          height: 36px;
          right: -18px;
          top: -11px;
        }
      }
      .item-progress {
        position: relative;
        height: 15px;
        border-radius: 16px;
        flex: 1;
        background: #ededed;
        margin-left: 6px;
        .progress-text {
          position: absolute;
          top: 22px;
        }
      }
      .icon {
        width: 20px;
        height: 20px;
      }
      .item-text {
        margin-left: 10px;
      }
    }
    .gap {
      display: flex;
      justify-content: center;
      width: 20px;
      div {
        height: 100%;
        border-left: 1px dashed #c5c6ca;
        width: 1px;
      }
    }
  }

  .path-container {
    padding: 28px;
  }
  .placeholder {
    height: 98px;
  }
  .nav {
    position: fixed;
    left: 0;
    right: 0;
    background-color: #f6f6f6;
  }
  .tabs {
    height: 44px;
    padding: 12px 0 9px 0;
    margin-top: 10px;
    box-sizing: border-box;
    background-color: #ffffff;
    display: flex;
    justify-content: center;
    align-items: center;
    .tabs-item {
      width: 135px;
      display: flex;
      align-items: center;
      flex-direction: column;
      font-size: 18px;
      font-weight: 700;
    }
    .tabs-line {
      width: 135px;
      height: 1px;
      margin-top: 2px;
    }
    .active {
      color: #2478ff;
      .tabs-line {
        background-color: #61a4f9;
      }
    }
  }
}
</style>
