<template>
  <div v-if="hasTask" class="audit intime">
    <div class="audit-head">
      <a-row>
        <a-col :span="6">
          <span class="head-label">扫描员：</span>
          <span class="head-cont">{{ batchInfo.device }}</span>
        </a-col>
        <a-col :span="6">
          <span class="head-label">批次：</span>
          <span class="head-cont">{{ batchInfo.batchId }}</span>
        </a-col>
        <a-col :span="6">
          <span class="head-label">时间：</span>
          <span class="head-cont">{{ dateFormat(batchInfo.createTime) }}</span>
        </a-col>
        <a-col :span="6">
          <span class="head-label">卷袋编号：</span>
          <span class="head-cont">{{ batchInfo.packageCode }}</span>
        </a-col>
      </a-row>
    </div>
    <div class="intime-side">
      <div class="intime-side-body">
        <div class="task-list">
          <ul class="list-head">
            <li style="width: 150px">准考证号</li>
            <li style="width: 80px">姓名</li>
            <li style="width: 60px">座位号</li>
            <li style="width: 50px">状态</li>
          </ul>
          <div class="list-body">
            <ul
              v-for="(item, index) in dataList"
              :key="item.examNumber"
              :class="[
                'list-row',
                { 'is-active': curStudent?.examNumber === item.examNumber },
              ]"
              @click="setCurStudent(index)"
            >
              <li style="width: 150px">{{ item.examNumber }}</li>
              <li style="width: 80px">{{ item.name }}</li>
              <li style="width: 60px">{{ item.seatNumber }}</li>
              <li style="width: 50px">
                <CheckCircleFilled v-if="item.status" class="color-success" />
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="intime-side-foot">
        <a-space :size="7">
          <template #split>
            <a-divider
              type="vertical"
              style="height: 22px; background-color: #d9d9d9"
            />
          </template>
          <a-button
            type="success"
            :disabled="canSubmit"
            :loading="loading"
            @click="onConfirm(true)"
          >
            <template #icon><CheckCircleOutlined /></template>
            通过
          </a-button>
          <a-button
            type="error-light"
            :loading="loading"
            @click="onConfirm(false)"
          >
            <template #icon><CloseCircleOutlined /></template>
            拒绝
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="audit-body">
      <template v-if="curStudent">
        <div class="audit-body-imgs">
          <div v-for="paper in curStudent.papers" :key="paper.number">
            <img
              v-for="(page, pindex) in paper.pages"
              :key="pindex"
              class="paper-img"
              :src="getFileUrl(page)"
            />
          </div>
        </div>
        <ReviewMarkPan
          :task-info="{
            examNumber: curStudent.examNumber,
            name: curStudent.name,
          }"
          @mark="onMark"
        />
      </template>
    </div>
  </div>
  <div v-else class="audit is-wait">
    <div>
      <img src="@/assets/imgs/bg-wait.png" alt="等待" />
      <p>等待审核结果…</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed } from "vue";
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  CheckCircleFilled,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { omit } from "lodash-es";

import {
  AuditBatchResult,
  AuditBatchStudent,
  AuditBatchData,
} from "@/ap/types/audit";
import {
  intimeAuditBatch,
  intimeAuditBatchSubmit,
  intimeAuditBatchRelease,
} from "@/ap/audit";
import { useUserStore } from "@/store";
import { dateFormat, getFileUrl } from "@/utils/tool";
import useLoop from "@/hooks/useLoop";

import ReviewMarkPan from "../../Review/ReviewMarkPan.vue";
import useLoading from "@/hooks/useLoading";

defineOptions({
  name: "IntimeAudit",
});

const userStore = useUserStore();

interface StudentItem extends AuditBatchStudent {
  status: boolean;
}

const dataList = ref<StudentItem[]>([]);
const curStudent = ref<StudentItem | null>(null);
const curStudentIndex = ref(0);
const batchInfo = ref({} as AuditBatchData);
const hasTask = ref(false);

const canSubmit = computed(() => {
  return !dataList.value.some((item) => !item.status);
});

function initData() {
  dataList.value = [];
  curStudent.value = null;
  curStudentIndex.value = 0;
  batchInfo.value = {};
  hasTask.value = false;
}

const { start: startLoopGetData, stop: stopLoopGetData } = useLoop(
  getData,
  2000
);
async function getData() {
  const res = await intimeAuditBatch({ examId: userStore.curExam.id });
  if (!res) {
    hasTask.value = false;
    return;
  }
  stopLoopGetData();
  hasTask.value = true;
  batchInfo.value = omit(res, "students");
  dataList.value = res.students || [];
  setCurStudent(0);
}

function onMark() {
  curStudent.value.status = true;
  getNextStudent();
}

// task
function setCurStudent(index: number) {
  curStudentIndex.value = index;
  curStudent.value = dataList.value[curStudentIndex.value];
}
function getNextStudent() {
  if (curStudentIndex.value === dataList.value.length - 1) return;

  setCurStudent(++curStudentIndex.value);
}
function getPrevStudent() {
  if (curStudentIndex.value === 0) return;

  setCurStudent(--curStudentIndex.value);
}

// confirm
const { loading, setLoading } = useLoading();
async function onConfirm(confirm: boolean) {
  if (loading.value) return;
  setLoading(true);
  const res = await intimeAuditBatchSubmit({
    batchId: batchInfo.value.batchId,
    confirm,
  }).catch(() => {});
  setLoading(false);
  if (!res) return;

  message.success("操作成功！");
  initData();
  startLoopGetData();
}

async function releaseBatch() {
  await intimeAuditBatchRelease({ examId: userStore.curExam.id });
}

onBeforeUnmount(() => {
  releaseBatch();
  stopLoopGetData();
});

onMounted(async () => {
  await releaseBatch();
  startLoopGetData();
});
</script>
