<template>
  <syCommonDialog
    :visible="visible"
    type="element"
    :elementDialogProps="{
      title: '增加藏品',
    }"
    showMask
    elementDialogSize="medium"
    @closePopup="$emit('update:visible', false)"
  >
    <HandleAllKindsOfType
      type="uploadAlbum"
      :file="file"
      @upload="upload"
      @clear="clear"
      @cancelUpload="clear"
      :uploadPercent="percent"
    ></HandleAllKindsOfType>
    <div class="tip" style="margin-top: 20px">
      提示：系统根据您的文件名生成数字产品编号，一旦上传无法修改。
    </div>
    <syButton
      mode="elementBtn"
      type="primary"
      style="width: 100%; height: 40px; margin-top: 50px; margin-bottom: 42px"
      :disabled="!file || percent < 1 || isDone === false"
      @click="handleClickConfirm"
      >确定</syButton
    >
  </syCommonDialog>
</template>

<script setup lang="ts">
/**
 * @description: 增加藏品弹出框，用于专辑详情中的文件上传
 */
import { syCommonDialog, syButton } from "cqk-sy-ui";
import HandleAllKindsOfType from "@/components/HandleAllKindsOfType/index.vue";
import { ref, watch } from "vue";
import { handleBigFileUpload } from "@/service/Upload";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";

const props = defineProps<{
  visible: boolean;
}>();
const route = useRoute();

watch(
  () => props.visible,
  () => {
    if (props.visible) {
      file.value = null;
      percent.value = 0;
    } else {
      clear();
    }
  }
);

const file = ref<File | null>(null);
const percent = ref(0);
const uploadedRef = ref<null | Awaited<
  ReturnType<typeof handleBigFileUpload>
> | null>(null);
const isDone = ref(false);
const isSubmitting = ref(false);

const emit = defineEmits(["update:visible", "uploaded"]);

const upload = async (f: File) => {
  file.value = f;
  percent.value = 0;
  const res = await handleBigFileUpload(
    f,
    (p) => {
      percent.value = p;
    },
    () => {
      isDone.value = true;
    }
  );
  uploadedRef.value = res;
};

const clear = () => {
  file.value = null;
  uploadedRef.value?.cancelUpload && uploadedRef.value?.cancelUpload();
  uploadedRef.value = null;
  percent.value = 0;
  isDone.value = false;
};

const handleClickConfirm = async () => {
  if (isSubmitting.value) return;
  isSubmitting.value = true;

  await uploadedRef.value?.unzip(Number(route.query.id));
  emit("update:visible", false);
  emit("uploaded");
  isSubmitting.value = false;
  ElMessage.success("上传成功");
};
</script>

<style scoped lang="scss">
@mixin tip {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  line-height: 20px;
}

.tip {
  @include tip;
  color: #565656;
}
</style>
