<template>
  <el-row>
    <el-col :span="20" class="box">
      <el-card class="box-card" v-if="examInfo">
        <span>评测详情</span>
        <el-divider></el-divider>
        <template #header>
          <div class="card-header">
            <el-tooltip v-if="examInfo.isPublic" class="box-item" content="无需邀请码即可加入" placement="top"
                        effect="dark">
              <el-icon>
                <Unlock/>
              </el-icon>
            </el-tooltip>
            <el-tooltip v-else class="box-item" content="需要邀请码加入" placement="top" effect="dark">
              <el-icon>
                <Lock/>
              </el-icon>
            </el-tooltip>
            <span style="font-size: 20px">评测「{{ examInfo.examName }}」</span>
            <el-tag class="ml-2" :type="statusType">{{ state }}</el-tag>
            <el-tag v-if="isFinished" class="ml-2" type="info">已完成</el-tag>
            <el-button
              v-if="!isJoined && (state === '未开始' || state === '进行中')"
              :disabled="isJoined"
              type="primary"
              style="float: right"
              @click="onJoinExam">
              报名参加
            </el-button>
            <el-button
              v-if="isJoined && state === '未开始'"
              :disabled="isJoined"
              type="primary"
              style="float: right">
              等待加入
            </el-button>
            <el-button
              v-if="isJoined && state === '进行中' && !isFinished"
              type="success"
              style="float: right"
              @click="onStartExam">
              开始评测
            </el-button>
            <el-button
              v-if="isJoined && (state === '已结束' || isFinished)"
              style="float: right"
              @click="onOpenResult">
              结果报告
            </el-button>
          </div>
        </template>
        <el-row>评测ID: {{ examId }}</el-row>
        <el-row>
          <el-col :span="12">
            所属课程: {{ courseInfo.name }}
          </el-col>
          <el-col :span="12">
            监考：{{ examInfo.antiCheating ? "是" : "否" }}
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            职位: {{ examInfo.position }}
          </el-col>
          <el-col :span="12">
            技能点: {{ examInfo.skills }}
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            开始时间：{{ examInfo.startTime }}
          </el-col>
          <el-col :span="12">
            结束时间：{{ examInfo.endTime }}
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            客观题: {{ examQuestionsNum - examCodeQuestionsNum }} 道
          </el-col>
          <el-col :span="12">
            编程题: {{ examCodeQuestionsNum }} 道
          </el-col>
        </el-row>
      </el-card>
      <el-dialog v-model="inputInviteCode" :width="500">
        <el-form label-width="150px">
          <el-form-item label="请输入邀请码">
            <el-input v-model="inviteCode"></el-input>
          </el-form-item>
        </el-form>
        <div style="margin: auto;width: fit-content">
          <el-button type="success" @click="joinExamByInviteCode">确定</el-button>
        </div>

      </el-dialog>
    </el-col>
  </el-row>
</template>

<script>
import dayjs from "dayjs";
import {ElMessage} from "element-plus";

export default {
  name: "studentExamDetails",
  data() {
    return {
      examInfo: [],
      courseInfo: [],
      examId: 0,
      isJoined: false,
      isFinished: false,
      inputInviteCode: false,
      examQuestionsNum: 0,
      examCodeQuestionsNum: 0,
      inviteCode: "",
      examList: [],
      totalNum: 0,
    };
  },

  computed: {
    state() {
      const TIME_FORMAT = "YYYY-MM-DD HH:mm:ss";
      const now = dayjs();
      const formattedStartTime = dayjs(this.examInfo.startTime, TIME_FORMAT);
      const formattedEndTime = dayjs(this.examInfo.endTime, TIME_FORMAT);

      if (formattedEndTime < now) {
        return "已结束";
      }
      if (formattedStartTime > now) {
        return "未开始";
      }
      return "进行中";
    },

    statusType() {
      switch (this.state) {
        case "未开始":
          return "info";
        case "进行中":
          return "success";
        case "已结束":
          return "danger";
      }
      return "";
    },

  },

  methods: {
    initial() {
      this.examId = this.$route.params.examId;
      this.$apis.getExamById(this.examId).then(({data}) => {
        this.examInfo = data.data.result;
        this.examInfo.skills = this.examInfo.skills.toString();
        this.courseInfo = this.examInfo.course;
      });

      this.$apis.getExamQuestions(this.examId).then(({data}) => {
        if(!!data.data.result) {
          this.examQuestionsNum = Object.keys(
              data.data.result.questionAndScore
          ).length;
        }
        this.$apis.getExamCodeQuestions(this.examId).then(({data}) => {
          this.examCodeQuestionsNum = data.data.result.length;
        });
      });
    },

    getExamState() {
      const curUserId = this.$store.state.user.id;
      let userLists = [];
      this.$apis.getExamJoinedUsers(this.examId).then(({data}) =>{
        userLists = data.data.result;
        if(!!userLists){
          userLists.forEach((item) => {
            if(item.id === curUserId) {
              this.isJoined = true;
            }
          });
        }
      });

      this.$apis.getExamSubmitRecordsByUserId(this.examId).then(({data}) => {
        this.isFinished = !!data.data.result.find((val) => !val.message);
      });
    },

    onJoinExam() {
      if (this.examInfo.isPublic) {
        this.$apis.joinPublicExam(this.examId).then(() => {
          this.isJoined = true;
          console.log(this.examInfo);
          ElMessage({
            message: "加入考试成功",
            type: "success",
          });
        });
      } else {
        this.inputInviteCode = true;

      }
    },

    joinExamByInviteCode() {
      const inviteCode = this.inviteCode;
      this.$apis.joinExamByInviteCode(inviteCode, this.examId)
          .then(() => {
            this.inputInviteCode = false;
            this.isJoined = true;
            console.log(this.examInfo);
            ElMessage({
              message: "加入考试成功",
              type: "success",
            });
          })
          .catch(() => {
          })
          .finally(() => {
            this.inviteCode = "";
          });
    },

    onStartExam() {
      const examId = this.examId?.toString();
      const url = "https://eval.seec.seecoder.cn/exam/" + examId + "/before-exam";
      window.open(url + "?id_token=" + this.$store.state.user.token);
    },
    onOpenResult() {
      const examId = this.examId?.toString() ?? "";
      const url = "https://eval.seec.seecoder.cn/student/result/" + examId;
      window.open(url + "?id_token=" + this.$store.state.user.token);
    },

  },

  created() {
    this.initial();
  },

  mounted() {
    this.getExamState();
  },


};
</script>

<style scoped>
.box {
  height: 80%;
  /*overflow-y: auto;*/
  display: flex;
  flex-direction: column;
  margin-left: 150px;
}
</style>