<template>
  <el-upload
    ref="upload"
    class="bg-upload"
    v-bind="$attrs"
    :file-list="fileList"
    :action="action"
    :data="{
      directory: 'image',
      uniqueCode: false
    }"
    :auto-upload="autoUpload"
    :list-type="listType"
    :limit="limit"
    :accept="acceptTypes"
    :before-upload="handleBeforeUpload"
    :on-success="handleSuccess"
    :on-remove="handleRemove"
    :on-preview="handlePreview"
    :multiple="multiple"
  >
    <template v-slot:trigger>
      <el-icon v-if="listType === 'picture-card'"><Plus /></el-icon>
      <!-- <i class="el-icon-plus" v-if="listType === 'picture-card'"></i> -->
      <el-button type="primary" :icon="UploadFilled" v-else>
        {{ triggerText }}
      </el-button>
    </template>

    <template v-if="!autoUpload">
      <el-button
        type="success"
        icon="el-icon-position"
        @click="submitUpload"
        style="margin-left: 16px"
      >
        上传到服务器
      </el-button>
    </template>

    <template v-slot:tip v-if="showTips && tips">
      <div class="el-upload__tip" style="color:#909bb6;">
        {{ customTips||tips }}
      </div>
    </template>
  </el-upload>
</template>

<script>
import {
  UploadFilled
} from '@element-plus/icons-vue'
export default {
  name: "BgUploadImage",
  props: {
    modelValue:{
      type: Array,
      default: () => [],
    },
    action: {
      type: String,
      default: "/apaas/common/file/upload",
    },
    autoUpload: {
      type: Boolean,
      default: true,
    },
    listType: {
      type: String,
      default: "text",
    },
    limit: {
      type: Number,
    },
    multiple: {
      type: Boolean,
      default: true,
    },

    accept: {
      type: [Array, String],
    }, // 接受类型
    fileSize: {
      type: Number,
    }, // 文件大小
    fileSizeUnit: {
      type: String,
      default: "MB",
    }, // 文件单位 KB/MB/GB
    triggerText: {
      type: String,
      default: "点击上传",
    }, // 按钮文字
    showTips: {
      type: Boolean,
      default: false,
    }, // 显示提示
    customTips:{
      type: String,
      default: "",
    },// 自定义提示内容 
  },
  emits: ['update:modelValue'],
  computed: {
    acceptTypes() {
      if (Array.isArray(this.accept)) {
        return this.accept.join(",");
      } else {
        return this.accept;
      }
    },
    types() {
      return this.acceptTypes.split(",").filter((v) => v !== "");
    },
    tips() {
      let str = "";

      if (this.types.length > 0) {
        str += `后缀为 ${this.types.join("、")} `;
      }

      if (this.fileSize) {
        if (str) str += " 且";

        str += `大小不超过 ${this.fileSize}${this.fileSizeUnit}`;
      }

      if (str) str += "的文件";

      if (this.limit) {
        str += `，最多上传 ${this.limit} 个文件`;
      }

      if (str) {
        str = "支持" + str;
      }

      return str;
    },
  },
  data() {
    return {
      fileList: [],
      UploadFilled,
    };
  },
  watch: {
    modelValue() {
      let newStr = this.modelValue.map((v) => v.url).join(",");
      let oldStr = this.fileList
        .map((v) => (v.response && v.response.data) || v.url)
        .join(",");

      if (newStr !== oldStr) {
        this.fileList = [...this.modelValue];
      }
    },
  },
  methods: {
    handleBeforeUpload(file) {
      let units = {
        KB: 1024,
        MB: 1024 * 1024,
        GB: 1024 * 1024 * 1024,
      };
      let temp = file.name.split(".");
      let type = "." + temp[temp.length - 1].toLocaleLowerCase();
      let fileTypeIsOk =
        this.types.length === 0 || this.types.indexOf(type) > -1;
      let fileSizeIsOk =
        this.fileSize === 0 ||
        this.fileSize === undefined ||
        file.size / units[this.fileSizeUnit] <= this.fileSize;
      let checked = fileTypeIsOk && fileSizeIsOk;

      if (!checked) {
        this.$message.error(this.tips);
      }

      return checked;
    },
    handleSuccess(response, file, fileList) {
      this.updateFileList(fileList);
    },
    handleRemove(file, fileList) {
      this.updateFileList(fileList);
    },
    handlePreview({ name, url }) {
      let a = document.createElement("a"); // 生成一个a元素
      let event = new MouseEvent("click"); // 创建一个单击事件

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

      this.fileList = fileList;

      console.log(values);

      this.$emit("update:modelValue", values);
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
  },
  mounted() {
    this.fileList = [...this.modelValue];
  },
};
</script>
