<template>
  <div class="dsk-file-input-container" :class="{'upload-is-disabled' : disabled}">
    <div class="dsk-photo-input-inner" @click.stop="uploadFile" v-if="!comFileList.length">
      <i class="el-icon-plus"></i>
      <span>上传文件</span>
    </div>
    <el-badge :value="comFileList.length" class="item" type="primary" v-if="comFileList.length" @click.native="showFileListDialog">
      <div class="dsk-photo-input-inner" @click.stop="uploadFile">
        <i class="el-icon-plus"></i>
        <span>上传文件</span>
      </div>
    </el-badge>
    <el-upload :on-change="handleChange" action="#" :accept="allowTypes.join(',')" :auto-upload="false" :show-file-list="false"
      ref="elUploadDskUploadIns" class="el-upload-dsk-upload-ins"></el-upload>

    <el-dialog title="已上传文件" :visible.sync="fileListDialog" width="800px" @close="fileListDialogClose" :close-on-click-modal="false"
      class="dsk-upload-dialog">
      <el-table :data="comFileList.slice((pageInfo.currentPage -1) * pageInfo.pageSize, pageInfo.pageSize * pageInfo.currentPage)" border stripe>
        <el-table-column prop="fileName" label="文件名称"></el-table-column>
        <el-table-column prop="type" label="文件类型"></el-table-column>
        <el-table-column prop="url" label="文件地址" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span style="color:#0081ff;cursor: pointer;" @click="viewFile(scope.row)">{{scope.row.url}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="90" v-if="!disabled">
          <template slot-scope="scope">
            <span style="color:#F56C6C;cursor: pointer;" @click="removeImg(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background layout="prev, pager, next" :total="comFileList.length" @current-change="currentChange"
        v-if="comFileList.length > 10"></el-pagination>
    </el-dialog>
  </div>
</template>
<script>
import { uploadFileToOssApi } from "@/api/consultingOrgManagement";
import { elementMessageSingleton } from "@/utils";
export default {
  name: "dskFileInput",
  props: {
    limit: {
      type: [String, Number]
    },
    disabled: {
      type: Boolean,
      default: false
    },
    fileList: {
      type: Array,
      default: () => []
    }
  },
  model: {
    prop: "fileList",
    event: "update:fileList"
  },
  data() {
    return {
      allowTypes: [".docx", ".pdf", ".doc", ".xlsx", ".xls", ".xlt", ".xlsm", ".txt", ".xltm"],
      comFileList: [],
      fileListDialog: false,
      pageInfo: {
        pageSize: 10,
        currentPage: 1
      }
    };
  },
  //可访问data属性
  created() {

  },
  //计算集
  computed: {
    limitRestrict() {
      return this.limit === -1 ? true : this.comFileList.length >= this.limit ? false : true;
    }
  },
  //方法集
  methods: {
    async handleChange(file, fileList) {
      try {
        /** 
       * @type {string}
      */
        let fileName = file.name;
        let fileType = "";
        const index = fileName.lastIndexOf(".");
        if (index) fileType = fileName.slice(index);

        if (!this.allowTypes.includes(fileType.toLowerCase())) {
          return this.$message.warning(`只支持上传${this.allowTypes.join(" , ")}类型文件`);
        }
        // 验证通过进行上传
        await this.uploadHandle(file.raw, fileType);
        this.$message.success("上传成功");
      } catch (error) {
        console.log(error);
      } finally {
        this.$refs["elUploadDskUploadIns"].clearFiles();
      }
    },
    uploadFile() {
      // 禁用状态
      if (this.disabled) return;
      // 超出个数限制
      if (!this.limitRestrict) return elementMessageSingleton("warning", `文件限制上传${this.limit}个,已上传${this.comFileList.length}个文件`);
      this.$refs["elUploadDskUploadIns"].$el.querySelector(".el-upload__input").click();
    },
    async uploadHandle(file, fileType) {
      try {
        const formData = new FormData();
        formData.append("file", file);
        const result = await uploadFileToOssApi(formData);
        if (result.code == 200 && result.data) {
          this.comFileList.push({
            url: result.data.url,
            type: fileType,
            id: result.data.ossId,
            fileName: result.data.fileName
          });
          this.$emit("update:fileList", this.comFileList);
        }
      } catch (error) {

      }
    },
    showFileListDialog() {
      this.fileListDialog = true;
    },
    fileListDialogClose() {
      this.pageInfo = this.$options.data.call(this).pageInfo;
    },
    viewFile(row) {
      this.$download.saveAs(row.url, row.fileName);
    },
    currentChange(current) {
      this.pageInfo.currentPage = current;
    },
    removeImg(row) {
      if (row.id) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const index = this.comFileList.findIndex(item => item.id == row.id);
          if (index > -1) {
            this.comFileList.splice(index, 1);
            this.$emit("update:fileList", this.comFileList);
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }
        }).catch(() => { });
      }
    }
  },
}
</script>
<style lang="scss" scoped>
.dsk-file-input-container {
  width: 100%;
  height: 32px;

  &.upload-is-disabled {
    .dsk-photo-input-inner {
      cursor: not-allowed;
      &:hover {
        color: rgba(35, 35, 35, 0.8);
        border-color: #dcdfe6;
      }
    }
  }

  .dsk-photo-input-inner {
    width: 106px;
    height: 32px;
    background: #ffffff;
    border: 1px solid #dcdfe6;

    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0px 16px;
    box-sizing: border-box;
    color: rgba(35, 35, 35, 0.8);
    font-size: 14px;
    font-weight: 400;
    cursor: pointer;

    &:hover {
      color: #0081ff;
      border-color: #0081ff;
    }
  }

  ::v-deep .el-upload-dsk-upload-ins {
    width: 0px;
    height: 0px;
    opacity: 0;
    position: relative;
    z-index: -999;
  }

  ::v-deep .el-badge__content {
    background: #0081ff;
    cursor: pointer;
    border-color: #0081ff;
  }

  ::v-deep .dsk-upload-dialog {
    @import "@/assets/styles/dsk-upload-dialog.scss";
  }
}
</style>
