<template>
  <el-col :xl="{ span: span, offset: offset }" :lg="lgSpan" :md="mdSpan" :sm="smSpan" :xs="xsSpan">
    <el-form-item :label="label" :rules="[...requireRule(required, label, validate, trigger), ...rules]" :prop="prop"
      :label-width="labelWidth" :style="itemStyle">
      <el-upload v-if="!disabled && !parent.disabled" 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" :data="{ module, func, category }"
        class="upload-file-uploader" :auto-upload="autoUpload" :disabled="disabled" ref="upload">
        <!-- 上传按钮 -->
        <CustomButton :style="buttonStyle" label="上传附件" size="medium" :disabled="disabled" type="primary"
          v-if="showButton" />
        <el-button v-if="!autoUpload" style="margin-left: 10px;" size="small" type="success" @click="submitUpload">
          上传到服务器
        </el-button>

        <!-- 上传提示 -->
        <div class="el-upload__tip" slot="tip" v-if="showTip">
          提示:
          <template v-if="fileType"> 仅允许上传<b style="color: #f56c6c">"{{ fileType.join("/") }}"</b>格式</template>
          <template v-if="fileSize"> ，单个附件大小上限 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
          <template v-if="fileOther"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ fileOther }}</template>
        </div>

      </el-upload>
      <!-- 文件列表 -->
      <transition-group :style="{ fileListWidth }" class=" el-upload-list el-upload-list--text" name="el-fade-in-linear" style="max-height: 500px;overflow: auto"
        tag="ul">
        <li :key="file.staticUrl" class="el-upload-list__item ele-upload-list__item-content"
          v-for="(file, index) in fileList" style="width: 100%;">
        <el-tooltip class="item" effect="light" :content="file.attaName" placement="top-end">
          <span class="el-icon-document">
                {{ file.attaName }}
          </span>
        </el-tooltip>

          <span class="ele-upload-list__item-content-action" style="float: right;">
            <el-link v-if="contentType(file.attaName)"
              @click="handlePreview(file)"
              type="primary" style="color:#DE9314;borderColor: '#DE9314'">预览</el-link>
            <el-link @click="handleDownload(file)" type="primary"
              style="color:#DE9314;borderColor: '#DE9314'">下载</el-link>
            <el-link v-if="!disabled && !parent.disabled" @click="handleDelete(index)" type="danger">删除</el-link>
          </span>
        </li>
      </transition-group>
    </el-form-item>
  </el-col>
</template>

<script>
import { getToken } from "@/utils/auth";
import mixin from "./mixin";
import { download, preview } from "../../../../utils/request";
import { downloadFileByPath } from "../../../../api/file/file";


export default {
  name: "FileUploadItem",
  mixins: [mixin],
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 20,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 500,
    },
    fileOther: {
      type: String,
      default: "",
    },
    /**
     *
     * */
    itemStyle: {
      type: Object,
      default: () => {
      },
    },

    /**
     *  是否开启文件校验
     * */
    validatorFlag: {
      type: Boolean,
      default: true
    },
    // 文件类型, 例如['xlsx', '.xls']
    fileType: {
      type: Array,
      default: () => ['pdf', 'jpg', 'png', 'zip'],
    },

    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    autoUpload: {
      type: Boolean,
      default: true,
    },
    urlSuffix: {
      type: String,
      default: "",
    },
    label: {
      type: String,
      default: "附件"
    },
    labelWidth: {
      type: String,
      default: ''
    },
    showButton: {
      type: Boolean,
      default: true
    },
    fileListWidth: {
      type: String,
      default: '600px'
    },
    /**
     * 模块类型--区分文件夹
     * */
    module: {
      type: String
    },
    /**
     * 功能类型--区分文件夹
     * */
    func: {
      type: String
    },
    /**
     * 附件类型--区分文件夹
     * */
    category: {
      type: String
    },
    span: {
      type: Number,
      default: 24
    },
    offset: {
      type: Number,
      default: 0
    },
    trigger: {
      type: String,
      default: 'blur'
    },
    validate: {
      type: String
    },
    rules: {
      type: Array,
      default: () => []
    },
    /**
     *
     * */
    buttonStyle: {
      type: Object,
      default: () => {
      }
    },
    lgSpan: {
      type: Number,
      default: 24
    },
    lgOffset:{
      type: Number,
      default: 0
    },
    mdSpan: {
      type: Number,
      default: 24
    },
    smSpan: {
      type: Number,
      default: 24
    },
    xsSpan: {
      type: Number,
      default: 24
    }

  },
  data() {
    return {
      number: 0,
      uploadList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/upload/file-upload-classification", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: []
    };
  },
  created() {
    this.$watch(() => this.parent.model[this.prop], val => this.fileList = val || [], { immediate: true })
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && this.fileSize;
    },
  },
  methods: {
    handlePreview(file){
      downloadFileByPath(file.staticUrl)
        .then(res => preview(res, this.contentType(file.attaName)))
    },
    handleDownload(file){
      downloadFileByPath(file.staticUrl)
        .then(download)
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }

      //校检文件类型
      if (this.fileType && this.validatorFlag) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1).toLowerCase();
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.toLowerCase().indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }


      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading()
    },
    //上传服务器
    submitUpload() {
      this.$refs.upload.submit()
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      this.$modal.closeLoading()
      if (res.code == 500) {
        this.$modal.msgError("上传文件失败，请重试");
        return;
      }
      const { originalFileName, serverFileName, staticUrl, uploadUrl } = res.result
      this.uploadList.push({ attaName: originalFileName, uploadName: serverFileName, staticUrl, uploadUrl });
      if (this.uploadList.length === this.number) {
        if (this.fileList == null || this.fileList == undefined) {
          this.fileList = []
        }
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.parent.model[this.prop] = this.fileList

        this.$set(this.parent.model, 'module', this.module);
        this.$set(this.parent.model, 'storage', this.func);
        this.$set(this.parent.model, 'category', this.category);
        this.$emit("input", this.fileList);
      }
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.fileList);
    },
    contentType(name) {

      if (!name) {
        return
      }
      const suffix = name.slice(name.lastIndexOf('.') + 1).toLowerCase()
      const map = {
        'pdf': 'application/pdf',
        'jpg': 'image/jpg',
        'jpeg': 'image/jpeg',
        'png': 'image/png'
      }
      console.log('map[suffix]', map[suffix])
      return map[suffix]
    }
  }
};
</script>

<style scoped lang="scss">
.upload-file {
  margin-left: 20px;
  display: flex;
}

::v-deep .el-dialog__body{
  padding: 16px;
}

.upload-file-uploader {
  /*margin-bottom: 5px;*/
}

.el-upload__tip {
  margin-top: 13px;
  line-height: 12px;
}

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

}

.upload-file-list .el-upload-list__item:first-child {
  margin-top: 5px !important;

}

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

}

.el-icon-document {
  height: 22px;
  width: calc(100% - 150px);
  padding-top: 6px;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap
}

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

.el-link.el-link--primary.is-underline:hover:after {
  border-color: #DE9314;
}

.uploadLabel {
  padding: 4px 12px 0 0;
  color: #606266;
  font-weight: 700;
  font-size: 14px;
  text-align: right;
  vertical-align: middle;
}

.el-upload-list__item:first-child{
  margin-top: 7px;
}
.el-upload-list__item{
  margin-top: 9px;
}
</style>
