<template>
  <el-card class="test" shadow="hover" @click="toTestInfo">

    <div :style="{borderBottom: type==='eval' ? '30px solid #f5b86e' : '30px solid #8dc9e2'}"
         style="float: right; width: 0; height: 0; position: absolute;right: 0;bottom: 0;border-left: 30px solid transparent;">
      <div v-if="type==='eval'" style="padding: 0 4px 0 4px; position: absolute; right: 0; bottom: -30px; color: white">
        E
      </div>
      <div v-else style="padding: 0 3px 0 3px; position: absolute; right: 0; bottom: -30px; color: white">
        C
      </div>
    </div>

    <el-row>
      <el-col :span="16">
        <el-col class="title">
          {{ title }}
        </el-col>
      </el-col>
      <el-col :span="8" class="status">
        <el-tag v-if="state==='NOT_STARTED'" size="small" type="info">未开始</el-tag>
        <el-tag v-else-if="state==='RUNNING_IN' && !isPublicTest" size="small" type="success">已参加</el-tag>
        <el-tag v-else-if="state==='RUNNING_NOT' && !isPublicTest" size="small">未参加</el-tag>
        <el-tag v-else-if="isPublicTest" size="small">开放中</el-tag>
        <el-tag v-else-if="state==='FINISHED'" size="small" type="danger">已结束</el-tag>
        <el-tag v-else-if="state==='CLOSED'" size="small" type="info">已关闭</el-tag>
      </el-col>
    </el-row>
    <el-row class="course" v-if="course!==''">
      {{ course }}
    </el-row>
    <el-row class="teacher">
      {{ teacherName }}
    </el-row>

    <el-row class="time">
      {{ timePeriod }}
    </el-row>

    <el-row v-if="type==='eval'" class="comment">
      {{ testVO.comment }}
    </el-row>
  </el-card>
</template>

<script>
import {ElMessage, ElMessageBox} from "element-plus";
import store from "@/store";

export default {
  name: "TestCard",
  props: {
    testVO: Object,
    isPublicTest: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      teacher: Object,
    };
  },
  computed: {
    isLogin() {
      return store.state.user.token;
    },
    isCreator() {
      if (this.testVO.examId) {
        return Number(this.testVO.course.teacherId) === Number(this.$store.state.user.id);
      }else{
        return this.testVO.creator.username === this.$store.state.user.phone;
      }
    },
    isTeacher() {
      return this.$store.getters.isTeacher;
    },
    isStudent() {
      return this.$store.getters.isStudent;
    },
    type() {
      if (this.testVO.examId) {
        return "eval";
      } else {
        return "coder";
      }
    },
    title() {
      if (this.type === "eval") {
        return this.testVO.examName;
      } else {
        return this.testVO.name;
      }
    },
    course() {
      if (this.type === "eval") {
        return "";
      } else {
        return "所属课程: " + this.testVO.course;
      }
    },
    teacherName() {
      if (this.type === "eval") {
        return "教师: " + this.teacher.name;
      } else {
        return "教师: " + this.teacher;
      }
    },
    timePeriod() {
      if (this.type === "eval") {
        return "时间: " + this.testVO.startTime.substring(0, 16) + "至" + this.testVO.endTime.substring(0, 16);
      } else {
        return "时间: " + this.timestampToTime(this.testVO.startAt) + "至" + this.timestampToTime(this.testVO.endAt);
      }
    },
    state() {
      const now = new Date();
      if (this.type === "eval") {
        if (new Date(this.testVO.endTime) < now) {
          return "FINISHED";
        } else if (new Date(this.testVO.startTime) > now) {
          return "NOT_STARTED";
        } else if (this.testVO.isJoined) {
          return "RUNNING_IN";
        } else {
          return "RUNNING_NOT";
        }
      } else {
        if (this.testVO.status === "CLOSED") {
          return "CLOSED";
        } else if (this.testVO.startAt * 1000 > now) {
          return "NOT_STARTED";
        } else if (this.testVO.endAt * 1000 < now) {
          return "FINISHED";
        } else if (this.testVO.joined) {
          return "RUNNING_IN";
        } else {
          return "RUNNING_NOT";
        }
      }
    },
  },
  async created() {
    if (this.type === "eval") {
      this.teacher = (await this.$apis.getUserAPI(this.testVO.course["teacherId"])).data.data;
    } else {
      this.teacher = (await this.$apis.getNameByUsernameAPI(this.testVO.creator.username)).data.data;
    }
  },
  methods: {
    timestampToTime(timestamp) {
      const date = new Date(timestamp * 1000);
      const Y = date.getFullYear() + "-";
      const M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      const D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      const h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      const m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes());
      return Y + M + D + h + m;
    },
    // TODO 分情况处理跳转
    async toTestInfo() {
      if (!this.isLogin) {
        ElMessage({
          showClose: true,
          message: "请先登录",
          type: "warning",
          duration: 1000,
        });
        await this.$router.push({name: "Auth", params: {login_to: "/portal"}});
        return;
      }

      console.log(this.testVO);

      if (this.isCreator) {
        if (this.type === "eval") {
          this.$router.push(`/exam/${this.testVO.examId}`);
          // window.open("https://eval.seec.seecoder.cn/teacher/exam/" + this.testVO.examId + "/details?id_token" + this.$store.state.user.token);
        } else {
          this.$router.push(`/exam/${this.testVO.id}`); //跳转到考试详情页
          // window.open("https://coder.seec.seecoder.cn/exam/" + this.testVO.id + "?id_token=" + this.$store.state.user.token);
        }
      } else if (this.isTeacher) {
        this.$message.error("无权访问其他教师创建的课程");
      } else {
        let messageBoxContent = "";
        let messageBoxTitle = "";
        let confirmButtonText = "";
        let cancelButtonText = "让我想想";
        let nextURL = "";
        if (this.type === "eval") {
          messageBoxTitle = "Eval";
          if (this.testVO.isJoined) {
            nextURL = "https://eval.seec.seecoder.cn/exam/" + this.testVO.id + "/before-exam/?id_token=" + this.$store.state.user.token;
            window.open(nextURL);
            return;
          } else {
            const courseId = (await this.$apis.getCourseByEvalId(this.testVO.course.id)).data.data;
            if (courseId) {
              const isCourseSelected = (await this.$apis.checkCourseSelection(courseId, this.$store.state.user.id)).data.data;
              if (isCourseSelected) {
                messageBoxContent = "是否立即查看测试详情";
                confirmButtonText = "立即查看";
                nextURL = "https://eval.seec.seecoder.cn/student/home/?id_token=" + this.$store.state.user.token;
              } else {
                messageBoxContent = "尚未参加课程，是否立即参加？";
                confirmButtonText = "立即选课";
                nextURL = "/course/" + courseId;
              }
            } else {
              messageBoxContent = "是否立即查看测试详情";
              confirmButtonText = "立即查看";
              nextURL = "https://eval.seec.seecoder.cn/student/home/?id_token=" + this.$store.state.user.token;
            }
          }
        } else {
          messageBoxTitle = "Coder";
          if (this.testVO.joined) {
            nextURL = "https://coder.seec.seecoder.cn/exam/" + this.testVO.id + "?id_token=" + this.$store.state.user.token;
            window.open(nextURL);
            return;
          } else {
            const courseId = (await this.$apis.getCourseByCoderId(this.testVO.courseId)).data.data;
            if (courseId) {
              const isCourseSelected = (await this.$apis.checkCourseSelection(courseId, this.$store.state.user.id)).data.data;
              if (isCourseSelected) {
                messageBoxContent = "是否立即查看测试详情";
                confirmButtonText = "立即查看";
                nextURL = "https://coder.seec.seecoder.cn/exam?id_token=" + this.$store.state.user.token;
              } else {
                messageBoxContent = "尚未选择课程，是否立即参加？";
                confirmButtonText = "立即选课";
                nextURL = "/course/" + courseId;
              }
            } else {
              messageBoxContent = "是否立即查看测试详情";
              confirmButtonText = "立即查看";
              nextURL = "https://coder.seec.seecoder.cn/exam?id_token=" + this.$store.state.user.token;
            }
          }
        }
        ElMessageBox.confirm(messageBoxContent, messageBoxTitle, {
          distinguishCancelAndClose: true,
          confirmButtonText,
          cancelButtonText,
        }).then(() => {
          if (nextURL.startsWith("http")) {
            window.open(nextURL);
          } else {
            this.$router.push(nextURL);
          }
        });
      }
    },
  }
};
</script>

<style scoped>
.test {
  min-height: 180px;
  border-radius: 8px;
  height: calc(100% - 14px);
  position: relative;
  border: 1px solid #cccccc;
}

.test:hover {
  cursor: pointer;
  border: 1px solid #aaaaaa;
}

.title {
  font-weight: bold;
  font-size: medium;
}

.status {
  text-align: right;
}

.course {
  font-size: 10px;
  margin-top: 4px;
  color: #999999;
}

.teacher {
  font-size: 10px;
  margin-top: 10px;
  color: #999999;
}

.time {
  margin-top: 4px;
  font-size: 10px;
  margin-bottom: 16px;
  color: #999999;
}

.comment {
  background-color: #f6f6f6;
  color: #777777;
  margin-top: 10px;
  border-radius: 8px;
  padding: 10px;
  font-size: 10px;
  margin-bottom: 16px;
}
</style>
