<template>


  <div class="upload-file">

    <el-upload
        multiple
        :action="uploadFileUrl"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :show-file-list="false"
        :headers="headers"
        class="upload-file-uploader"
        ref="fileUpload"
    >

      <!-- 上传按钮 -->
      <el-button type="primary">{{name}}</el-button>
    </el-upload>
    <!-- 上传提示 -->
    <div  class="el-upload__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--text" name="el-fade-in-linear" tag="ul">

      <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
        <el-link @click="down(file)"  :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(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>

  </div>
</template>

<script>
import { getAccessToken } from "@/utils/auth";
import { downloadFile } from "@/views/knowledge/views/util/file";

export default {
  props: {
    value: {
      type: [String, Object, Array],
    },
    position: {
      type: String,
      default: "bottom",
    },
    name: {
      type: String,
      default: "选取文件",
    },
    buttonType: {
      type: String,
      default: "common",
    },
    limit: {
      type: Number,
      default: 1,
    },
    fileSize: {
      type: Number,
      default: 200,
    },
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf","mp4","png","jpg","zip","rar","jpeg","xlsx","docx"],
    },
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: "",
      viewFileUrl: process.env.VUE_APP_FILE_API,
      headers: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部
      fileList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/uploadDetail", // 请求地址
    };
  },
  computed: {
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  mounted(){
    //加载文件列表
    this.initFiles()
  },
  watch: {
    value(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: this.viewFileUrl+item };
          }
          item.uid = item.uid || new Date().getTime() + temp++;
          return item;
        });
      } else {
        this.fileList = [];
      }
    },
  },
  methods: {
    /**
     * 手动加载文件列表，为了解决本组件value值变化可能会出现监听不到的情况
     */
    initFiles(){
      if(this.fileList.length==0){
        // 不存在就是新增，新增时直接返回，不然要报错
        if (!this.value){
          return;
        }
        let temp = 1;
        const list = Array.isArray(this.value)? this.value : this.value.split(",");
        this.fileList = list.map((item) => {
          if (typeof item === "string") {
            item = { name: item, url: this.viewFileUrl+item };
          }
          item.uid = item.uid || new Date().getTime() + temp++;
          return item;
        });
      }
    },
    handleBeforeUpload(file) {
      if (this.fileType.length) {
        const name = file.name.split(".");
        const fileExt = name[name.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;
    },
    down(row) {
      console.log(row, 162);
      downloadFile(row.url, row.name);
    },
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败");
    },
    handleUploadSuccess(res, file) {
      if (res.code === 0) {
        if (res.data) {
          this.uploadList.push({
            name: res.data.name,
            url: res.data.url,
            size: res.data.size,
          });
          this.uploadedSuccessfully();
        } else {
          this.$modal.closeLoading();

        }
      } 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);
      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 = [];
        console.log(179,this.fileList)
        this.number = 0;
        this.$emit("input", this.fileList);

        this.$modal.closeLoading();
      }
    },
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i].url) {
          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;
}
.tp-anniu {
  width: 115px;
  height: 30px;
  background: #FFFFFF;
  border-radius: 3px 3px 3px 3px;
  border: 1px solid #237EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #237EFF;
  margin: 0px 40px;
}

</style>
