<template>
  <div class="bg-upload" :class="{ 'is-disabled': actionDisabled, 'is-easy': isEasy }">
    <el-upload
      action="/apaas/common/file/upload"
      :data="{
        directory: 'file',
        uniqueCode: false,
      }"
      :limit="limit"
      :http-request="httpRequest"
      :before-upload="handleBeforeUpload"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :disabled="actionDisabled"
      style="max-width: 600px"
      drag
      multiple>
      <!-- <el-button type="primary">
        上传附件
      </el-button>
      <div class="el-upload__tip" slot="tip">
        支持上传{{ fileTypes.join("、") }}，最大{{ fileMaxSize }}M
      </div> -->
      <template v-if="isEasy">
        <el-button type="primary" size="mini">
          <bg-icon :icon="`#${triggerIcon}`" v-if="triggerIcon" style="margin-right: 8px" />
          {{ triggerText }}
        </el-button>
      </template>
      <div class="trigger-content" v-else>
        <div class="trigger-icon">
          <img src="./imgs/ic_updata_cloud.png" />
        </div>
        <p class="trigger-tip" style="text-align: center" v-if="customTips">
          <slot></slot>
        </p>
        <p class="trigger-tip" v-else>
          1.最多允许上传{{ limit }}个附件 <br />
          2.单个附件最大{{ fileMaxSize }}M； <br />
          3.允许上传后缀为传{{ fileTypes.join("、") }} <br />
        </p>
      </div>
      <template v-slot:tip v-if="otherInfo != ''">
        <div class="el-upload__tip" style="color: #909bb6; line-height: 18px">
          {{ otherInfo }}
        </div>
      </template>
    </el-upload>
  </div>
</template>

<script setup>
import { computed, watch, onMounted, reactive, ref, nextTick, toRefs } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  fileTypes: {
    type: Array,
    default: () => ["doc", "docx", "xls", "xlsx", "pdf", "jpg", "jpeg", "png"],
  },
  fileMaxSize: {
    type: Number,
    default: 20, // 单位：M
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  refresh: {
    type: Boolean,
    default: false,
  }, // 是否重新初始化附件（手动刷新组件的附件列表）
  customTips: {
    type: Boolean,
    default: false,
  }, // 是否自定义提示
  isEasy: {
    type: Boolean,
    default: false,
  },
  triggerText: {
    type: String,
    default: "请上传",
  },
  triggerIcon: {
    type: String,
    default: "bg-ic-file",
  },
  otherInfo: {
    type: String,
    default: "",
  },
  httpRequest: {
    type: Function,
  },
  limit: {
    type: Number,
    default: 9999,
  },
});

const emit = defineEmits(["update:modelValue", "change"]);

const state = reactive({
  fileList: [],
});

const actionDisabled = computed(() => {
  return props.disabled;
});

watch(
  () => props.modelValue,
  () => {
    let newStr = props.modelValue.map((v) => v.url).join(",");
    let oldStr = state.fileList.map((v) => (v.response && v.response.data) || v.url).join(",");

    if (newStr !== oldStr) {
      state.fileList = [...props.modelValue];
    }
  }
);
const handleBeforeUpload = (file) => {
  let temp = file.name.split(".");
  let type = temp[temp.length - 1].toLocaleLowerCase();
  let fileTypesOk = props.fileTypes.indexOf(type) > -1 || props.fileTypes.length == 0;
  let fileMaxSizeOk = file.size / 1024 / 1024 <= props.fileMaxSize;

  if (!fileTypesOk) {
    ElMessage.error(`上传文件只能是${props.fileTypes.join("、")}这些格式！`);
  }

  if (!fileMaxSizeOk) {
    ElMessage.error(`上传文件大小不能超过${props.fileMaxSize}M!`);
  }

  return fileTypesOk && fileMaxSizeOk;
};
const handleExceed = (file, fileList) => {
  ElMessage.error(`只允许上传${props.limit}个文件`);
};
const handlePreview = (val) => {
  let a = document.createElement("a"); // 生成一个a元素
  let event = new MouseEvent("click"); // 创建一个单击事件

  a.download = val.name; // 设置图片名称
  a.href = val.url || val.response.data; // 将生成的URL设置为a.href属性
  a.dispatchEvent(event); // 触发a的单击事件
};
const handleRemove = (file, fileList) => {
  updateFileList(fileList);
};
const handleSuccess = (response, file, fileList) => {
  updateFileList(fileList);
};
const updateFileList = (fileList) => {
  let values = fileList.map((v) => {
    return {
      name: v.name,
      url: (v.response && v.response.data) || v.url,
    };
  });

  state.fileList = fileList;

  emit("update:modelValue", values);
  emit("change", values);
};

onMounted(() => {
  state.fileList = [...props.modelValue];
});

const { fileList } = toRefs(state);
</script>

<style>
.bg-upload .el-upload-dragger {
  padding: 0;
  border: 0;
}
</style>
