<template>
  <div>
    <el-dialog v-model="props.examShow" title="在线考试" :before-close="handleClose" width="90vw" draggable>
      <div class="countdown" v-if="examPaper.examTime != null">剩余考试时间：{{ showtime }}</div>
      <div class="main">
        <div class="left">
          <div class="examtitle">
            <span class="name">{{ props.examObj.name }}</span>
          </div>
          <div class="examtx" v-if="pdList && pdList.length > 0">
            <div class="txbox">{{ questionType.panDuan }}、判断题</div>
            <div class="cout">共{{ pdList.length }}道，每题{{ examPaper.trueOrFalseQuestions }}分，满分{{ pdList.length *
              examPaper.trueOrFalseQuestions }}分</div>
          </div>
          <!-- <div class="exambox" v-for="(item, index) in list" :key="index"> -->
          <div class="exambox" v-for="(item, index) in pdList" :key="index">
            <!-- 判断题 -->
            <div class="content" :id="`anchor-pd-${index + 1}`">
              <span class="qtype">{{ index + 1 }}.</span>{{ item.questionname }}
            </div>
            <div class="answer_img">
              <!-- <img :src="item.questionimg" alt=""> -->
              <MOSTY.Upload :width="'100%'" :limit="5" :nopicer="false" :isImg="true" :ShowfileList="false"
                v-model="item.files" :nameshow='true' :gsgfList="['jpg', 'png', 'jpeg']" disabled>
              </MOSTY.Upload>
            </div>
            <div class="answer_area">
              <el-radio-group v-model="item.checked" @change="changeAnswer($event, item)">
                <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 class="btns">
                <el-button @click="clickFlag(item)"><el-icon>
                    <Flag />
                  </el-icon><span v-if="!item.isFlag">&nbsp;标记</span><span
                    v-if="item.isFlag">&nbsp;取消标记</span></el-button>
              </div>
            </div>

          </div>
          <div class="examtx" v-if="danXList && danXList.length > 0">
            <div class="txbox">{{ questionType.danXuan }}、单选题</div>
            <div class="cout">共{{ danXList.length }}道，每题{{ examPaper.singleChoice }}分，满分{{ danXList.length *
              examPaper.singleChoice }}分</div>
          </div>
          <div class="exambox" v-for="(item, index) in danXList" :key="index">
            <!-- 单选题 -->
            <div class="content" :id="`anchor-danx-${index + 1}`">
              <span class="qtype">{{ index + 1 }}.</span>
              {{ item.questionname }}
            </div>
            <div class="answer_area">
              <el-radio-group v-model="item.checked" @change="changeAnswer($event, item)">
                <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 class="btns">
                <el-button @click="clickFlag(item)"><el-icon>
                    <Flag />
                  </el-icon><span v-if="!item.isFlag">&nbsp;标记</span><span
                    v-if="item.isFlag">&nbsp;取消标记</span></el-button>
              </div>
            </div>
          </div>
          <div class="examtx" v-if="duoXList && duoXList.length > 0">
            <div class="txbox">{{ questionType.duoXuan }}、多选题</div>
            <div class="cout">共{{ duoXList.length }}道，每题{{ examPaper.multipleChoice }}分，满分{{ duoXList.length *
              examPaper.multipleChoice }}分</div>
          </div>
          <div class="exambox" v-for="(item, index) in duoXList" :key="index">
            <div class="content" :id="`anchor-duox-${index + 1}`">
              <span class="qtype">{{ index + 1 }}.</span>
              {{ item.questionname }}
            </div>
            <div class="answer_area">
              <el-checkbox-group v-model="item.checked" @change="changeAnswer($event, item)">
                <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 class="btns">
                <el-button @click="clickFlag(item)"><el-icon>
                    <Flag />
                  </el-icon><span v-if="!item.isFlag">&nbsp;标记</span><span
                    v-if="item.isFlag">&nbsp;取消标记</span></el-button>
              </div>
            </div>

          </div>
          <div class="btns">
            <el-button type="primary" @click="submit">交卷</el-button>
          </div>
        </div>
        <div class="right">
          <div class="right_item" v-if="pdList && pdList.length > 0">
            <div>{{ questionType.panDuan || '一' }}、判断题（共{{ pdList.length }}道，每题{{ examPaper.trueOrFalseQuestions
              }}分，合计{{ pdList.length *
                examPaper.trueOrFalseQuestions }}分）</div>
            <div class="list">
              <div v-for="(it, inde) in pdList" :key="inde" @click="selectOne('pd', 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>{{ questionType.danXuan || '二' }}、单选题（共{{ danXList.length }}道，每题{{ examPaper.singleChoice }}分，合计{{
              danXList.length *
              examPaper.singleChoice }}分）</div>
            <div class="list">
              <div v-for="(it, inde) in danXList" :key="inde" @click="selectOne('danx', 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>{{ questionType.duoXuan }}、多选题（共{{ duoXList.length }}道，每题{{ examPaper.multipleChoice }}分，合计{{
              duoXList.length *
              examPaper.multipleChoice }}分）</div>
            <div class="list">
              <div v-for="(it, inde) in duoXList" :key="inde" @click="selectOne('duox', 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, onUnmounted, watch } from "vue";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();
import * as MOSTY from "@/components/MyComponents/index";
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
  },
  examObj: {
    type: Object,
    default: {}
  },
  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({});
const timer = ref(null);
const isFlag = ref(true);
/**判断题 */
const pdList = ref([])
/**单选题 */
const danXList = ref([])
/** 单选题 */
const duoXList = ref([])
const starttime = ref(null);
/** 题的中文序号 */
const questionType = ref({
  panDuan: '',
  danXuan: '',
  duoXuan: ''
})
// 初始化
onMounted(() => {
  // 查询考试试题列表
  getExamlibList(props.listId);
  // 获取试卷详情
  getExampaperInfo(props.id);
});
// 获取试卷详情
const getExampaperInfo = (id) => {
  getApi({}, "/mosty-jcgl/paper/getInfo?id=" + id).then((res) => {

    if (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 = () => {
  /** 检查未做的题（无答案的） */
  const checkAnswer = (arr, title) => {
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      let answer = item.checked;
      if (!answer || answer.length == 0) {
        return `【${title}】第 ${i + 1} 题没有完成，确定交卷？`
      }
    }
    return false
  }
  /** 确认并保存 */
  const confirm = (pdMessage) => {
    ElMessageBox.confirm(
      pdMessage,
      "警告"
    ).then(() => {
      clearInterval(timer.value);
      save();
    }).catch(() => { });
  }
  /** 单选的提示，没有提示就都填了答案 */
  let pdMessage = checkAnswer(pdList.value, '判断题')
  if (pdMessage) return confirm(pdMessage)
  let dxMessage = checkAnswer(danXList.value, '单选题')
  if (dxMessage) return confirm(dxMessage)
  let duoxMessage = checkAnswer(duoXList.value, '多选题')
  if (duoxMessage) return confirm(duoxMessage)
  save();
};

/**获取答案 */
const getAnswer = () => {
  // pdList.value = resObj.trueOrFalseList || [];

  // danXList.value = resObj.singleList || [];

  // duoXList.value = resObj.multipleList || [];
  let tbExamlibVoList = [];
  pdList.value.forEach(item => {
    let answer = item.checked
    if (answer) {
      answer = typeof answer === 'object' ? answer.join('') : answer
    }
    tbExamlibVoList.push({
      id: item.id,
      answer: answer
    })
  })
  danXList.value.forEach(item => {
    let answer = item.checked
    if (answer) {
      answer = typeof answer === 'object' ? answer.join('') : answer
    }
    tbExamlibVoList.push({
      id: item.id,
      answer: answer
    })
  })
  duoXList.value.forEach(item => {
    let answer = item.checked
    if (answer) {
      answer = typeof answer === 'object' ? answer.join('') : answer
    }
    tbExamlibVoList.push({
      id: item.id,
      answer: answer
    })
  })

  return tbExamlibVoList
}
// 保存
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 = getAnswer();

  postApi(param, "/mosty-jcgl/paper/submitExamPaper").then((res) => {
    ElMessageBox.alert('交卷成功,当前试题已考试' + (res.count + 1) + '次，本次考试得分：' + res.score + '分');
    emits("changeVi3", false);
  })
}
// 右侧选中一个
const selectOne = (type, inde) => {
  document.querySelector('#anchor-' + type + '-' + (inde + 1)).scrollIntoView(true);
};
// 标记、取消标记
const clickFlag = (item) => {
  item.isFlag = !item.isFlag
  // list.value.forEach(item => {
  //   if (item.id == val.id) {
  //   }
  // })
  // proxy.$forceUpdate();
}

// 切换答案
const changeAnswer = (e, val) => {
  list.value.forEach(item => {
    if (item.id == val.id) {
      item.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 = [];
      }
    });
    let resObj = res && res.records && res.records[0] || {};

    pdList.value = resObj.trueOrFalseList || [];
    danXList.value = resObj.singleList || [];
    duoXList.value = resObj.multipleList || [];
    /** 设置题的中文序号 */
    function setQuestionType() {
      let currCount = 0
      const chinaNumArr = ['一', '二', '三']
      if (pdList.value.length > 0) {
        questionType.value.panDuan = chinaNumArr[currCount]
        currCount++
      }
      if (danXList.value.length > 0) {
        questionType.value.danXuan = chinaNumArr[currCount]
        currCount++
      }
      if (duoXList.value.length > 0) {
        questionType.value.duoXuan = chinaNumArr[currCount]
      }
    }
    setQuestionType()
  });
};
// 关闭弹窗
const handleClose = () => {
  ElMessageBox.confirm("关闭弹窗将不记得分，请确认?", "警告").then(() => {
    emits("changeVi3", false);
  });
};


watch(props.examShow, (newVal) => {
  if (!newVal) {
    if (timer.value) clearInterval(timer.value);
  }
})

onUnmounted(() => {
  if (timer.value) clearInterval(timer.value);
})
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  background: #ebebeb !important;
}

::v-deep .el-checkbox {
  color: #000;
  background-color: #eff0f261;
  display: block !important;
  margin: 10px 0px;
  line-height: 43px;
  padding: 0 10px;
}

::v-deep .el-radio {
  color: #000;
  width: 558px !important;
  background-color: #eff0f261;
  display: block !important;
  margin: 10px 0px;
  padding: 0 10px;
}

.el-radio.el-radio--large {
  height: 34px;
  line-height: 34px;
}

.main {
  display: flex;
  width: 100%;
}

.left {
  height: 70vh;
  width: calc(100% - 400px);
  margin: 0 40px;
  background-color: #f2f5f5;

  .examtitle {
    height: 16vh;
    width: 100%;
    background: var(--el-color-primary);

    .name {
      height: 49px;
      color: #fff;
      display: block;
      text-align: center;
      font-size: 31px;
      padding: 5vh;
      font-weight: 500;
    }
  }

  .xqxxbox {
    height: 15vh;
    flex-wrap: wrap;
    background: #fff;
    box-shadow: 0px 2px 12px -4px rgba(0, 0, 0, 0.08);

    >ul {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      padding: 20px;

      >li {
        width: 50%;
        height: 3vh;
        color: #000;
        font-size: 15px;
      }
    }
  }

  .examtx {
    margin-top: 10px;
    background-color: #eeeeee;
    display: flex;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid #ccc;
    box-shadow: 0px 2px 12px -4px rgba(0, 0, 0, 0.08);

    .txbox {
      color: #000;
      font-size: 15px;
      font-weight: 400;
    }

    .cout {
      color: #000;
      font-size: 13px;
    }
  }

  .exambox {
    background-color: #fff;
    padding: 0 20px;

    .content {
      display: block;
      font-size: 16px;
      line-height: 22px;
      padding-top: 10px;

      .qtype {
        color: var(--el-color-primary);
        font-size: 18px;
        font-weight: 500;
        margin-right: 11px;
      }
    }

    .answer_area {
      margin-top: 10px;

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

  .btns {
    width: 100%;
    padding-bottom: 5px;
    padding-right: 30px;
    text-align: right;
  }




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

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

  padding-right: 20px;
  overflow-y: scroll;
  border-right: 1px solid var(--el-color-primary);
}

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

.right {
  width: 300px;
  height: 70vh;
  padding: 0 20px;
  overflow: auto;

  .right_item {
    margin-bottom: 15px;

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

      .listItem {
        display: block;
        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;
        }
      }
    }
  }

}
</style>
