<template>
  <div class="fileUpload w-full">
    <input
      type="file"
      name=""
      id=""
      ref="inputRef"
      accept=".jpg,.jpeg,.gif,.bmp,.png,.mp4,.wmv,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt"
      class="hidden"
      @change="handleFile"
    />
    <div
      class="uploadBox text-center flex items-center justify-center h-full cursor-pointer"
      @click="modelValue.length <= 4 && inputRef!.click()"
    >
      <div>
        <Icon
          icon-name="iconshangchuan"
          style="font-size: 50px"
          class="mx-auto uploadIcon"
        ></Icon>
        <div>上传作品</div>
      </div>
    </div>
    <div style="margin-top: 18px">
      <FileDisplayItem
        v-for="file in modelValue"
        :key="file.id"
        :file="file"
        style="margin-top: 10px"
        @close="deleteFile(file.id)"
      ></FileDisplayItem>
    </div>
    <div class="request" style="margin-top: 32px">
      上传要求：<br />
      1、上传的作品必须包含您存证过的作品<br />
      2、单文件大小不超过200M，最多上传5个文件
      <br />
      3、支持文件格式，分别如下： <br />
      图片类：JPG、JPEG、GIF、BMP、PNG；<br />
      视频类：MP4、WMV；<br />
      音频类：MP3、WAV； <br />
      文件类：DOC、DOCX、XLS、XLSX、PPT、PPTX、PDF、 TXT。
    </div>
  </div>
</template>

<script setup lang="ts">
import Icon from "@/components/Icon/index.vue";
import { nextTick, ref } from "vue";
import { iFile } from "./types";
import FileDisplayItem from "./FileDisplayItem.vue";
import { fileTypeChecked } from "@/utils/file";
import { ElMessage, useFormItem } from "element-plus";
const props = defineProps<{
  modelValue: (iFile & { id: number })[];
}>();
const emit = defineEmits(["update:modelValue"]);

const formItem = useFormItem();

let id = 1;

const setState = (value: (iFile & { id: number })[]) => {
  emit("update:modelValue", value);
};

const addFile = (value: iFile & { id: number }) => {
  // 添加文件
  setState([...props.modelValue, value]);
};

const deleteFile = (id: number) => {
  // 删除文件
  setState(props.modelValue.filter((i) => i.id !== id));
  console.log("blur");
  nextTick(() => {
    formItem.formItem?.validate("blur");
  });
  //   取消文件上传??????
  // cancelUpload();
};

const uploadFileToServer = (file: File, id: number) => {
  // 上传文件??????
  let p = 0;
  const s = setInterval(() => {
    p += 0.1;
    updateFile(id, {
      progress: p >= 1 ? 1 : p,
    });
    p >= 1 && clearInterval(s);
  }, 1000);
};

const updateFile = (id: number, value: Partial<iFile & { id: number }>) => {
  // 更新文件
  const list = [...props.modelValue];
  const file = list.find((i) => i.id === id);
  if (!file) return;
  Object.keys(value).forEach((keyOfValue) => {
    (file as any)[keyOfValue] = (value as any)[keyOfValue];
  });
  setState(list);
};

const inputRef = ref<HTMLInputElement>();
const handleFile = (e: Event) => {
  const files = (e.target as HTMLInputElement).files;
  if (!files || files?.length === 0) return;
  const file = files[0];
  if (!fileTypeChecked(file, inputRef.value!.accept)) {
    ElMessage.error("请上传指定类型的文件");
    return;
  }
  addFile({
    id: ++id,
    file: file,
    name: file.name,
    size: file.size,
    url: "",
    progress: 0,
  });
  uploadFileToServer(file, id);
  inputRef.value!.value = "";
  nextTick(() => {
    formItem.formItem?.validate("blur");
  });
};
</script>

<style scoped lang="scss">
.fileUpload {
  .uploadBox {
    height: 158px;
    background: #f7f7f7;
    border-radius: 10px;
    border: 1px dashed #e2e2e2;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: var(--sy-gray-text);
    .uploadIcon {
      color: #c3c3c3;
    }
  }
  .request {
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: var(--text-gray);
  }
}
</style>
