<template>
  <div v-if="curStudent" class="slice-image">
    <div v-for="item in curStudent.papers" :key="item.id" class="image-paper">
      <div
        v-for="(page, pindex) in item.pages"
        :key="pindex"
        class="image-page"
      >
        <template v-if="page.sliceUri">
          <h3 class="image-page-title">
            {{ getPageTitle(item.number, pindex) }}
          </h3>
          <div
            v-for="(url, sindex) in page.sliceUri"
            :key="sindex"
            class="image-item"
          >
            <img :src="getFileUrl(url)" :alt="`${sindex + 1}`" />
            <div class="image-action">
              <import-btn
                upload-url="/api/admin/scan/answer/slice/update"
                :format="['jpg', 'png', 'jpeg']"
                :upload-data="curSliceInfo"
                @upload-success="updateSliceSuccess"
              >
                <a-tooltip placement="top">
                  <template #title>
                    <span>替换图片</span>
                  </template>
                  <a-button
                    class="image-change"
                    @click="onUpdateSlice(item.number, pindex, sindex)"
                  >
                    <template #icon><PictureFilled /></template>
                  </a-button>
                </a-tooltip>
              </import-btn>
              <a-button
                class="image-slice"
                @click="onEditSlice(item.number, pindex, sindex)"
              >
                <template #icon><NumberOutlined /></template>
              </a-button>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>

  <!-- CutImageDialog -->
  <CutImageDialog
    ref="cutImageDialogRef"
    :sheet-url="curSliceInfo.sheetUri"
    :slice-selection="curSliceSelection"
    @confirm="cutImageModified"
  />
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { NumberOutlined, PictureFilled } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";

import { uploadSlice, cardInfo } from "@/ap/base";
import { CardContent, CardPage } from "@/ap/types/base";
import { getFileMD5 } from "@/utils/crypto";
import { useDataCheckStore, useUserStore } from "@/store";
import { getFileUrl } from "@/utils/tool";

import CutImageDialog from "./CutImageDialog.vue";
import ImportBtn from "@/components/ImportBtn/index.vue";
import axios from "axios";

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

const userStore = useUserStore();
const dataCheckStore = useDataCheckStore();

const curStudent = computed(() => {
  return dataCheckStore.curStudent;
});

const curSliceSelection = ref<AreaSize>();
const curSliceInfo = ref({
  paperIndex: 0,
  paperId: 0,
  pageIndex: 0,
  index: 1, // 注意：这里的index是从1开始的
  sheetUri: "",
});

const cardData = ref<CardPage[]>([]);

function getPageTitle(paperNumber: number, pageIndex: number) {
  return `卡${paperNumber}${pageIndex === 0 ? "正面" : "反面"}`;
}

// 编辑
const cutImageDialogRef = ref();
function onEditSlice(paperNumber: number, pageIndex: number, index: number) {
  const paper = curStudent.value?.papers[paperNumber - 1];
  if (!paper) return;

  curSliceInfo.value = {
    paperIndex: paperNumber - 1,
    pageIndex: pageIndex + 1,
    paperId: paper.id as number,
    index: index + 1,
    sheetUri: paper.pages[pageIndex].sheetUri,
  };
  const paperPageIndex = (paperNumber - 1) * 2 + pageIndex;
  const area = cardData.value[paperPageIndex]?.exchange.answer_area[index].area;
  if (area) {
    curSliceSelection.value = {
      x: area[0],
      y: area[1],
      w: area[2],
      h: area[3],
    };
  } else {
    curSliceSelection.value = undefined;
  }

  cutImageDialogRef.value?.open();
}
async function cutImageModified(file: File) {
  const md5 = await getFileMD5(file);

  const { paperId, pageIndex, index } = curSliceInfo.value;
  const datas = {
    paperId,
    pageIndex,
    index,
    file,
    md5,
  };
  const res = await uploadSlice(datas).catch(() => {});
  if (!res) return;

  dataCheckStore.modifySliceUri({
    ...curSliceInfo.value,
    pageIndex: curSliceInfo.value.pageIndex - 1,
    index: curSliceInfo.value.index - 1,
    uri: res.uri,
  });
}

// 上传
function onUpdateSlice(paperNumber: number, pageIndex: number, index: number) {
  const paper = curStudent.value?.papers[paperNumber - 1];
  if (!paper) return;

  curSliceInfo.value = {
    paperIndex: paperNumber - 1,
    pageIndex: pageIndex + 1,
    paperId: paper.id as number,
    index: index + 1,
    sheetUri: paper.pages[pageIndex].sheetUri,
  };
}

function updateSliceSuccess(data: { uri: string }) {
  dataCheckStore.modifySliceUri({
    ...curSliceInfo.value,
    pageIndex: curSliceInfo.value.pageIndex - 1,
    index: curSliceInfo.value.index - 1,
    uri: data.uri,
  });
  message.success("上传成功！");
}

// 卡格式
async function getCardInfo() {
  if (!dataCheckStore.curStudent) return;

  const res = await cardInfo({
    examId: userStore.curExam.id,
    number: dataCheckStore.curStudent.cardNumber,
  });
  const uri = getFileUrl(res.uri);
  const cardRes = await axios.get(uri);
  cardData.value = (cardRes.data as CardContent).pages;
}

watch(
  () => dataCheckStore.curStudent?.id,
  (val) => {
    if (!val) return;
    getCardInfo();
  },
  { immediate: true }
);
</script>

<style lang="less" scoped>
.slice-image {
  padding: 16px;
  overflow-y: auto;
  overflow-x: hidden;
  height: 100%;

  .image-page {
    &-title {
      font-weight: 500;
      font-size: 14px;
      color: @text-color1;
      line-height: 22px;
      margin-bottom: 8px;
    }
  }
  .image-item {
    margin-bottom: 16px;
    position: relative;
    min-height: 50px;

    img {
      display: block;
      width: 100%;
    }
  }
  .image-action {
    position: absolute;
    top: 12px;
    right: 12px;
    z-index: auto;

    .ant-btn {
      width: 32px;
      height: 32px;
      line-height: 32px;
      padding: 0;
      border-radius: 6px;
      text-align: center;

      &:hover {
        opacity: 0.8;
      }

      &.image-change {
        background: #e8f3ff;
        border: 1px solid #bedaff;
        color: #4080ff;
      }
      &.image-slice {
        background: #e8ffea;
        border: 1px solid #aff0b5;
        color: #23c343;
        margin-left: 6px;
      }
    }
  }
}
</style>
