<template>
  <el-upload
    ref="imageRef"
    :file-list="files"
    :show-file-list="false"
    :limit="max"
    :action="FILE_UPLOAD"
    :auto-upload="false"
    :on-exceed="exceed"
    :on-change="handleChange"
  >
    <template #trigger>
      <div>
        <slot></slot>
      </div>
    </template>
  </el-upload>
</template>
<script setup>
import { defineProps, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { computed } from "vue";
import { useStore } from "vuex";
import { FILE_UPLOAD } from "@/api/api";

const store = useStore();
const userInfo = computed(() => store.state.userInfo);

const props = defineProps({
  value: [],
  max: {
    type: Number,
    default: 1,
  },
});

const emit = defineEmits();
const files = ref([]);
const imageRef = ref();

watch(props.value, () => {
  props.value.length || (files.value = props.value);
});

function exceed() {
  ElMessage.error(`只能上传${props.max}个附件`);
}

function handleChange(file) {
  let fileName =
    userInfo.value.realName + "-" + userInfo.value.userNo + "-" + file.name;
  let f = new File([file.raw], fileName);
  f.uid = file.uid;
  file.raw = f;
  console.log(file.raw);
  if (file.raw.name.includes(".mp4") || file.raw.name.includes(".MP4")) {
    files.value = [];
    emit("update:fileList", files.value);
    ElMessage.error(`暂不支持视频文件上传`);
    return;
  } else if (
    file.raw.name.includes(".jpeg") ||
    file.raw.name.includes(".JPEG")
  ) {
    files.value = [];
    emit("update:fileList", files.value);
    ElMessage.error(`暂不支持jpeg格式图片文件上传`);
    return;
  } else {
    imageRef.value.submit();

    if (file.response && file.response.code === 200) {
      file.url = file.response.data;
    }
    console.log("files.value", files.value);
    const index = files.value.findIndex((f) => f.uid === file.uid);
    if (index === -1) {
      files.value.unshift(file);
    } else {
      files.value[index] = file;
    }
    console.log("files.value22", files.value);
    emit("update:fileList", files.value);
  }
}

function remove(i) {
  files.value.splice(i, 1);
  console.log(imageRef);
}

function clearFiles() {
  imageRef.value.clearFiles();
}

function reUpload(i) {
  if (
    files.value[i].status === "ready" ||
    files.value[i].status === "uploading"
  ) {
    imageRef.value.abort(files.value[i].raw);
    files.value[i].status = "abort";
  } else if (
    files.value[i].status === "fail" ||
    files.value[i].status === "abort"
  ) {
    imageRef.value.handleStart(files.value[i].raw);
    imageRef.value.submit();
  }
}

function abort(i) {
  imageRef.value.abort(files.value[i].raw);
}

defineExpose({ reUpload, remove, clearFiles });
</script>
