<template>
  <div class="growth-details">
    <div class="navbar">
      <div class="nav-left" @click="returnclick">
        <el-icon color="#fff" size="20"><ArrowLeft /></el-icon>
      </div>
      <div class="nav-title">{{ data.growthName }}</div>
    </div>
    <!-- <template v-if="data.electiveTaskNum !== 0"> -->
    <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>
    <!-- </template> -->

    <div class="search">
      <div class="search-input">
        <el-input
          v-model="queryParams.taskName"
          :input-style="{
            width: '100%',
            height: '40px',
            color: '#fff',
          }"
          @change="getList"
          placeholder="搜索关键字"
        >
          <template #prefix>
            <el-icon color="#fff" class="el-input__icon"><search /></el-icon>
          </template>
        </el-input>
      </div>
      <el-dropdown>
        <img class="icon" src="@/assets/image/growth/qiehuan.png" />
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="tabClick(null, '4')"
              >全部</el-dropdown-item
            >
            <el-dropdown-item @click="tabClick(null, '0')"
              >未开始</el-dropdown-item
            >
            <el-dropdown-item @click="tabClick(null, '1')"
              >已完成</el-dropdown-item
            >
            <el-dropdown-item @click="tabClick(null, '2')"
              >进行中</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <!-- <img class="icon"  src="@/assets/image/growth/list.png" /> -->
      <img class="icon" @click="toPath" src="@/assets/image/growth/path.png" />
    </div>
    <div
      class="container"
      v-loading="loading"
      :style="{
        height: stageProcessList.length ? '' : ':400px',
      }"
    >
      <!-- :style="{
        top: data.electiveTaskNum !== 0 ? '165px' : '103px',
        height: stageProcessList.length ? '' : ':400px',
      }" -->
      <template v-if="stageProcessList && stageProcessList.length">
        <div
          :id="item.id"
          v-for="(item, key) in stageProcessList"
          :key="key"
          class="task-item"
        >
          <div class="task-img" @click.native="toFinish(item)">
            <img
              style="width: 100%; height: 100%"
              :src="getAssetsFile(item.courseType)"
            />
            <div class="task-img-icon">{{ key + 1 }}</div>
          </div>
          <div
            style="margin-left: 11px; width: 58%"
            @click.native="toFinish(item)"
          >
            <div style="display: flex; align-items: center">
              <div class="task-type">
                {{ TASK_TYPES.typeName[item.courseType] }}
              </div>
              <div class="task-name">{{ item.taskName }}</div>
            </div>
            <!-- <div
              class="task-state"
              :style="{
                color:
                  item.completionStatus === '0'
                    ? '#C4C2C2'
                    : item.completionStatus === '1'
                    ? '#0077EC'
                    : '#FF8726',
              }"
            >
              {{
                item.completionStatus === "0"
                  ? "未开始"
                  : item.completionStatus === "1"
                  ? "已完成"
                  : "进行中"
              }}
            </div> -->

            <template v-if="item.completionStatus === '0'">
              <div
                class="task-state"
                :style="{
                  color: item.canLearn ? '#F2903D' : '#c4c2c2',
                }"
              >
                未开始
              </div>
            </template>
            <template v-if="item.completionStatus === '1'">
              <div class="task-state" style="color: #8bc34a">已完成</div>
            </template>
            <template v-if="item.completionStatus === '2'">
              <div class="task-state" style="color: #f2903d">进行中</div>
            </template>
            <template v-if="item.completionStatus === '3'">
              <div class="task-state" style="color: #c4c2c2">已结束</div>
            </template>
            <template v-if="item.completionStatus === '10'">
              <div class="task-state" style="color: #c4c2c2">未解锁</div>
            </template>
            <div style="display: flex; align-items: center">
              <div style="flex: 1">
                <el-progress
                  :percentage="item.progress"
                  :show-text="false"
                  :stroke-width="3"
                  :color="item.progress == 100 ? '#8BC34A' : '#F2903D'"
                />
              </div>
              <div class="progress-text">{{ item.progress }}%</div>
            </div>
          </div>
        </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 { computed, reactive, ref, watch, onMounted } from "vue";
import { ElLoading } from "element-plus";
import { useRequest, request } from "@/api/request";
import { growthRequest } from "@/api/growthRequest";
import {
  EvaluationToLearn,
  QueryEvaluationTaskStatusOne,
  STUDY_RECORD,
  SubmitExternalExam,
  PROFESSIONAL_STUDENT_TASKLIST,
  PROFESSIONAL_STUDENT_LEARN,
} from "@/api/api";
import { useRoute, useRouter } from "vue-router";
import store from "@/store";
import { ElMessage } from "element-plus";
import ReturnHead from "@/components/ReturnHead.vue";
import { GROWTH, TASK_TYPES } from "@/api/CONST";
import dayjs from "dayjs";
import { useStore } from "vuex";
import { changeTime } from "@/api/method";
const {
  query: { routerId, type },
} = useRoute();
const router = useRouter();
const { commit, dispatch, state } = useStore();
// 专业力必修详情
const data = computed(() => state.growthInfo);
// 查询条件
const queryParams = reactive({
  type: 1,
});
const tabClick = (type, status) => {
  // 选修/必修
  if (type) {
    queryParams.type = type;
  }
  // 任务状态
  if (status) {
    queryParams.completionStatus = status;
  }
  if (status == 4) {
    queryParams.completionStatus = "";
  }
  getList();
};

console.log(data.value);
watch(data, () => {
  if (data.value.code === 6) {
    router.push({
      path: "/notpath",
    });
  }
});
// 学习任务列表
const stageProcessList = ref([]);
// 锚点跳转的次数
const anchorNum = ref(0);
onMounted(() => {
  dispatch("getGrowthInfo", { routerId, type });
  if (type) {
    queryParams.type = type;
  }
  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;

    if (anchorNum.value === 0) {
      let find = stageProcessList.value.find((item) => item.lastStudy);
      if (find) {
        // var aLink = document.createElement("a");
        // aLink.href = `#${find.id}`; // 设置链接地址
        // aLink.click();
        // document.body.removeChild(aLink);
      }
    }
  });
};
const openCourseVisible = ref(false);
const openCourseList = ref([]);
const openCourseIdList = ref([]);

const userInfo = computed(() => store.state.userInfo);

async function toFinish(d) {
  if (!d.canLearn) {
    ElMessage.warning(`学习任务暂未开始`);
    return;
  }
  if (d.completionStatus == 3) {
    ElMessage.warning(`学习任务已结束无法学习`);
    return;
  }
  if (d.completionStatus == 10) {
    ElMessage.warning(`请先完成“${d.superTaskName}”的学习任务`);
    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,
    });
  }
  console.log("TASK_TYPES.path[d.type]", TASK_TYPES.path[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: d.courseType === "11" ? "5" : GROWTH,
          projectId: d.courseId,
          infoId: d.courseType === "11" ? d.taskId : 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,
      };
      const path =
        TASK_TYPES.path[d.courseType](params) + d.info.examinationTestId;
      // 增加异步防止ios阻止弹窗弹出
      setTimeout(() => {
        window.open(path, "_top");
      });
    } else {
      let params = {
        courseId: d.courseId ? d.courseId : d.info.id,
        targetId: d.targetId ? d.targetId : "",
      };
      TASK_TYPES.path[d.courseType](params);
    }
  }
}
const getAssetsFile = (url) => {
  return new URL(`../../assets/image/growth/type${url}.png`, import.meta.url)
    .href;
};
function toOffcoursePlanPage(id) {
  window.open(
    `${location.protocol}//${location.host}${
      import.meta.env.VITE_BASE_API
    }/stu/project/redirectDetail?courseId=${id}`,
    "_top"
  );
}

const returnclick = () => {
  window.open(
    window.location.protocol + import.meta.env.VITE_BOE_GROWTH,
    "_top"
  );
};
const toPath = () => {
  router.push({
    path: "/growthPath",
    query: {
      routerId,
      type: queryParams.type,
    },
  });
};
</script>

<style lang="scss" scoped>
.growth-details {
  background-image: url(@/assets/image/growth/bg.png);
  background-size: 100%;
  background-repeat: no-repeat;
  height: 100vh;
  box-sizing: border-box;
  background-color: #ffffff;
  position: relative;
  :deep(input::placeholder) {
    color: #ffffff;
  }
  .container {
    position: absolute;
    background-color: #ffffff;
    top: 165px;
    left: 0;
    right: 0;
    border-radius: 15px 15px 0 0;
    padding: 5px 15px;
    .task-item {
      position: relative;
      z-index: 9999;
      display: flex;
      padding: 20px 0;
      border-bottom: 2px #d3e3f2 dashed;
      .progress-text {
        font-weight: bold;
        font-size: 15px;
        color: #333333;
        margin-left: 9px;
      }
      .task-img {
        width: 42%;
        border-radius: 4px;
        overflow: hidden;
        position: relative;
      }
      .task-img-icon {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        color: #fff;
        font-size: 12px;
        box-sizing: border-box;
        top: 0;
        left: 0;
        // background-image: url(@/assets/image/growth/listJiaoBiao.png);
        // background-size: 100% 100%;
        width: 25px;
        height: 16px;
        background: #f2903d;
        border-radius: 0 0px 4px 0px;
      }
      .task-state {
        font-size: 13px;
        margin-top: 7px;
        margin-bottom: 17px;
      }
      .task-name {
        font-size: 14px;
        color: #000000;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 200px;
      }
      .task-type {
        background-image: url(@/assets/image/growth/task-type.png);
        width: 41px;
        height: 17px;
        background-size: 100% 100%;
        font-weight: 400;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 12px;
        color: #ffffff;
        margin-right: 5px;
      }
    }
  }
  .search {
    display: flex;
    align-items: center;
    padding: 0 15px;
    .search-input {
      flex: 1;
    }
    .icon {
      width: 18px;
      height: 18px;
      margin-left: 8px;
    }
    :deep(.el-input__wrapper) {
      box-shadow: none;
      padding-left: 18px;
      background-color: rgba(255, 255, 255, 0.1);
      border-radius: 20px;
    }
    :deep(.el-input__inner) {
      background-color: rgba(255, 255, 255, 0);
      padding-left: 0;
    }
  }
  .navbar {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 44px;
    .nav-title {
      width: 300px;
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-weight: 500;
      font-size: 18px;
      color: #ffffff;
    }
    .nav-left {
      position: absolute;
      left: 10px;
      top: calc(50% - 10px);
    }
  }
  .el-dialog__body {
    width: 80%;
  }
  :deep(.el-dialog__body) {
    padding-top: 0px;
  }
  .el-dialog__header {
    display: none;
  }

  .tabs {
    padding: 12px 0 14px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    .tabs-item {
      color: #ffffff;
      margin: 0 33px;
      display: flex;
      align-items: center;
      flex-direction: column;
      font-size: 15px;
      opacity: 0.7;
      font-weight: 700;
    }
    .tabs-line {
      width: 39px;
      height: 3px;
      margin-top: 6px;
    }
    .active {
      font-size: 17px;
      font-weight: 700;
      opacity: 1;
      .tabs-line {
        background: #ffffff;
        border-radius: 2px;
      }
    }
  }
}
</style>
