<template>
  <div>
    <el-dialog v-model="props.examShow" title="在线考试" width="1300px" :before-close="handleClose" draggable>
      <div class="countdown" v-if="item && item.examTime">剩余考试时间：{{ showtime }}</div>
      <div class="main" v-if="item">
        <div class="left">
          <div class="top">第&nbsp;&nbsp;
            <span>{{ index + 1 }}&nbsp;/&nbsp;{{ list.length }}</span>&nbsp;&nbsp;题
          </div>
          <!-- 判断题 -->
          <div class="content" v-if="item.qtype == '0'">
            <span class="qtype">【判断题】</span>{{ item.questionname }}
          </div>
          <div class="answer_area" v-if="item.qtype == '0'">
            <el-radio-group v-model="item.checked" @change="changeAnswer($event)">
              <div class="exam">
                <el-radio :label="'T'" size="large">{{ "T、" + item.a }}</el-radio>
                <el-radio :label="'F'" size="large">{{ "F、" + item.b }}</el-radio>
              </div>
            </el-radio-group>
          </div>
          <!-- 单选题 -->
          <div class="content" v-if="item.qtype == '1'">
            <span class="qtype">【单选题】</span>
            {{ item.questionname }}
          </div>
          <div class="answer_area" v-if="item.qtype == '1'">
            <el-radio-group v-model="item.checked" @change="changeAnswer($event)">
              <div class="exam">
                <el-radio :label="'A'" size="large">{{ "A、" + item.a }}</el-radio>
                <el-radio :label="'B'" size="large">{{ "B、" + item.b }}</el-radio>
                <el-radio :label="'C'" size="large">{{ "C、" + item.c }}</el-radio>
                <el-radio :label="'D'" size="large">{{ "D、" + item.d }}</el-radio>
              </div>
            </el-radio-group>
          </div>
          <!-- 多选题 -->
          <div class="content" v-if="item.qtype == '2'">
            <span class="qtype">【多选题】</span>
            {{ item.questionname }}
          </div>
          <div class="answer_area" v-if="item.qtype == '2'">
            <el-checkbox-group v-model="item.checked" @change="changeAnswer($event)">
              <div class="exam">
                <el-checkbox :label="'A'" size="large">{{ "A、" + item.a }}</el-checkbox>
                <el-checkbox :label="'B'" size="large">{{ "B、" + item.b }}</el-checkbox>
                <el-checkbox :label="'C'" size="large">{{ "C、" + item.c }}</el-checkbox>
                <el-checkbox :label="'D'" size="large">{{ "D、" + item.d }}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
          <div class="btns">
            <el-button @click="clickFlag"><el-icon>
                <Flag />
              </el-icon><span v-if="!item.isFlag">&nbsp;标记</span><span v-if="item.isFlag">&nbsp;取消标记</span></el-button>
            <el-button type="primary" v-if="index != 0" @click="prev">上一题</el-button>
            <el-button type="primary" v-if="index < list.length - 1" @click="next">下一题</el-button>
            <el-button type="primary" @click="submit">交卷</el-button>
          </div>
        </div>
        <div class="right">
          <div class="right_item" v-if="pdList && pdList.length > 0">
            <div>一、判断题（共{{ pdList.length }}道，每题{{ examPaper.trueOrFalseQuestions }}分，合计{{ pdList.length *
              examPaper.trueOrFalseQuestions }}分）</div>
            <div class="list">
              <div v-for="(it, inde) in list" :key="inde" @click="selectOne(inde)">
                <div class="listItem" v-if="it.qtype == '0'">
                  <div :class="(typeof it.checked === 'string' && it.checked) || (typeof it.checked === 'object' && it.checked.length > 0) ?
                    'select index' : 'index'">{{ inde + 1 }}</div>
                  <div class="flag">
                    <el-icon v-if="it.isFlag" :color="'var(--el-color-primary)'">
                      <Flag />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="right_item" v-if="danXList && danXList.length > 0">
            <div>二、单选题（共{{ danXList.length }}道，每题{{ examPaper.singleChoice }}分，合计{{ danXList.length *
              examPaper.singleChoice }}分）</div>
            <div class="list">
              <div v-for="(it, inde) in list" :key="inde" @click="selectOne(inde)">
                <div class="listItem" v-if="it.qtype == '1'">
                  <div :class="(typeof it.checked === 'string' && it.checked) || (typeof it.checked === 'object' && it.checked.length > 0) ?
                    'select index' : 'index'">{{ inde + 1 }}</div>
                  <div class="flag">
                    <el-icon v-if="it.isFlag" :color="'var(--el-color-primary)'">
                      <Flag />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="right_item" v-if="duoXList && duoXList.length > 0">
            <div>三、多选题（共{{ duoXList.length }}道，每题{{ examPaper.multipleChoice }}分，合计{{ duoXList.length *
              examPaper.multipleChoice }}分）</div>
            <div class="list">
              <div v-for="(it, inde) in list" :key="inde" @click="selectOne(inde)">
                <div class="listItem" v-if="it.qtype == '2'">
                  <div :class="(typeof it.checked === 'string' && it.checked) || (typeof it.checked === 'object' && it.checked.length > 0) ?
                    'select index' : 'index'">{{ inde + 1 }}</div>
                  <div class="flag">
                    <el-icon v-if="it.isFlag" :color="'var(--el-color-primary)'">
                      <Flag />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div>
          <el-button type="primary" @click="handleClose">
            <el-icon>
              <Close />
            </el-icon>关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, defineProps, defineEmits, getCurrentInstance } from "vue";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();
import { dateFormat } from "@/utils/tools";
const { D_DBZ_YHDJ, D_BZ_SF, NSFBXSCTP, NJCXLY, NYHBZ } = proxy.$dict("D_DBZ_YHDJ", "D_BZ_SF",
  "NSFBXSCTP", "NJCXLY", "NYHBZ");
// 数据
const props = defineProps({
  examShow: {
    type: Boolean,
    default: true
  },
  id: {
    type: String,
    default: ""
  },
  listId: {
    type: String,
    default: ""
  }
});
// 题目列表
const list = ref([]);
// 当前题目下标
const index = ref(0);
// 当前题目对象
const item = ref(null);
const emits = defineEmits(["changeVi3"]);
const showtime = ref("0秒");
const countdown = ref(0);
const examPaper = ref(null);
const timer = ref(null);
const isFlag = ref(true);
const pdList = ref([])
const danXList = ref([])
const duoXList = ref([])
const starttime = ref(null);
// 初始化
onMounted(() => {
  // 查询考试试题列表
  getExamlibList(props.listId);
  // 获取试卷详情
  getExampaperInfo(props.id);
});
// 获取试卷详情
const getExampaperInfo = (id) => {
  getApi({}, "/mosty-jcgl/paper/getInfo?id=" + id).then((res) => {
    examPaper.value = res;
    starttime.value = dateFormat({ type: "all", time: new Date() })
    if (res.examTime) {
      showtime.value = res.examTime + "分";
      countdown.value = res.examTime * 60;
      timer.value = setInterval(() => {
        setCountDown();
      }, 1000);
    }
  });
};
// 倒计时
const setCountDown = () => {
  if (countdown.value == 0) {
    clearInterval(timer.value);
    showtime.value = "考试结束";
    isFlag.value = false;
    ElMessageBox.confirm("当前考试时间已结束，将自动交卷", "警告").then(() => {
      save();
    }).catch(() => {
      save();
    });
  } else {
    let time = countdown.value - 1;
    let temp;
    if (time >= 60) {
      temp = Math.floor(time / 60) + "分" + (time % 60) + "秒";
    } else {
      temp = time + "秒";
    }
    countdown.value = time;
    showtime.value = temp;
  }
};
//交卷
const submit = () => {
  for (let i = 0; i < list.value.length; i++) {
    let answer = list.value[i].checked;
    if (!answer || answer.length == 0) {
      ElMessageBox.confirm(
        "当前第" + (i + 1) + "题没有完成，确定交卷？",
        "警告"
      ).then(() => {
        save();
      }).catch(() => { });
      return;
    }
  }
  save();
};
// 保存
const save = () => {
  let tbExamlibVoList = []
  for (let i = 0; i < list.value.length; i++) {
    let answer = list.value[i].checked
    if (answer) {
      answer = typeof answer === 'object' ? answer.join('') : answer
    }
    tbExamlibVoList.push({
      id: list.value[i].id,
      answer: answer
    })
  }
  let param = {}
  param.paperid = examPaper.value.id
  param.starttime = starttime.value
  param.endtime = dateFormat({ type: "all", time: new Date() });
  param.tbExamlibVoList = tbExamlibVoList;
  postApi(param, "/mosty-jcgl/paper/submitExamPaper").then((res) => {
    ElMessageBox.alert('交卷成功,当前试题已考试' + (res.count + 1) + '次，本次考试得分：' + res.score + '分');
    emits("changeVi3", false);
  })
}
// 右侧选中一个
const selectOne = (inde) => {
  index.value = inde;
  item.value = list.value[index.value];
};
// 标记、取消标记
const clickFlag = () => {
  item.value.isFlag = !item.value.isFlag
}
// 上一题
const prev = () => {
  index.value = index.value - 1;
  item.value = list.value[index.value];
};
// 下一题
const next = () => {
  index.value = index.value + 1;
  item.value = list.value[index.value];
};
// 切换答案
const changeAnswer = (e) => {
  if (item.value.qtype != "2") {
    list.value[index.value].checked = e;
    item.value.checked = e;
  } else {
    list.value[index.value].checked = e;
    item.value.checked = e;
  }
};
const getExamlibList = async (id) => {
  getApi(
    {
      id: id,
      pageCurrent: 1,
      pageSize: 1000
    },
    "/mosty-jcgl/exampaper/getExamlibByPaperId"
  ).then((res) => {
    list.value = res.records;
    list.value.forEach((item) => {
      if (item.qtype == "2") {
        item.checked = [];
      }
    });
    item.value = res.records[index.value];
    pdList.value = res.records.filter(item => { return item.qtype == '0' })
    danXList.value = res.records.filter(item => { return item.qtype == '1' })
    duoXList.value = res.records.filter(item => { return item.qtype == '2' })
  });
};
// 关闭弹窗
const handleClose = () => {
  ElMessageBox.confirm("关闭弹窗将不记得分，请确认?", "警告").then(() => {
    emits("changeVi3", false);
  });
};
</script>
<style lang="scss" scoped>
.main {
  height: 500px;
  display: flex;

  .right {
    width: 30%;
    padding: 0 20px;
    overflow: auto;

    .right_item {
      margin-bottom: 15px;

      .list {
        display: flex;
        flex-wrap: wrap;

        .listItem {
          cursor: pointer;
          margin: 15px 0 0 15px;
          width: 30px;
          height: 42px;
          background: #e9e6e6;

          >div {
            display: flex;
            align-items: center;
            justify-content: center;
            box-sizing: border-box;
          }

          .select {
            background: var(--el-color-primary);
            color: #fff;
          }

          .index {
            height: 25px;
            border-bottom: 2px solid #fff;
          }
        }
      }
    }
  }

  .left {
    .btns {
      width: 100%;
      margin-top: 20px;
      padding-right: 30px;
      text-align: right;
    }

    .answer_area {
      margin-top: 15px;

      .exam {
        display: flex;
        flex-direction: column;
      }
    }

    .content {
      margin: 10px 10px 0 10px;
      font-size: 16px;
      line-height: 22px;

      .qtype {
        color: var(--el-color-primary);
        font-size: 18px;
        font-weight: 900;
      }
    }

    .top {
      font-size: 20px;
      font-weight: 900;

      >span {
        color: var(--el-color-primary);
      }
    }

    width: 70%;
    border-right: 1px solid var(--el-color-primary);
  }
}

.countdown {
  line-height: 50px;
  color: red;
  font-size: 16px;
  font-weight: 800;
}

::v-deep .el-checkbox {
  color: #000;
}

::v-deep .el-radio {
  color: #000;
}
</style>
