<template>
  <div class="upload-file">
    <el-upload
    multiple
    drag
    :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"
      :headers="headers" class="upload-file-uploader" ref="fileUpload">
      <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 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, index) in fileList">
        <el-link :href="getFileUrl(file)" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file) }} </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 { getToken } from "@/utils/auth";
import { upload } from "@/api/system/public";

export default {
  name: "K-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
    },
    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: ".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: {
    // 上传前校检格式和大小
    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)
      {
        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;
      this.$emit("input", this.listToTagObj(this.fileValueList));
    },
    // 删除文件
    handleDelete(item) {
      if (item && item.status === "success") {
        console.log("handleDelete index",item)
      //this.fileList.splice(item, 1);
      // console.log("handleDelete",item,this.fileValueList)

      let index = this.fileValueList.findIndex(x=>x.name==item.name);
      // console.log("handleDelete",index,this.fileValueList)
      if(index>-1)
      {
        this.fileValueList.splice(index, 1);
      }
      //this.fileValueList.splice(item, 1);
      console.log("handleDelete deleted",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, 'image').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);
          // console.log("uploadFile", this.fileList)
          fileObj.onSuccess();
        }).catch(err => {
          /*上传失败*/
          this.$modal.closeLoading();
          fileObj.onError()
        })
      }

    },
    // 对象转成指定字符串分隔
    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(JSON.stringify( {url:list[i].url,name:list[i].name}));
      }
      console.log("listToString2",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(){
        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: 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>
