<template>
  <div class="upload-file-box">
    <template v-if="!readonly">
      <el-upload
        class="upload-demo"
        :id="idName"
        :action="action"
        :data="dataObj"
        :headers="headers"
        :before-remove="beforeRemove"
        :before-upload="beforeAvatarUpload"
        :on-exceed="handleExceed"
        :on-error="handleError"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-preview="handlePreview"
        :limit="limit"
        :file-list="fileList"
        :disabled="readonly"
        :accept="accept"
        :multiple="multiple"
      >
        <el-button size="small" type="primary">{{ textName }}</el-button>
        <div slot="tip" class="el-upload__tip">{{ tip }}</div>
      </el-upload>
    </template>
    <div class="upload-list" v-else-if="fileList.length > 0">
      <el-table
        :data="fileList"
        style="width: 100%"
        :show-header="false"
        :cell-style="{ padding: 0, 'border-bottom': 'unset' }"
      >
        <el-table-column>
          <template
            slot-scope="scope"
            v-if="scope.row.originalName || scope.row.name"
          >
            <el-link type="primary" :href="scope.row.url">{{
              scope.row.originalName || scope.row.name
            }}</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import $ from "jquery";

export default {
  name: "UploadFile",

  props: {
    fileList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    textName: {
      type: String,
      default: "点击上传",
    },
    idName: {
      type: String,
    },
    fileKey: {
      type: String,
    },
    fileUrl: {
      type: String,
    },
    fileName: {
      type: String,
    },
    folderKey: {
      type: String,
    },

    // 只读
    readonly: {
      type: Boolean,
      default: false,
    },

    limit: {
      type: Number,
      default: 1,
    },

    tip: {
      type: String,
      default: "只能上传1个文件，更换文件请主动删除",
    },

    maxSize: {
      type: Number,
      default: 20,
    },

    isMultiple: {
      type: Boolean,
      default: false,
    },

    otherData: {
      type: Object,
      default: () => {
        return {};
      },
    },

    //限制类型
    accept: {
      type: String,
      default: "",
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    // 返回的文件是否有特殊字符，默认有
    isFileUrlSimple: {
      type: Boolean,
      default: false,
    },
    // 是否打开新页面
    isTarget: {
      type: Boolean,
      default: false,
    },
    // 是否开启预览功能
    enablePreview: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    fileList: {
      handler(val) {
        this.setFileUrl();
      },
      deep: true,
    },
  },
  mounted() {
    if (this.isFileUrlSimple) {
      this.action =
        window.ajaxBase.baseUrl + "/v1/file/business/simple/file/upload";
    }
    this.setFileUrl();
  },
  data() {
    return {
      action: window.ajaxBase.uploadFileUrl,
      headers: {
        token: localStorage.getItem("token"), // 获取token
      },
    };
  },

  computed: {
    dataObj() {
      let param = {
        ...this.otherData,
      };
      if (this.folderKey) {
        param.folderKey = this.folderKey;
      }
      return param;
    },
  },

  methods: {
    setFileUrl() {
      this.$nextTick(() => {
        let queryStr = "#" + this.idName + " .el-upload-list__item-name";
        let elementFiles = $(queryStr);

        this.fileList.forEach((item, index) => {
          elementFiles.eq(index).attr("download", "download");
          elementFiles.eq(index).attr("href", item.url);
          if (this.isTarget) {
            elementFiles.eq(index).attr("target", "_blank");
          }
        });
      });
    },

    //上传前判断文件大小
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < this.maxSize;
      if (!isLt2M) {
        this.$emit("update:fileKey", "");
        this.$emit("update:fileUrl", "");
        this.$emit("update:fileName", "");
        this.$emit("update:fileList", []);
        this.$message({
          message: "上传文件大小不能超过" + this.maxSize + "MB!",
          type: "warning",
        });
      }
      return isLt2M;
    },

    //点击叉号回调
    handleDialogClose() {
      this.$emit("close");
    },

    //移除文件
    handleRemove(file, fileList) {
      if (file && file.status === "success") {
        this.$emit("update:fileKey", "");
        this.$emit("update:fileUrl", "");
        this.$emit("update:fileName", "");
        this.$emit("update:fileList", fileList);
        this.$emit("handleRemove", file, fileList);
      }
    },

    //上传成功
    handleSuccess(response, file, fileList) {
      if (response.success) {
        this.$emit("update:fileKey", response.data.rows[0].key);
        this.$emit("update:fileUrl", response.data.rows[0].url);
        this.$emit("update:fileName", response.data.rows[0].originalName);
        this.$emit("update:fileList", fileList);
        this.$emit("onUploadSuccess", response.data.rows[0], file, fileList);
      } else {
        this.$message.error(response.message);
      }
    },
    //预览
    handlePreview(file) {
      if (!this.enablePreview) return;
      let url = file.url;
      if (
        !url &&
        file.response &&
        file.response.data &&
        file.response.data.rows
      ) {
        url = file.response.data.rows[0].url;
      }
      if (url) window.open(url, "_blank");
    },
    //上传失败
    handleError(file, fileList) {
      this.$emit("handleError", file, fileList);
    },

    //文件限制
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },

    async beforeRemove(file, fileList) {
      if (file && file.status === "success") {
        let flag = await this.$confirm(`确定移除 ${file.name}？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        this.$emit("before-remove");
        return flag;
      }
    },
  },
};
</script>
<style lang="scss">
.upload-file-box {
  .upload-list {
    margin-top: 4px;
    .el-table::before {
      height: 0px;
    }
    .el-table tbody tr:hover > td {
      background-color: #ffffff !important;
    }
  }
}
</style>
