<template>
  <uploader
    class="uploader-example"
    ref="uploader"
    v-bind="$props"
    v-on="$listeners"
    :options="uploadOptions"
    @file-added="filesAdded"
  >
    <uploader-unsupport />
    <uploader-btn
      ref="uploadFileButton"
      v-if="replied === true && rowItem.fbk1 && hasQuestion"
      :class="[classObj, classObj2]"
    >
      <span style="margin-left: 5px" @click.stop="uploadRow(row)">{{ btnName }}</span>
    </uploader-btn>
    <uploader-btn
      ref="uploadFileButton"
      v-else-if="replied === false"
      :class="[classObj, classObj2]"
    >
      <span style="margin-left: 5px" @click.stop="uploadRow(row)">{{ btnName }}</span>
    </uploader-btn>
    <el-button size="small" class="upload-small-btn" v-else @click.stop="checkQuestion(row)">{{
      btnName
    }}</el-button>
  </uploader>
</template>

<script>
import uploadApi from '../../lib/api/upload';
import { validateNull } from '../../lib/validate';
import { getApiPath, ft } from '../../lib/utils';
import { getUserInfo } from '../../lib/auth';

export default {
  name: 'Upload',
  props: {
    accept: {
      type: String,
      default: ''
    },

    btnName: {
      type: String,
      default: ft('i18n_common_upload', '上传')
    },

    domain: {
      type: String,
      default: () => {
        return null;
      }
    },

    elsAccount: {
      type: String,
      default: null
    },

    id: {
      type: String,
      default: null
    },

    isElementBtn: {
      type: Boolean,
      default: false
    },

    isHideBtn: {
      type: Boolean,
      default: false
    },

    multiple: {
      type: Boolean,
      default: false
    },

    hasQuestion: {
      type: Boolean,
      default: () => {
        return false;
      }
    },

    replied: {
      type: Boolean,
      default: false
    },

    row: {
      type: Object,
      default: () => {
        return null;
      }
    },

    rowItem: {
      type: Object,
      default: () => {
        return null;
      }
    },
    showNumber: {
      type: Boolean,
      default: false
    },
    businessModule: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      currentElsAccount: '',
      dome: '',
      showUpdate: true,
      fileList: [],
      businessId: '',
      uploader: null,
      uploadOptions: {
        target: getApiPath() + '/FileUploadService/chunk/file_upload',
        testChunks: true, // 是否开启服务器分片校验
        chunkSize: '5242880', // 分片大小 5MB = 5242880 Bytes
        allowDuplicateUploads: true, // 允许重复上传
        fileParameterName: 'file', // 上传文件时文件的参数名，默认file
        maxChunkRetries: 3, // 最大自动失败重试上传次数
        singleFile: !this.multiple, // { Boolean } Default false, To prevent multiple file uploads if it is true.
        checkChunkUploadedByResponse: function (chunk, message) {
          const objMessage = JSON.parse(message);
          if (objMessage.skipUpload) {
            return true;
          }
          return (objMessage.uploaded || []).indexOf(chunk.offset + 1) >= 0;
        },
        headers: {
          // 在header中添加的验证，请根据实际业务来
          token: getUserInfo().token,
          account: `${getUserInfo().elsAccount}_${getUserInfo().elsSubAccount}`
        },
        query: () => {}
      }
    };
  },
  computed: {
    classObj() {
      return this.isElementBtn
        ? 'resetBtn el-button el-button--default el-button--small el-icon-upload2'
        : '';
    },
    classObj2() {
      return this.isHideBtn
        ? 'displayBtn el-button el-button--default el-button--small el-icon-upload1'
        : '';
    }
  },
  watch: {
    attachmentTemplate() {
      this.initData();
    },

    fileList(newVal) {
      // console.log(newVal);
    },
    id: {
      handler(val) {
        if (val) {
          this.businessId = val;
          this.uploadOptions.query = () => {
            return {
              orderNumber: val
            };
          };
          this.initData();
        }
      },
      immediate: true
    },
    showNumber: {
      handler(val) {
        if (val) {
          this.uploadOptions.query = () => {
            return {
              orderNumber: this.businessId
            };
          };
        } else {
          this.uploadOptions.query = () => {
            return {};
          };
        }
      },
      immediate: true
    },
    businessModule: {
      handler(val) {
        if (val === 'order') {
          this.uploadOptions.target = val
            ? getApiPath() + '/FileUploadService/chunk/file_upload_order'
            : getApiPath() + '/FileUploadService/chunk/file_upload';
        }
      },
      immediate: true
    }
  },
  mounted() {
    const currentUserInfo = getUserInfo();
    this.currentElsAccount = currentUserInfo.elsAccount;

    if (this.$refs.uploadFileButton && this.accept) {
      this.$refs.uploadFileButton.attrs.accept = this.accept;
    }
  },
  methods: {
    filesAdded(file) {
      if (
        ![
          'gif',
          'jpg',
          'jpeg',
          'png',
          'bmp',
          'tif',
          'tiff',
          'doc',
          'docx',
          'xls',
          'xlsx',
          'ppt',
          'pptx',
          'txt',
          'pdf',
          'sql',
          'rar',
          'zip',
          'avi',
          'mpg',
          'mpeg',
          'dat',
          'ra',
          'ram',
          'rmvb',
          'mov',
          'qt',
          'asf',
          'wmv',
          'mp4',
          'mkv',
          'cdr',
          'dwg',
          'eml'
        ].includes(
          file.name.substring(file.name.lastIndexOf('.') + 1, file.name.length).toLowerCase()
        )
      ) {
        this.$message.error(`上传文件类型不支持,
只允许gif,jpg,jpeg,png,bmp,tif,tiff,doc,docx,xls,xlsx,ppt,pptx,txt,pdf,sql,rar,zip,avi,mpg,mpeg,dat,ra,ram,rmvb,mov,qt,asf,wmv,mp4,mkv,cdr,dwg,'eml'等格式.`);
        file.ignored = true;
      }
    },
    checkQuestion() {
      if (!this.rowItem.fbk1) {
        this.$message.error('请输入问题描述行号');
        return false;
      } else if (!this.hasQuestion) {
        this.$message.error('输入的问题描述行号有误，请重新填写');
        return false;
      }
    },

    doAction(action, data) {
      this.$emit(action, data);
      // this.$message.success(action)
    },

    // 可增加行方法
    downloadFile(row) {
      if (row.attachmentUrl) {
        const params = {
          elsAccount: row.elsAccount,
          elsSubAccount: row.elsSubAccount,
          filePath: `${this.dome}${row.attachmentUrl}`
        };
        uploadApi.download(params).then((res) => {
          const code = res.data.statusCode || res.data.code;
          if (code !== '200') {
            this.$message.error(res.data.message);
          }
        });
      }
    },

    async getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        let fileResult = '';
        reader.readAsDataURL(file); // 开始转
        reader.onload = function () {
          fileResult = reader.result;
        }; // 转 失败
        reader.onerror = function (error) {
          reject(error);
        }; // 转 结束  咱就 resolve 出去
        reader.onloadend = function () {
          resolve(fileResult);
        };
      });
    },

    handleSuccess(response, file, fileList) {},

    initData() {
      this.showUpdate = !validateNull(this.id);

      if (!validateNull(this.businessId)) {
        // this.option.delBtn = this.delBtn;
      }
    },

    removeFile(file) {
      this.$refs.uploader.uploader.removeFile(file);
    },

    sendFiles() {
      const list = this.fileList.filter((item) => item.uuid); // 过滤掉未上传过的行数据
      return new Promise((resolve, reject) => {
        if (list.length > 0) {
          const params = list.map((item) => item.uuid);
          uploadApi
            .sendFiles(params)
            .then((res) => {
              const code = res.data.statusCode || res.data.code;
              if (code === '200') {
                resolve({ result: true, code: code });
              } else {
                resolve({
                  result: false,
                  message: res.data.message,
                  code: code
                });
              }
            })
            .catch((res) => {
              reject(res);
            });
        } else {
          // eslint-disable-next-line prefer-promise-reject-errors
          resolve({ result: true, code: '200' });
          // reject({
          //   result: false,
          //   message: '请上传附件',
          //   statusCode: '-100'
          // });
        }
      });
    },

    uploadRow(row) {
      this.$emit('uploadRow', row);
    }
  }
};
</script>

<style lang="scss">
.thumb {
  width: 80px;
  height: 80px;
}
.uploader-example {
  display: inline;
  margin-right: 10px;
}
.el-icon-upload1:before {
  content: '\e794' !important;
}
.upload-small-btn {
  padding: 7px 8px;
}
.uploader-btn.displayBtn {
  border: 1px solid #999999;
  background-color: #e7e7e7;
  color: #9c9c9c;
  pointer-events: none;
}
.uploader-btn.resetBtn {
  display: inline-block;
  line-height: 1;
  cursor: pointer;
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  padding: 9px 15px;
  font-size: 13px !important;
  border-radius: 4px;
  position: relative;
  outline: none;
  margin-left: 10px;
  span {
    margin: 0 !important;
  }
  a {
    color: #606266;
  }
  &:focus,
  &:hover {
    color: #40a9ff;
    border-color: #40a9ff !important;
    background-color: #fff !important;
    a {
      color: #409eff;
    }
  }
}
</style>
