<template>
  <div class="wp">
    <div class="wp">
      <div class="hd">
        <div class="logo"><img src="img/logo.png" /></div>
        <span class="y">
          欢迎您，<span id="user-name"></span> <span class="pipe">|</span
          ><a href="##">退出</a>
        </span>
      </div>
      <div class="cont">
        <div class="title title_grey cl">
          <h2>数据同步中 …</h2>
        </div>
        <div class="progress-box">
          <h3 id="message">{{ status }}</h3>
          <div class="progress">
            <!-- <div class="progress-outer">
              <div id="progress" class="progress-inner" style="width: 0%">
                <span class="progress-text"></span>
              </div>
            </div> -->
            <a-progress
              :percent="Math.round((finishCount / totalCount) * 100)"
            />
          </div>
          <p>
            已数据同步考生：<b id="finish-count">{{ finishCount }}</b> /
            全部考生：<b id="total-count">{{ totalCount }}</b>
          </p>
        </div>
      </div>
      <div class="ft">
        Copyright © 2011-2020 www.qmth.com.cn, All Rights Reserved
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { store } from "@/store";
import { onMounted, ref } from "vue";
import { Modal } from "ant-design-vue";
import { useRouter } from "vue-router";
import { getStudents, countStudents, getPackages } from "@/api/api";

const router = useRouter();
console.log(router);
let status = ref("");

let finishCount = ref(0);
let totalCount = ref(0);
let finished = ref(false);
onMounted(async () => {
  try {
    status.value = "正在计算总数...";
    const res = await countStudents(store.env.examId);
    totalCount.value = res.data;

    let pageNumber = 0;

    status.value = "正在下载考生...";
    // eslint-disable-next-line
    while (true) {
      pageNumber++;
      const array = (
        await getStudents(store.env.examId, pageNumber, 100, {
          withScoreDetail: true,
        })
      ).data;
      if (array == undefined || array.length == 0) {
        break;
      }
      const datas = [];
      for (let i = 0; i < array.length; i++) {
        const obj = array[i];
        var objList = [];
        var subList = [];
        if (obj.objectiveScoreDetail) {
          obj.objectiveScoreDetail.forEach((detail) => {
            const score = Math.round((detail.score * 10) / 10);
            objList.push(detail.answer + ":" + score);
          });
        }
        if (obj.subjectiveScoreDetail) {
          obj.subjectiveScoreDetail.forEach((detail) => {
            const score = Math.round((detail.score * 10) / 10);
            subList.push(score);
          });
        }
        datas.push([
          obj["id"],
          store.env.examId,
          obj["schoolId"],
          obj["examNumber"],
          obj["examNumber"],
          obj["name"],
          obj["studentCode"],
          obj["subjectCode"],
          obj["subjectName"],
          obj["campusName"],
          obj["packageCode"],
          obj["batchCode"],
          obj["sheetCount"],
          obj["sliceCount"],
          obj["answers"],
          obj["upload"] ? 1 : 0,
          obj["absent"] ? 1 : 0,
          obj["breach"] ? 1 : 0,
          obj["manualAbsent"] ? 1 : 0,
          obj["objectiveScore"].length > 0 ? obj["objectiveScore"] : 0,
          obj["subjectiveScore"].length > 0 ? obj["subjectiveScore"] : 0,
          objList.join(";"),
          subList.join(";"),
          obj["subjectiveStatus"] || "UNMARK",
          obj["examSite"],
          obj["examRoom"],
          obj["remark"],
          obj["college"] || "",
          obj["className"] || "",
          obj["teacher"] || "",
          obj["paperType"] || "",
        ]);
      }
      console.log("get:" + array.length);
      await window.electron.replaceStudents(datas);
      finishCount.value += array.length;
    }

    status.value = "正在下载签到表...";
    //get and save package
    const packages = (await getPackages(store.env.examId)).data;
    const packageData = [];
    for (let i = 0; i < packages.length; i++) {
      const obj = packages[i];
      packageData.push([store.env.examId, obj["code"], obj["picCount"]]);
    }
    await window.electron.replacePackage(packageData);

    finished.value = true;
    status.value = "数据同步完成";

    // config.updateSyncTime()

    const modal = Modal.success();
    modal.update({
      title: "数据同步完成",
      content: "完成",
      onOk: () => router.back(),
    });
  } catch (error) {
    const modal = Modal.error();
    console.log(error);
    modal.update({
      title: "数据同步出错",
      content: error.message || error,
      onOk: () => router.back(),
    });
  }
});
</script>
