<script setup lang="ts">
import VueQrcode from "@chenfengyuan/vue-qrcode";
import draggable from "vuedraggable";
import "viewerjs/dist/viewer.css";
import Viewer from "viewerjs";
import { watch } from "vue";
import { store } from "@/store/store";
import { Eye, TrashOutline, Checkmark } from "@vicons/ionicons5";

const props = defineProps<{
  defaultList: string[];
  qrValue: string;
  pictureAnswer?: { order: number; fileUrl: string };
  uploadModalVisible: boolean;
}>();

const emit = defineEmits<{
  (e: "update:uploadModalVisible", v: boolean): void;
  (e: "on-photos-reseted", v: string[]): void;
  (e: "on-photo-removed", v: string): void;
}>();

let uploadList: string[] = $ref([]);

watch(
  () => props.defaultList,
  () => (uploadList = [...props.defaultList])
);

let uploadModalVisible = $ref(false);
let totalList: string[] = $ref([]);
const order = store.exam.currentQuestion.order;

let uploaded = $ref(false);
let qrScanned = $ref(false);

watch(
  () => props.pictureAnswer,
  (value) => {
    uploaded = true;
    if (value?.order === order) {
      totalList.push(...[...new Set(value.fileUrl.split(","))]);
    }
  }
);

watch(
  () => uploadModalVisible,
  () => emit("update:uploadModalVisible", uploadModalVisible)
);

watch(
  () => store.exam.questionQrCodeScanned,
  () => {
    if (store.exam.questionQrCodeScanned.order === order) {
      qrScanned = true;
    }
  }
);

let drag = $ref(false);

function handleView(imagesClass: string, index: number) {
  const viewer = new Viewer(<HTMLElement>document.querySelector(imagesClass), {
    container: "#app",
    zIndex: 99999,
    title: false,
    toolbar: {
      zoomIn: 1,
      zoomOut: 1,
      oneToOne: 1,
      reset: 1,
      prev: 1,
      play: { show: 0, size: "large" },
      next: 1,
      rotateLeft: 1,
      rotateRight: 1,
      flipHorizontal: 1,
      flipVertical: 1,
    },
    ready() {
      viewer.view(index);
    },
    hidden() {
      viewer.destroy();
    },
  });
  viewer.show();
}
function handleRemove(file: string) {
  emit("on-photo-removed", file);
}
function handleRemoveTotal(file: string) {
  totalList.splice(totalList.indexOf(file), 1);
}
function modalCloseClicked() {
  // 在二维码被扫描，文件没得到之前，提示是否关闭。
  if (qrScanned && !uploaded) {
    $dialog.warning({
      title: "确认关闭？",
      content:
        "检测到二维码被扫描，但是图片未上传。关闭此窗口后，将不再接受小程序图片上传。",
      positiveText: "确定关闭",
      negativeText: "取消关闭",
      onPositiveClick: () => {
        uploadModalVisible = false;
        return true;
      },
      onNegativeClick: () => undefined,
    });
    return;
  } else if (totalList.length > 6) {
    // 检查是否超过6张
    $dialog.warning({
      title: "图片数量超出限制",
      content: "请删除多余的图片，图片总数不应该超过6张",
    });
    return;
  }
  uploadModalVisible = false;
  emit("on-photos-reseted", totalList);
}
function uploadListSort() {
  emit("on-photos-reseted", uploadList);
}
function dragMove(e: any) {
  // console.log(e);
  // 第三方组件没定义
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call
  return !e.dragged.className.includes("plus");
}
function prepareUpload() {
  uploadModalVisible = true;
  qrScanned = false;
  uploaded = false;
  totalList = [...uploadList];
}
</script>

<template>
  <div>
    <draggable
      v-model="uploadList"
      :move="dragMove"
      class="upload-images"
      itemKey="index"
      @update="uploadListSort"
    >
      <template #item="{ element: item, index }">
        <div class="demo-upload-list">
          <img :src="item" />
          <div class="demo-upload-list-cover">
            <n-icon
              :component="Eye"
              size="30"
              @click="handleView('.upload-images', index)"
            />
            <n-icon
              :component="TrashOutline"
              size="20"
              style="position: absolute; top: 1px; right: 0px"
              @click="handleRemove(item)"
            />
          </div>
        </div>
      </template>
      <template #footer>
        <div
          v-if="uploadList.length < 6"
          class="demo-upload-list plus"
          @click="prepareUpload"
        >
          <span
            class="tw-inline-block"
            style="transform: scale(4); padding-bottom: 2px"
            >+</span
          >
        </div>
      </template>
    </draggable>

    <div>
      点击
      <span style="color: blue; font-size: 24px">+</span>
      上传图片(最多上传6张图片)
    </div>

    <n-modal
      :show="uploadModalVisible"
      title="上传图片"
      :maskClosable="false"
      preset="card"
      style="width: 800px"
      @close="modalCloseClicked"
    >
      <div>
        <div v-if="qrValue" style="display: flex">
          <VueQrcode
            :value="qrValue"
            :options="{ width: 200 }"
            :style="{
              margin: '-10px',
              filter: totalList.length >= 6 ? 'blur(10px)' : 'none',
            }"
          />
          <div style="font-size: 24px; margin-top: -5px; margin-left: 20px">
            <div>
              请使用<span style="font-weight: 900; color: #1e90ff">微信</span
              >扫描二维码后，在微信小程序上拍照，并上传文件。<br />
              上传期间，请勿关闭二维码。
            </div>
            <div
              v-if="qrScanned"
              class="tw-flex tw-items-center"
              style="margin-top: 30px; font-size: 30px"
            >
              {{ uploaded ? "已上传" : "已扫描" }}
              <n-icon :component="Checkmark" />
            </div>
          </div>
        </div>
        <div v-else>正在获取二维码...</div>

        <draggable
          v-model="totalList"
          class="total-images"
          itemKey="index"
          @start="drag = true"
          @end="drag = false"
        >
          <template #item="{ element: item, index }">
            <div class="demo-upload-list">
              <img :src="item" />
              <div class="demo-upload-list-cover">
                <n-icon
                  :component="Eye"
                  size="30"
                  @click="handleView('.total-images', index)"
                />
                <n-icon
                  :component="TrashOutline"
                  size="20"
                  style="position: absolute; top: 1px; right: 0px"
                  @click="handleRemoveTotal(item)"
                />
              </div>
            </div>
          </template>
        </draggable>

        <div v-if="totalList.length > 6">* 图片上传最多只支持6张</div>
        <div style="display: flex; justify-content: center">
          <n-button type="success" size="large" @click="modalCloseClicked">
            确认
          </n-button>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<style scoped>
.demo-upload-list {
  display: inline-block;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;

  cursor: move;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.plus {
  font-size: 12px;
  box-shadow: 0 0 1px 1px var(--app-color-text-light);
}
.plus:hover {
  cursor: pointer;
  color: blueviolet;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}

.total-images {
  height: 110px;
}
</style>
