<template>
  <el-form>
    <el-upload ref="fileList"
               :disabled="disabled"
               :action="uploadImgUrl"
               :on-success="handleUploadSuccess"
               :before-upload="handleBeforeUpload"
               :limit="limit"
               :on-preview="handlePreview"
               :on-error="handleUploadError"
               :on-exceed="handleExceed"
               :on-remove="handleRemove"
               name="file"
               :file-list="fileList"
               :headers="headers"
    >
      <div slot="tip" class="el-upload__tip">
        cad文件类型：dwg，dwt；word文件类型：doc，docx；Excel文件类型：xls,xlsx;照片文件类型：jpg,png,jpeg; mp4类型
      </div>
      <el-button class="el-icon-plus abs" type="primary">上传文件</el-button>
    </el-upload>

    <!-- 上传提示 -->
    <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>
    <!-- 文件列表 -->
    <!--    <transition-group class="upload-file-list el-upload-list el-upload-list&#45;&#45;text" name="el-fade-in-linear" tag="ul">-->
    <!--      <li :key="file.url + index" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">-->
    <!--        <el-link :href="`${file.url}`" :underline="false" target="_blank">-->
    <!--          <span class="el-icon-document"> {{ file.name }} </span>-->
    <!--        </el-link>-->
    <!--        <div class="ele-upload-list__item-content-action">-->
    <!--          <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>-->
    <!--        </div>-->
    <!--      </li>-->
    <!--    </transition-group>-->
  </el-form>
</template>

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

export default {
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['dwg', 'dwt', 'doc', 'docx', 'xls', 'xlsx', 'png', 'jpg', 'jpeg','mp4'],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      type: "",
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/obs", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: []
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "object") {
              item = {name: item.fileName, url: item.picUrl};
            }
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    handlePreview(file) {
      if (file.url == null) return;
      const link = document.createElement('a');
      link.href = file.url;
      link.download = file.name ? file.name : '文件'; // 可以指定下载后的文件名
      link.click();
    },
    // 删除文件
    handleDelete(index) {

      const obj = this.fileList[index];
      if (obj != null) {
        this.fileList.splice(index, 1);
      }
      this.$emit("input", this.fileList);
    },
    // 删除图片
    handleRemove(file, fileList) {
      const findex = this.fileList.map(f => f.url).indexOf(file.url);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
      }

      this.$emit("removeFile", this.fileList);
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      if (res.code == 200) {
        this.fileList.push({name: res.data.fileName, url: res.data.url});
        this.$emit("input", this.fileList);
        if (this.loading)
          this.loading.close();
      } else {
        this.$message.error(res.msg);
        this.loading.close();
      }
    },
    /**
     * cad文件类型：dwg，dwt；word文件类型：doc，docx；Excel文件类型：xls,xlsx;
     * @param file
     * @returns {boolean}
     */
    // 上传前loading加载
    handleBeforeUpload(file) {
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          let name = '';
          let flag = false;
          if (!['dwg', 'dwt', 'doc', 'docx', 'xls', 'xlsx', 'png', 'jpg', 'jpeg','mp4'].includes(fileExtension)) {
            name = 'cad文件类型：dwg，dwt；word文件类型：doc，docx；Excel文件类型：xls,xlsx;照片文件类型：jpg,png,jpeg,mp4类型';
            flag = true
          }
          if (flag == true) {
            this.$message.error(
              `文件格式不正确, 规则：${name}!`
            );
            return false;
          }
          return true
        } else {
          return false
        }

      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(res) {
      this.$message({
        type: "error",
        message: "上传失败",
      });
      this.loading.close();
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      this.type = file.name.slice(file.name.lastIndexOf(".") + 1);
      console.log(this.type)
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
  }
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
  display: none;
}

// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter, .el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}

.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;
}
</style>

