<script setup lang="ts">
import Scoreboard from "./Scoreboard.vue";
import { fileUpload, getUnmarkList, submitManualAnswer } from "@/api";
import { formatTitleToPaper } from "@/utils";
import SignImage from "../CorrectDia/SignImage.vue";
import Question from "@/components/Question";
import CorrectionHistoryDia from "./CorrectionHistoryDia.vue";
import { computed, nextTick, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import correctionOk from "@/assets/images/correction_ok.gif";
import { ElMessageBox } from "element-plus";
import {
  RefreshLeft,
  RefreshRight,
  ZoomIn,
  ZoomOut,
} from "@element-plus/icons-vue";

const props = defineProps<{
  modelValue: boolean;
  data: Record<string, any>;
  jobId: string;
}>();
const emit = defineEmits(["update:modelValue", "close"]);
const show = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  },
});

const titleInfo = reactive({
  submitAnswer: "",
  submitAnswerPic: "",
  markAnswer: "",
  markLoading: false,
  markAnswerPic: "",
});

// 最后一次提交的试题题号
const lastTitleNo = ref(0);
const titleList = ref([]);
const formatTitle = computed(() => ({
  ...(titleList.value.find((i) => i.id === showRecord.value.titleId) || {
    analyze: [],
    analyzePic: [],
  }),
  show: true,
}));
const unList = ref([]);
// 当前批改作业index
const correctionIdx = ref(0);
const showRecord = computed(() => unList.value[correctionIdx.value] || {});
watch(
  showRecord,
  (val) => {
    titleInfo.submitAnswer = val.submitAnswer;
    titleInfo.submitAnswerPic = val.submitAnswerPic;
    titleInfo.markLoading = false;
  },
  {
    deep: true,
    immediate: true,
  }
);
async function getData() {
  const res = await getUnmarkList({ jobId: props.jobId });
  correctionIdx.value = 0;
  unList.value = res.data || [];

  const picList: string[] = [];
  unList.value.forEach((i) => {
    picList.push(...(i.submitAnswerPic?.split(",") || []));
  });
  preloadPic(picList);
}

async function handleOpen() {
  try {
    await getData();
    isOk.value = unList.value.length > 0 ? false : true;
    isCheck.value = false;
    titleInfo.markAnswer = "";
    titleInfo.markAnswerPic = "";
    const list: any[] = [];
    props.data.content?.forEach((i: any) => {
      list.push(...(i.children || []));
    });
    titleList.value = list;
  } catch (err) {
    console.log(err);
  }
}
// 预加载图片
async function preloadPic(list: string[]) {
  for (const i of list) {
    await loadPic(i);
  }
}

function loadPic(src: string) {
  return new Promise((resolve) => {
    const img = new Image();
    img.src = src;
    img.onload = () => resolve(img);
    img.onerror = () => resolve(null);
  });
}

// 图片批改
const signImageDia = reactive({
  show: false,
  src: "",
  data: {},
});
function handleEditPic(src, data) {
  signImageDia.show = true;
  signImageDia.src = src;
  signImageDia.data = data;
}
// 图片批注结果
async function onSave(file, info) {
  info.markLoading = true;
  try {
    const res = await fileUpload({ file });
    info.markAnswerPic = `${info.markAnswerPic || ""}${
      info.markAnswerPic ? "," : ""
    }${res.data.url}`;
  } finally {
    info.markLoading = false;
  }
}
// 删除图片批注
async function handleDel(idx, info) {
  info.markAnswerPic = info.markAnswerPic
    .split(",")
    .filter((i, index) => index !== idx)
    .join(",");
}

const showTitle = ref(false);
function onAnalysis() {
  showTitle.value = !showTitle.value;
}

// 查看历史记录
const correctionHistoryDia = reactive({
  show: false,
});
function handleHistory() {
  correctionHistoryDia.show = true;
}

// 是否批改完成
const isOk = ref(false);
// 提交分数
function onSubmit(score) {
  if (isOk.value) return;
  if (titleInfo.markLoading)
    return ElMessage.warning("图片批改正在上传，请稍后再试");

  try {
    submitManualAnswer([
      {
        answerScore: score,
        jobStuId: showRecord.value.jobStuId,
        id: showRecord.value.jobStuTittleId,
        markAnswer: titleInfo.markAnswer,
        markAnswerPic: titleInfo.markAnswerPic,
      },
    ]);
    correctionIdx.value++;
    isCheck.value = false;
    showTitle.value = false;
    titleInfo.markAnswer = "";
    titleInfo.markAnswerPic = "";
    if (
      showRecord.value.titleNo &&
      showRecord.value.titleNo !== lastTitleNo.value
    ) {
      //  切换题号了
      showTitle.value = true;
      ElMessageBox.alert(
        `现在开始批改第${showRecord.value.titleNo}题`,
        "温馨提示",
        {
          center: true,
          confirmButtonText: "好的",
        }
      );
    }
    lastTitleNo.value = showRecord.value.titleNo;

    if (correctionIdx.value === unList.value.length) {
      isOk.value = true;
    }
  } catch (err) {
    console.log(err);
  }
}
// 修正批改
const isCheck = ref(false);
async function handleCheck(row) {
  isCheck.value = true;
  isOk.value = false;
  await getData();
  unList.value = [row, ...unList.value];
}
function handleClose() {
  emit("close");
}

const maxScale = 2;
const minScale = 1;
let nowScale = 1;
let nowDeg = 0;
function handleActions(action, id) {
  const el = document.getElementById(id);
  if (!el) return;
  el.style.zIndex = "1000";
  switch (action) {
    case "reset":
      nowScale = 1;
      nowDeg = 0;
      el.style.scale = "unset";
      el.style.transform = "unset";
      el.style.transformOrigin = "unset";
      el.style.zIndex = "unset";
      break;
    case "zoomIn":
      if (nowScale >= maxScale) return;
      el.style.scale = String((nowScale += 0.5));
      el.style.transformOrigin = nowDeg === 0 ? "top" : "center";
      break;
    case "zoomOut":
      if (nowScale <= minScale) return;
      el.style.scale = String((nowScale -= 0.5));
      el.style.transformOrigin = nowDeg === 0 ? "top" : "center";
      break;
    case "anticlockwise":
      el.style.transform = `rotate(${(nowDeg -= 90)}deg)`;
      el.style.transformOrigin = "center";
      break;
    case "clockwise":
      el.style.transform = `rotate(${(nowDeg += 90)}deg)`;
      el.style.transformOrigin = "center";
      break;
  }
}
</script>
<template>
  <el-dialog
    title="批改作业"
    v-model="show"
    fullscreen
    close-on-click-modal
    destroy-on-close
    :close-on-press-escape="false"
    @opened="handleOpen"
    @close="handleClose"
  >
    <el-descriptions class="box" border style="width: 100%" column="4">
      <template v-if="!isOk">
        <el-descriptions-item label="姓名"
          >{{ showRecord.className }}_{{
            showRecord.stuName
          }}</el-descriptions-item
        >
        <el-descriptions-item label="题号"
          >{{ showRecord.titleNo }}
          <el-tag v-if="isCheck" type="success" style="margin: 0 16px"
            >已批改：{{ showRecord.answerScore }}</el-tag
          >
        </el-descriptions-item>
      </template>
      <el-descriptions-item label="待批改数">{{
        isOk ? "已全部批改完毕" : unList.length - correctionIdx
      }}</el-descriptions-item>
      <el-descriptions-item label="操作">
        <el-button v-if="!isOk" type="primary" @click="onAnalysis">{{
          showTitle ? "隐藏解析" : "查看解析"
        }}</el-button>
        <el-button type="primary" @click="handleHistory">批改记录</el-button>
      </el-descriptions-item>
    </el-descriptions>
    <template v-if="isOk">
      <div class="correction-ok">
        <img :src="correctionOk" mode="scaleToFill" />
      </div>
    </template>
    <template v-else>
      <div class="content">
        <div class="left">
          <div class="subjective-ques">
            <div class="pic-list">
              <div v-if="titleInfo.submitAnswer" class="pic-box">
                {{ titleInfo.submitAnswer }}
              </div>
              <div v-if="titleInfo.submitAnswerPic" class="pic-box">
                <div
                  v-for="(pic, idx) in titleInfo.submitAnswerPic.split(',')"
                  class="pic"
                >
                  <el-image
                    :id="`pic-${idx}`"
                    style="width: 100%; height: auto"
                    :src="pic"
                    fit="cover"
                    :preview-src-list="[pic]"
                    @click="handleActions('reset', `pic-${idx}`)"
                  />
                  <div class="actions">
                    <el-icon @click="handleActions('zoomOut', `pic-${idx}`)">
                      <ZoomOut />
                    </el-icon>
                    <el-icon @click="handleActions('zoomIn', `pic-${idx}`)">
                      <ZoomIn />
                    </el-icon>
                    <el-icon
                      @click="handleActions('anticlockwise', `pic-${idx}`)"
                    >
                      <RefreshLeft />
                    </el-icon>
                    <el-icon @click="handleActions('clockwise', `pic-${idx}`)">
                      <RefreshRight />
                    </el-icon>
                  </div>
                </div>
              </div>
              <div v-if="!titleInfo.submitAnswer && !titleInfo.submitAnswerPic">
                未作答
              </div>
            </div>
            <!-- <div class="pic-list">
              <div style="width: 100%">
                <div>老师批语：</div>
                <el-input
                  v-model="titleInfo.markAnswer"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入"
                  style="margin: 16px 0"
                />
              </div>
              <div v-loading="titleInfo.markLoading" class="pic-box">
                <template v-if="titleInfo.markAnswerPic">
                  <div
                    v-for="(pic, idx) in titleInfo.markAnswerPic.split(',')"
                    class="pic"
                  >
                    <el-image
                      style="width: 100%; height: auto"
                      :src="pic"
                      fit="cover"
                      :preview-src-list="titleInfo.markAnswerPic.split(',')"
                    />
                    <el-icon
                      color="#F56C6C"
                      size="28"
                      @click.stop="handleDel(idx, titleInfo)"
                    >
                      <Delete />
                    </el-icon>
                  </div>
                </template>
              </div>
            </div> -->
            <Question
              v-if="showTitle"
              :data="formatTitle"
              :index="formatTitle.qNo"
              :showMore="false"
            />
          </div>
        </div>
        <div class="right">
          <Scoreboard :maxScore="showRecord.titleScore" @submit="onSubmit" />
        </div>
      </div>
    </template>

    <SignImage
      v-model="signImageDia.show"
      :src="signImageDia.src"
      :data="signImageDia.data"
      @onSave="onSave"
    ></SignImage>
    <CorrectionHistoryDia
      v-model="correctionHistoryDia.show"
      :jobId="props.jobId"
      @check="handleCheck"
    />
  </el-dialog>
</template>
<style lang="scss" scoped>
.box {
  --el-font-size-base: 18px;
  :deep(.el-descriptions__body) {
    td {
      font-size: 18px;
    }
  }
}
.content {
  margin-top: 16px;
  display: flex;
  font-size: 18px;
  .left {
    width: 60%;
    margin-right: 16px;
    .questions-item {
      border: 1px solid #e5e5e5;
      border-radius: 10px;
    }
    .subjective-ques {
      margin-top: 16px;
      .pic-list {
        display: flex;
        flex-wrap: wrap;
        padding: 18px;
        .pic-box {
          margin-left: 5px;
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          justify-content: center;
          // display: grid;
          // align-items: center;
          // grid-template-columns: repeat(auto-fill, 400px);
          // grid-template-rows: auto;
          gap: 16px;
        }
        .pic {
          width: 400px;
          height: auto;
          cursor: pointer;
          position: relative;
          border: 1px solid #e5e5e5;
          margin-top: 40px;
          img {
            width: 100%;
            height: 100%;
            object-fit: fill;
          }
          // &:hover {
          //   .el-icon {
          //     opacity: 1;
          //     visibility: visible;
          //   }
          // }
          // .el-icon {
          //   position: absolute;
          //   top: 50%;
          //   left: 50%;
          //   transform: translate(-50%, -50%);
          //   background: #fcd3d3;
          //   border-radius: 50%;
          //   padding: 4px;
          //   opacity: 0;
          //   visibility: hidden;
          //   transition: all 0.3s ease-in-out;
          // }

          .actions {
            width: 200px;
            height: 40px;
            position: absolute;
            top: -40px;
            left: 50%;
            transform: translateX(-50%);
            text-align: center;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 10px;
            z-index: 1001;
            .el-icon {
              width: 40px;
              height: 40px;
              color: #fff;
            }
          }
        }
      }
    }
  }
  .right {
    flex-shrink: 0;
  }
}
.correction-ok {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 100px;
}
</style>
