<template>
  <div class="cms-table-list">
    <cms-row class="cms-file-upload" :gutter="15">
      <cms-col :span="8">
        <el-upload
          style="height: 400px;padding: 0 10px;border-radius: 5px; border: 1px solid #eaeaea"
          ref="upload"
          class="upload-demo"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          :auto-upload="autoUpload"
          :multiple="multiple"
          :data="extraData"
          :limit="limit"
          :accept="accept"
          :file-list="fileList"
          :on-change="onChange"
          :http-request="httpRequest"
          :on-preview="handlePreview"
          :before-upload="handleBeforeUpload"
          :on-error="handleUploadError"
          :on-success="handleUploadSuccess"
          :on-exceed="handleExceed"
          :show-file-list="true"
          :with-credentials="true"
          :action="actionUrl">
          <cms-button slot="trigger" size="small" type="primary">{{ this.$t('upload.selectFile') }}</cms-button>
          <cms-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">
            {{ this.$t('upload.startUpload') }}
          </cms-button>
          <el-alert class="el-upload__text" :closable="false">
            <!--只能上传jpg/png文件，且不超过500kb            -->
            <code style="width: 100%;right: 0;font-size: 12px">
              {{
                this.$t('upload.fileTips', {
                  fileType: 'jpg/png',
                  fileSize: '500KB'
                })
              }}</code>
          </el-alert>
          <el-empty v-if="fileList.length === 0" :description="this.$t('upload.emptyTips')"></el-empty>
        </el-upload>
      </cms-col>
      <cms-col :span="16">
        <cms-query-table
          ref="attachTable"
          :tools-bar="toolsBar"
          :query-params="extraData"
          :fixed-height="true"
          :height="400"
          :callback="uploadCallback"
          :show-search-form="false"
          :columns="columnsConfig"
          :request-call="requestUrl">
        </cms-query-table>
      </cms-col>
    </cms-row>
  </div>
</template>

<script>
import { CmsFileUploadMixin } from './CmsFileUploadMixin'
import { dictionaryMix, mixTableConfig, mixTableConstants, pageInitMix } from "../mixin/common-mixins";

export default {
  name: "CmsFileUpload",
  mixins: [ CmsFileUploadMixin, dictionaryMix, pageInitMix, mixTableConstants, mixTableConfig ],
  i18n: require('./lang'),
  data() {
    return {
      accept: 'file',
      fileList: [],
      loading: false,
      progressPercent: "0%",
      modalVisible: false,
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: [ "doc", "xls", "ppt", "txt", "pdf", 'jpg' ],
    }
  },
  created() {

  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit()
    },
    onChange(file, fileList) {
      console.log('=========================', fileList);
      this.fileList = fileList;
    },
    // 文件数量过多时提醒 文件超出个数限制时的钩子
    handleExceed() {
      this.$messageTips.error(this.$t('upload.limit', { limit: this.limit }))
    },
    httpRequest({ data }) {
      let fd = new FormData();
      const fileList = this.fileList;
      fileList.forEach(item => fd.append("file", item.raw))
      for (const key in data) fd.append(key, data[key]);
      this.$http.common.uploadFile(fd).then(({ code, msg, data }) => {
        if (code === 200) {
          if (this.callback) this.callback(data);
          this.fileList = [];
          this.$refs.attachTable.reload();
        } else {
          this.$messageTips.error(msg)
        }
      });
      return false;
    },
    handlePreview(file) {
      console.log(file, '=======================');
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          return !!(fileExtension && fileExtension.indexOf(type) > -1);

        });
        if (!isTypeOk) {
          // this.$messageTips.error(`文件格式不正确, 请上传${ this.fileType.join("/") }格式文件!`);
          this.$messageTips.error(this.$t('upload.fileFormat', { fileFormat: this.fileType.join("/") }));
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$messageTips.error(`上传文件大小不能超过 ${ this.fileSize } MB!`);
          return false;
        }
      }
      return true;
    },
    // 上传失败
    handleUploadError(err) {
      console.log('err====', err)
      this.$messageTips.error("上传失败, 请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      //上传成功, 三个参数看情况使用
      // 清除上传文件列表
      this.$refs.upload.clearFiles();
    },
    callbackFun() {
      this.fileList = [];
    }
  },
  computed: {
    toolsBar() {
      return [ {
        status: "primary",
        icon: "el-icon-circle-plus-outline",
        title: this.$t("common.button.new"),
        access: "dict:insert",
        onClick: () => {
          this.modalVisible = true;
        },
      } ]
    },
    columnsConfig() {
      return [ {
        ...mixTableConfig.checkbox
      }, {
        ...mixTableConfig.default,
        fixed: 'left',
        title: this.$t('attach.column.fileName'),
        minWidth: 260,
        field: 'fileName',
        cellRender: {
          name: 'cell-link', events: {
            click: this.toView
          }
        }
      }, {
        ...mixTableConfig.default,
        title: this.$t('attach.column.fileSize'),
        field: 'businessNo',
        width: 100
      }, {
        ...mixTableConfig.default,
        title: this.$t('attach.column.fileSize'),
        field: 'fileSize',
        width: 100
      }, {
        ...mixTableConfig.default,
        title: this.$t('attach.column.fileType'),
        field: 'fileType',
        width: 120
      }, {
        ...mixTableConfig.operate,
        title: this.$t('common.column.operate'),
        width: 100,
        cellRender: {
          name: 'operateCell',
          buttons: [ {
            click: this.deleteItem,
            title: this.$t('common.button.delete'),
            props: {
              icon: 'el-icon-delete',
              type: 'danger',
              vPermissionButton: [ 'attach:delete' ]
            },
          } ]
        }
      } ]
    }
  },
}
</script>

<style lang="scss">
.cms-file-upload {
  .el-upload-dragger {
    height: 400px !important;
  }

  .el-alert {
    width: auto !important;
    //display: inline-block;
    //float: right;
    margin-top: 5px;
    padding: 0 16px !important;

    .el-alert__description {
      font-size: 12px;
      margin: 0;
      height: 30px;
      line-height: 30px;
    }
  }

  .el-upload-list {
    height: 350px;
    overflow-y: auto;
  }

  .el-upload-list__item {
  }
}

.vxe-modal--footer {
  background: #ebeef5;
  padding: 0.4em 0.4em 0 1em !important;
}
</style>
