<template>
  <div class="upload-file">
    <el-upload
      multiple
      v-if="isShowUploadBtn"
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :on-error="uploadedSuccessfully"
      :on-success="handleUploadSuccess"
      :file-list="fileList"
      :limit="limit"
      :accept="accept"
      :http-request="uploadFile"
      :show-file-list="true"
      :on-remove="handleDelete"
      :on-exceed="handleExceed"
      :on-preview="onPreview"
      :before-remove="beforeRemove"
      :headers="headers"
      class="upload-file-uploader"
      ref="fileUpload"
    >
      <el-button size="small" type="primary" v-if="showTip">点击上传</el-button>
      <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
      <!-- <i class="el-icon-upload"></i> -->
      <!-- 上传按钮 -->
      <!-- <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
      <!-- <el-button size="mini" type="primary">{{ btnName }}</el-button> -->
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        文件<template v-if="fileSize"
          >大小不超过<b style="color: #f56c6c">{{ fileSize }}MB</b></template
        >
        <template v-if="fileType">
          格式为<b style="color: #f56c6c">{{ fileType.join("/") }}</b></template
        >
        的文件
      </div>
    </el-upload>

    <!-- 详情页面显示列表 -->
    <transition-group
      v-if="!isShowUploadBtn"
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul"
    >
      <li
        :key="file.url"
        class="el-upload-list__item ele-upload-list__item-content"
        v-for="file in fileList"
      >
        <div v-if="showHow(file.url)">
          <el-image
            style="width: 100px; height: 100px"
            :src="file.url"
            fit="fit"
            :preview-src-list="getpreviewSrcList(file.url)">
          ></el-image>
        </div>
        <el-link v-else :href="file.url" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ file.name }}</span>
        </el-link>
      </li>
    </transition-group>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { upload } from "@/api/system/public";

export default {
  name: "W-FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    defaultValue: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 20,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["pdf", "jpg", "png", "bmp", "zip", "rar", "7z"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
    isRem: {
      type: Boolean,
      default: true,
    },
    showBut: {
      type: Boolean,
      default: true,
    },
    // 是否文件上传按钮或者拖拽框
    isShowUploadBtn: {
      type: Boolean,
      default: true,
    },
    btnName: {
      type: String,
      default: "选取文件",
    },
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      fileValueList: [],
      accept: this.getAcceptByFileType(), //".pdf,.jpg,.png,.bmp",
    };
  },
  watch: {
    defaultValue: {
      handler(val) {
        if (val) {
          let temp = 1;
          // this.fileList=val;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // console.log("watch fileList", list);
          if (list.length > this.limit) {
            this.handleExceed();
            return;
          }
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            if (typeof item === "string") {
              // console.log("watch fileList item", item)
              let itemObj = JSON.parse(item);
              // console.log("watch fileList itemObj", itemObj)
              if ("name" in itemObj && "url" in itemObj) {
                item = itemObj;
              } else {
                item = { name: item, url: item };
              }
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
          this.fileValueList = [...this.fileList];
          this.$emit("input", this.listToTagObj(this.fileValueList));
        } else {
          this.fileList = [];
          this.fileValueList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
    value: {
      handler(val) {},
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    beforeRemove(file, fileList) {
      if (this.isRem) {
        return true;
      }
      // 返回 false 可以阻止删除操作
      return false;
    },
    showHow(url) {
      // console.log(url, "sss");
      if (url.endsWith("jpg") || url.endsWith("png") || url.endsWith("bmp")) {
        return true;
      }
      return false;
    },
    getpreviewSrcList(url)
    {
      return [url];
    },
    getAcceptByFileType() {
      if (this.fileType) {
        let arr = this.fileType.map((x) => "." + x);
        return arr.join(",");
      }
      return "";
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split(".");
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }

      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }

      if (this.fileList.findIndex((x) => x.name == file.name) > -1) {
        console.log(this.fileList, "this.fileListwww");
        this.$modal.msgError(`不能上传相同名称的文件或图片!`);
        return false;
      }

      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传成功回调
    handleUploadSuccess(res, file, fileList) {
      // console.log("handleUploadSuccess", res, file, fileList);
      this.fileList = fileList;
      // console.log(this.fileList,"this.fileList")
      this.$emit("input", this.listToTagObj(this.fileValueList));

    },
    // 删除文件
    handleDelete(item) {
      if (item && item.status === "success") {
        // console.log("handleDelete1 index", item);
        //this.fileList.splice(item, 1);
        // console.log("handleDelete2", item, this.fileValueList);

        let index = this.fileValueList.findIndex((x) => x.name == item.name);
        // console.log("handleDelete3", index, this.fileValueList);
        if (index > -1) {
          this.fileValueList.splice(index, 1);
        }
        //this.fileValueList.splice(item, 1);
        // console.log("handleDelete4 deleted", this.fileValueList);
        this.fileList = this.listToTagObj(this.fileValueList);
        this.$emit("input", this.listToTagObj(this.fileValueList));
      }
    },
    // 上传失败结束处理 必须调用，否则失败文件也会显示
    uploadedSuccessfully(err, file, fileList) {},
    // 获取文件名称
    getFileName(name) {
      // 将字符串的 JSON 转换为对象
      const fileObj = JSON.parse(name);
      // 返回 name 属性
      return fileObj.name;
    },
    // 获取文件url
    getFileUrl(name) {
      // 将字符串的 JSON 转换为对象
      const fileObj = JSON.parse(name);
      // 返回 name 属性
      return fileObj.url;
    },

    //自定义上传方式(自带的成功回调及失败回调会失效)
    uploadFile(fileObj) {
      let formData = new FormData();
      formData.append("file", fileObj.file);
      // console.log("this.fileValueList.length", this.fileValueList.length);
      if (this.fileValueList.length <= this.limit) {
        upload(formData)
          .then((res) => {
            /*上传成功*/
            this.$modal.closeLoading();
            //let imgUrl = process.env.VUE_APP_BASE_API + res.data.url;
            let arr = [];
            arr.push({ name: res.data.realName, url: res.data.url });
            this.fileValueList = this.fileValueList.concat(arr);
            this.$modal.msgSuccess("上传成功!");
            fileObj.onSuccess();
            this.$emit("success", );
          })
          .catch((err) => {
            /*上传失败*/
            this.$modal.closeLoading();
            fileObj.onError();
            this.$emit("success", );
          });
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }

      return strs != "" ? strs.substring(0, strs.length - 1) : "";
    },

    listToTagObj(list) {
      let tempArry = [];
      for (let i in list) {
        // console.log("listToString2 i",i);
        tempArry.push({ url: list[i].url, name: list[i].name });
      }
      console.log("fileList", tempArry);
      return tempArry;
    },
    onPreview(file) {
      // console.log(file);
      var name = file.name;
      let index = this.fileValueList.findIndex((x) => x.name == file.name);
      this.fileValueList[index];
      var url = this.fileValueList[index].url;
      if (process.env.VUE_APP_BASE_API !== "/") {
        url = process.env.VUE_APP_BASE_API + this.fileValueList[index].url;
      }
      // console.log("process.env.VUE_APP_BASE_API",process.env.VUE_APP_BASE_API,process)

      // console.log("process.env.VUE_APP_BASE_API url",url)
      const a = document.createElement("a");
      a.setAttribute("download", name);
      a.setAttribute("target", "_blank");
      a.setAttribute("href", url);
      a.click();
    },
    clearFiles() {
      if (this.$refs["fileUpload"]) this.$refs["fileUpload"].clearFiles();

      this.fileList = [];
      this.fileValueList = [];
    },
  },
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}

.el-upload-list__item {
  transition: none !important;
}

.upload-file-list .el-upload-list__item {
  // border: 1px solid #e4e7ed;
  // line-height: 2;
  // margin-bottom: 5px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
