<template>
  <div class="upload-file"> 
      <el-upload v-if="readonly == false"
        multiple
        list-type="picture-card"
        :action="uploadFileUrl"
        :before-upload="handleBeforeUpload"
        :file-list="
          fileList.map((item) => {
            let obj = { name: item.name, url: baseUrl + item.url };
            return obj;
          })
        "
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :headers="headers"
        :on-remove="handleDelete"
        class="upload-file-uploader"
        :class="limit == fileList.length ? 'hiden' : ''"
        ref="fileUpload"
      >
        <i class="el-icon-plus"></i>
      </el-upload> 

    <div v-else>
      <div v-if="ylType == 'one'">
        <div v-if="fileList.length > 0">
          <div class="imageList" :key="i" v-for="(v, i) in fileList">
            <el-image
              :lazy="true"
              style="width: 100%; height: 100%"
              :src="baseUrl + v.url"
              :preview-src-list="[baseUrl + v.url]"
            >
            </el-image>
          </div>
        </div>
        <div v-else>
          <div class="imageList">
            <div
              style="
                width: 100%;
                height: 100%;
                background-color: rgb(245, 247, 250);
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 18px;
                color: #9ca3af;
              "
            >
              未上传
            </div>
          </div>
        </div>
      </div>
      <div v-else>
        <div v-if="fileList.length > 0">
          <div class="imageList">
            <el-image
              :lazy="true"
              style="width: 100%; height: 100%"
              :src="baseUrl + fileList[0].url"
              :preview-src-list="
                fileList.map((item) => {
                  return baseUrl + item.url;
                })
              "
            >
            </el-image>
          </div>
        </div>
        <div v-else>
          <div class="imageList">
            <div
              style="
                width: 100%;
                height: 100%;
                background-color: rgb(245, 247, 250);
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 18px;
                color: #9ca3af;
              "
            >
              未上传
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  name: "ImgUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: false,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    ylType: {
      type: String,
      default: "one",
    },
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            if (typeof item === "string") {
              item = {
                name: item,
                url: item,
              };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 上传前校检格式和大小
    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;
        }
      }
      // this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      // this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({
          name: res.fileName,
          url: res.fileName,
        });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        // this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      if (this.fileList.length == 0) {
        this.fileList = [];
      }
      this.$emit("input", this.listToString(this.fileList));
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        // this.$modal.closeLoading();
      }
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i = 0; i < list.length; i++) {
        strs += list[i].url + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
  },
};
</script>

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

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  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;
}

::v-deep .hiden {
  .el-upload {
    display: none !important;
  }
}

.imageList {
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #c0ccda;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 100px;
  height: 100px;
  margin: 0 8px 8px 0;
  display: inline-block;
}
::v-deep .el-upload--picture-card{
	width: 100px !important;
	height: 100px !important;
	line-height: 110px !important;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item{
	width: 100px !important;
	height: 100px !important; 
}
::v-deep .el-upload-list--picture-card .el-upload-list__item-actions {
  transition: none !important;
}

::v-deep .el-upload-list__item {
  transition: none !important;
}
</style>
