<template>
  <div class="d-flex flex-column">
    <el-upload class="am-upload-view" ref="upload" :before-upload="beforeUpload" :on-exceed="handleExceed" :http-request="handleRequest" :limit="10" :show-file-list="false" multiple :action="uploadUrl" :auto-upload="true">
      <div class="d-flex align-items-center">
        <div class="d-flex align-items-center am-upload-btn mr-4">
          <i class="el-icon-upload2 mr-2" />
          <span class="spanStyle">上传文件</span>
        </div>
        <span class="am-upload-tip spanStyle">{{ tips }}</span>
      </div>
    </el-upload>
    <el-table :data="fileDetailInfos" v-if="fileDetailInfos && fileDetailInfos.length > 0" size="mini" :stripe="true" class="w-100 mt-2" max-height="250">
      <el-table-column prop="fileName" label="附件名称"> </el-table-column>
      <el-table-column label="附件类型" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.fileType | toUpperCase }}</span>
        </template>
      </el-table-column>
      <el-table-column label="附件大小" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.fileSize | formatFileSize }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="scope">
          <template v-if="!scope.row.progress">
            <a href="javascript:;" class="am-active" @click="downloadFile(scope)">下载</a>
            <span class="px-2">|</span>
            <a href="javascript:;" class="am-active" @click="deleteFile(scope)">删除</a>
          </template>
          <template v-else>
            <div class="">
              <el-progress :text-inside="true" :stroke-width="26" :percentage="scope.row.progress"></el-progress>
            </div>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Button, Progress, Table, TableColumn, Upload } from "element-ui";
import { Emit, Mixins, Model, Prop } from "vue-property-decorator";
import { FileDetailInfo } from "@/model/FileDetailInfo";
import fileApi from "@/constants/api/ebtrust-file/file.api";
import { Attachment } from "@/model/Attachment";
import fileDetailInfoApi from "@/constants/api/ebtrust-project/file-detail-info";
import { DataInput, DataOutput } from "@/model";
import apiService from "@/services/api.service";
import { Code } from "@/constants/enum/code.enum";
import beanUtilsService from "@/services/bean-utils.service";
import { userStore } from "@dhccmobile/etbc-auth-api";
import { ElUploadInternalFileDetail } from "element-ui/types/upload";
import { AxiosRequestConfig } from "axios";
const ElUpload = Upload;
/**
 * @Description: 单行文本上传组件
 * @author LiuBo
 * @date 2021/2/1
 * @time 11:23
 */
@Component({
  name: "UploadFilesRow",
  components: {
    "el-progress": Progress,
    "el-upload": Upload,
    "el-button": Button,
    "el-table": Table,
    "el-table-column": TableColumn
  }
})
export default class UploadFilesRow extends Vue {
  @Prop({ required: false }) action: any; // 覆盖父类的action 使其不为必须prop
  multipleSelection: string[] = [];
  @Prop() baseInfo: FileDetailInfo | undefined;
  @Prop() instId: string | undefined;
  @Prop() nodeId: string | undefined;
  @Prop({
    required: false,
    default: () => {
      return [
        // Jpeg
        "jpeg",
        "jpg",
        "jpe",
        // Png
        "png",
        // Doc
        "doc",
        // docx
        "docx",
        // pdf
        "pdf",
        // Ppt
        "ppt",
        // Pptx
        "pptx",
        // Xls
        "xls",
        // Xlsx
        "xlsx",
        // Txt
        "txt",
        // raq
        "raq",
        // xlsm
        "xlsm"
      ];
    }
  })
  fileTypes: string[] | undefined;
  fileDetailInfos: any[] = [];
  uploadUrl = (apiService.coreConfig.fileApi || "") + fileApi.upload.url;
  userInfo: any = {}; // 当前登录用户信息
  tips = "支持扩展名：.jpeg .jpg .jpe .png .doc .docx .pdf .ppt .pptx .xls .xlsx .txt .raq .xlsm"; // 上传提示信息
  maxSize = 50 * 1024 * 1024;
  /**初始化*/
  mounted(): void {
    this.userInfo = userStore.principalUser;
  }
  initData() {
    this.searchFileList();
  }
  // 文件类型
  UploadType = {
    Jpeg: { code: "image/jpeg", name: "jpeg/jpg/jpe" },
    Png: { code: "image/png", name: "png" },
    Gif: { code: "image/gif", name: "gif" },
    Bmp: { code: "image/bmp", name: "bmp" },
    Doc: { code: "application/msword", name: "doc" },
    Docx: { code: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", name: "docx" },
    html: { code: "text/html", name: "html" },
    Mp3: { code: "audio/mpeg", name: "mp3" },
    Mp4: { code: "audio/mp4", name: "mp4" },
    Pdf: { code: "application/pdf", name: "pdf" },
    Ppt: { code: "application/vnd.ms-powerpoint", name: "ppt" },
    Xls: { code: "application/vnd.ms-excel", name: "xls" },
    Xlsx: { code: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", name: "xlsx" },
    Xml: { code: "application/xml", name: "xml" },
    Zip: { code: "aplication/zip", name: "zip" },
    Wps: { code: "application/vnd.ms-works", name: "wps" }
  };
  /**
   * @Description: 多文件上传时长度超长的调用
   * @author guoxuhui
   * @date 2021-04-07
   * @time 19:45
   */
  handleExceed(file: ElUploadInternalFileDetail, fileList: ElUploadInternalFileDetail[]) {
    this.$message("超出最大同时上传限制");
  }
  beforeUpload(file: any) {
    return new Promise((resolve, reject) => {
      if (!file.name) {
        this.$message(`文件名称不能为空`);
        return reject();
      }
      const name = file.name;
      let type = name.split(".").pop();
      type = type.toLowerCase();
      if (this.fileTypes && this.fileTypes.length > 0) {
        if (!this.fileTypes.find(value => value === type)) {
          this.$message(`不支持此文件：${file.name}的文件类型`);
          return reject();
        }
      }
      // 文件大小限制写在此处
      const size = file.size;
      if (size && size > this.maxSize) {
        this.$message(`文件：${file.name}的大小超过50m`);
        return reject();
      }
      return resolve();
    });
  }
  /**
   * @description: 文件上传
   * @author GuoXuHui
   * @date 2021/4/6 22:47
   */
  handleRequest(event: any) {
    if (event && event.file) {
      const data: any = apiService.jsonToFormData({
        file: event.file
      });
      this.$amLoading.open("上传中...");

      const requestConfig: AxiosRequestConfig = {
        onUploadProgress: (progressEvent: any) => {
          const num: number = ((progressEvent.loaded / progressEvent.total) * 100) | 0; //百分比
          if (this.fileDetailInfos && this.fileDetailInfos.find(value => value.fileId === event.file.uid)) {
            this.fileDetailInfos.find(value => value.fileId === event.file.uid)["progress"] = num;
            console.dir(this.fileDetailInfos);
          } else {
            this.fileDetailInfos.unshift({
              fileId: event.file.uid,
              fileName: event.file.name,
              fileType: event.file.name.split(".").pop(),
              fileSize: event.file.size,
              progress: num
            });
          }
        }
      };
      apiService.general(fileApi.upload, undefined, data, requestConfig).then((res: DataOutput<Attachment[]>) => {
        if (String(res.code) === String(Code.SUCCESS.code) && res.data && res.data.length > 0) {
          const attachment: Attachment = res.data[0];
          const fileDetailInfo: any = this.baseInfo ? beanUtilsService.copy(this.baseInfo) : new FileDetailInfo();
          fileDetailInfo.mulId = attachment.id!;
          fileDetailInfo.fileName = attachment.fileName!;
          fileDetailInfo.objId = this.nodeId || "";
          fileDetailInfo.flowId = this.instId || "";
          fileDetailInfo.fileType = attachment.fileSuffix!;
          fileDetailInfo.fileSize = attachment.fileSize!;
          fileDetailInfo.upUser = this.userInfo.emplName;
          fileDetailInfo.upTime = new Date();
          fileDetailInfo.fileLocal = attachment.fdfsFullPath! || attachment.nfsPath!;
          fileDetailInfo.trdId = attachment.fileId!;
          const dataInput: DataInput = new DataInput({
            data: fileDetailInfo
          });
          // fileDetailInfo.status = "uploading";
          // this.fileDetailInfos.push(fileDetailInfo);
          apiService.general(fileDetailInfoApi.add, undefined, dataInput).then((res: DataOutput) => {
            this.$amLoading.close(this);
            (this.$refs.upload as any).clearFiles();
            this.listChange([]);
            if (res.code === Code.SUCCESS.code) {
              this.searchFileList();
            } else {
              this.$message(res.msg);
            }
          });
        } else {
          this.fileDetailInfos = this.fileDetailInfos.filter((value: any) => value.fileId !== event.file.uid);
          (this.$refs.upload as any).clearFiles();
          this.$amLoading.close(this);
          this.$message(res.msg);
        }
      });
    }
  }

  /**
   * @Description: 删除文件
   * @author guoxuhui
   * @date 2021-04-07
   * @time 19:44
   */
  deleteFile(event: any): any {
    return this.$amConfirm(
      "确认删除当前项吗?",
      "提示",
      () => {
        if (event && event.row && event.row.trdId) {
          const dataInput: DataInput = new DataInput({
            data: event.row.mulId
          });
          this.$amLoading.open("删除中...");
          apiService.general(fileDetailInfoApi.deleteById, undefined, dataInput).then((res: DataOutput) => {
            this.$amLoading.close(this);
            if (String(res.code) === String(Code.SUCCESS.code)) {
              this.listChange([]);
              this.searchFileList();
            } else {
              this.$message(res.msg);
            }
          });
        }
      },
      () => {}
    );
  }
  /**
   * @description: 下载文件
   * @author guoxuhui
   * @date 2021/3/19 18:00
   */
  downloadFile(event: any): void {
    if (event && event.row && event.row.trdId) {
      const query: any = {
        fileId: event.row.trdId
      };
      apiService.general(fileApi.download, query).then((res: any) => {
        if (res && res.size > 0) {
          const link = document.createElement("a");
          const blob = new Blob([res], { type: "text/plain;charset=UTF-8" });
          link.setAttribute("href", window.URL.createObjectURL(blob));
          link.setAttribute("download", event.row.fileName);
          link.style.visibility = "hidden";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } else {
          this.$message(res.msg);
        }
      });
    }
  }
  @Emit("listChange")
  listChange(listData: any[]) {
    return listData;
  }
  /**
   * @Description: 重新查询文件
   * @author guoxuhui
   * @date 2021-04-07
   * @time 19:44
   */
  searchFileList(): void {
    const dataInput: DataInput<any> = new DataInput<any>({
      param: new FileDetailInfo({ flowId: this.instId, objId: this.nodeId })
    });
    apiService.general(fileDetailInfoApi.selectByObject, undefined, dataInput).then((res: DataOutput<FileDetailInfo[]>) => {
      if (res.code === Code.SUCCESS.code) {
        this.fileDetailInfos = res.data || [];
      } else {
        this.$message(res.msg);
      }
    });
  }
  /**
   * @Description: 批量下载
   * @author GuoXuHui
   * @date 2021-04-08
   * @time 11:32
   */
  handleBatchUpload(): void {
    if (this.multipleSelection && this.multipleSelection.length > 0) {
      const dataInput: DataInput = new DataInput({
        data: this.multipleSelection.map((item: any) => item.trdId)
      });
      apiService.general(fileApi.downloadBatch, undefined, dataInput).then((res: any) => {
        if (res && res.size > 0) {
          const link = document.createElement("a");
          const blob = new Blob([res], { type: "text/plain;charset=UTF-8" });
          link.setAttribute("href", window.URL.createObjectURL(blob));
          link.setAttribute("download", "enclosure.zip");
          link.style.visibility = "hidden";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } else {
          this.$message(res.msg);
        }
      });
    } else {
      this.$message("至少选择一项");
    }
  }
}
</script>

<style scoped lang="scss">
.am-upload-view {
  /*width: 50%;*/
}
.am-upload-btn {
  height: 30px;
  padding: 0 10px;
  border: 1px #d9d9d9 solid;
  border-radius: 5px;
  font-size: 14px;
  & > span {
    color: rgba(0, 0, 0, 0.65);
  }
}
.spanStyle {
  white-space: nowrap; /*强制span不换行*/
  overflow: hidden; /*超出宽度部分隐藏*/
  text-overflow: ellipsis; /*超出部分以点号代替*/
}
.am-upload-tip {
  font-size: 14px;
  color: #808080;
}
.am-active {
  font-size: 13px;
}
</style>
