<template>
  <el-upload
      action="#"
      :id="uuid"
      class="upload-demo my-upload-file"
      :class="fileList.length>0&&!loading?'success-file':''"
      :multiple="multiple"
      ref="uploadRef"
      :disabled="loading?true:self_disabled"
      :http-request="handleHttpUpload"
      :file-list="fileList"
      :on-preview="onPreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :show-file-list="showFileList"
      :drag="isBtn?false:true"
      :limit="limit"
  >
    <template v-if="isBtn">
      <el-tooltip
          v-if="isBtn&&btnTip"
          class="box-item"
          effect="dark"
          :content="btnTip"
          placement="top"
      >
        <el-button icon="Upload" type="primary">点击上传</el-button>
      </el-tooltip>
      <el-button v-else icon="Upload" type="primary">点击上传</el-button>
    </template>
    <template v-else>
      <el-icon class="el-icon--upload">
        <Finished style="color: var(--el-color-success)" v-if="fileList.length>0&&!loading"/>
        <upload-filled v-else/>
      </el-icon>
      <div v-if="!self_disabled" class="el-upload__text">{{loading?'上传中':(fileList.length>0?'上传成功':'点击或将文件拖拽到这里上传')}}</div>
    </template>
    <template #tip>
      <template v-if="!isBtn">
        <div v-if="props.fileType" class="el-upload__tip">支持扩展名：{{ props.fileType }}</div>
        <div v-if="props.multiple && props.limit" class="el-upload__tip">最多上传{{props.limit}}个文件</div>
      </template>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { computed,ref} from "vue";
import {ElNotification, UploadFile, UploadInstance} from "element-plus";
import type {UploadProps, UploadRequestOptions} from "element-plus";
import {generateUUID} from "@/utils/auth";

const uploadRef = ref<UploadInstance>();
import {upload} from '@/api/common'

// 接受父组件参数
const props = defineProps({
  zIndex: {
    default: -1
  },
  multiple: {
    type: Boolean,
    default: false
  },
  isBtn: {
    type: Boolean,
    default: false
  },
  showFileList: {
    type: Boolean,
    default: true
  },
  btnTip: {
    type: String,
    default: ''
  },
  limit: {
    type: Number,
    default: undefined
  },
  fileList: {
    type: Array,
    required: true,
    default: []
  },
  disabled: {
    default: false
  },
  fileSize: {
    default: 200
  },
  orderNo: {
    default: ''
  },
  fileType: {
    default: ""
  },
  name: {
    default: ""
  }
});

// 生成组件唯一id
const uuid = ref("id-" + generateUUID());

// 判断是否禁用上传和删除
const self_disabled = computed(() => {
  return props.disabled;
});


const emit = defineEmits(["upload"]);

const loading = ref(false);
const handleHttpUpload = async (options: UploadRequestOptions) => {

  loading.value = true;
  try {
    const formData = new FormData()
    formData.append('file',options.file)
    formData.append('name',props.name)
    const res =await upload(formData)
    if(props.multiple){
      let list=JSON.parse(JSON.stringify(props.fileList))
      list.push({
        url: res.fileUrl,
        name: res.originalName,
        filePath: res.fileUrl,
        fileName:  res.originalName,
      })
      emit('upload', list,props.zIndex)
    }else{
      emit("upload", res.fileUrl,res.originalName,props.zIndex);
    }
  } catch (error) {
    ElNotification({
      title: "温馨提示",
      message: "上传文件失败！",
      type: "error"
    });
    if(props.multiple){
      emit('upload', props.fileList,props.zIndex)
    }else{
      uploadRef.value!.clearFiles();
      emit("upload", "", "",props.zIndex);
    }
    options.onError(error as any);
  } finally {
    loading.value = false;
  }
};

const onPreview=(uploadFile: UploadFile)=> {
  window.open( uploadFile?.url)
}

const handleRemove: UploadProps["onRemove"] = (file:any) => {
  if(props.multiple){
    emit("upload",props.fileList.filter((f) => !(f === file.url)),props.zIndex)
  }else{
    uploadRef.value!.clearFiles();
    emit("upload", "", "", props.zIndex);
  }
};

/**
 * @description 文件上传之前判断
 * @param rawFile 选择的文件
 * */
const beforeUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;
  if (!imgSize) {
    ElNotification({
      title: "温馨提示",
      message: `上传文件大小不能超过 ${props.fileSize}M！`,
      type: "warning"
    });
    return false;
  }
  if( props.fileType){
    let fileType = props.fileType.replace(/\s/g, "");
    fileType.split('.').join('|')
    let fileIndex = rawFile.name.lastIndexOf('.')
    let substrName = rawFile.name.substr(fileIndex)
    if (fileType.indexOf(substrName)==-1) {
        ElNotification({
          title: "温馨提示",
          message: "上传文件不符合所需的格式！",
          type: "warning"
        });
      return false;
    }
  }
  return true;
};


</script>
<style lang="scss">
.success-file {
  .el-upload {
    .el-upload-dragger {
      border-width: 3px;
      border-color: var(--el-color-success) !important;
    }
  }
}

.my-upload-file{
  .el-upload-dragger{
    padding: var(--el-upload-dragger-padding-vertical);
  }
  .el-upload-list__item.is-success.el-list-leave-active.el-list-leave-to{
    display: none;
  }
  .el-icon--close-tip{
    display: none!important;
  }
}
.el-form-item.is-error{
  .el-upload-dragger {
    border-width: 3px;
    border-color: var(--el-color-error) !important;
  }
}
</style>
