<template>
  <div>
    <h4>
      <i class="el-icon-link" />
      <span v-if="!readonly">{{ labels.attachment }}</span>
      <span v-else>{{ labels.uploadAttachment }}</span>
      <el-button v-if="addBtn && !readonly" size="mini" @click="listRowAdd" class="file-btns">
        {{ labels.addRow }}
      </el-button>
    </h4>
    <fast2-theme-provider :option="finalOption" theme="block" :version="version">
      <template v-slot="component">
        <div v-if="component.option && component.option.column && component.option.column.length">
          <avue-crud
            :data="fileList"
            :option="handleOption(component.option)"
            :permission="getPermission"
            @row-del="handleDelete"
          >
            <template v-slot:fileAction="scope">
              <div
                class="operation-button-container"
                v-if="!readonly && downloadClient"
                @click="setUploadRow(scope.row)"
              >
                <fast2-upload
                  :id="id"
                  :businessModule="businessModule"
                  :showNumber="showNumber"
                  :isHideBtn="isHideBtn"
                  @file-success="fileSuccess"
                  @file-progress="onFileProgress"
                  @file-error="onFileError"
                />
                <el-link
                  class="uploader-btn"
                  download
                  v-if="scope.row.attachmentUrl"
                  target="_blank"
                  @click="handleDownload(scope.row)"
                >
                  {{ labels.download }}
                </el-link>
                <el-link
                  class="uploader-btn preview-btn"
                  target="_blank"
                  v-if="enablePreview(scope.row)"
                  @click="handlePreview(scope.row)"
                >
                  {{ labels.preview }}
                </el-link>
              </div>
              <div v-else-if="downloadClient">
                <el-link
                  class="uploader-btn"
                  download
                  v-if="scope.row.attachmentUrl"
                  target="_blank"
                  @click="handleDownload(scope.row)"
                >
                  {{ labels.download }}
                </el-link>
                <el-link
                  class="uploader-btn preview-btn"
                  target="_blank"
                  v-if="enablePreview(scope.row)"
                  @click="handlePreview(scope.row)"
                >
                  {{ labels.preview }}
                </el-link>
              </div>
            </template>
            <template slot="fbk1" slot-scope="{ row }">
              <div v-if="replied && !row.attachmentName">
                <el-input
                  v-model="row.fbk1"
                  @input="(value) => handleFbk1Change(value, row)"
                ></el-input>
              </div>
              <div v-if="replied && row.attachmentName">
                <el-input
                  v-model="row.fbk1"
                  disabled="true"
                  @input="(value) => handleFbk1Change(value, row)"
                ></el-input>
              </div>
            </template>
            <template slot="annexType" slot-scope="{ row }">
              <span v-if="row.isRequired === 'Y'" class="annexType" />{{ row.annexType }}
            </template>

            <!-- 自定义slot -->
            <template
              v-for="customSlotItem in customSlotItems"
              :slot="customSlotItem.prop"
              slot-scope="{ row }"
            >
              <slot
                v-if="customSlotItem && customSlotItem.prop"
                :slot-scope="row"
                :name="customSlotItem.slotName"
              />
            </template>

            <template slot-scope="scope" slot="menu">
              <!-- 自定义扩展操作栏 -->
              <slot name="extendOperation" :slot-scope="scope.row" />
              <span>
                <a @click="deleteFile(scope.row)"
                  >&emsp;&emsp;<i class="el-icon-circle-close"></i> {{ labels.clear }}</a
                >
              </span>
            </template>
          </avue-crud>
        </div>
      </template>
    </fast2-theme-provider>
    <a-modal
      :cancelText="labels.cancel"
      :cancel-button-props="{ props: { disabled: true, display: false } }"
      :maskClosable="false"
      :okText="labels.done"
      :ok-button-props="{ props: { disabled: true, display: false } }"
      :title="labels.uploadTitle"
      :visible="uploading"
      @cancel="handleCancelProgressDialog"
    >
      <p>{{ uploadFileName }} {{ labels.ModalText }}</p>
      <a-progress :percent="progress" />
    </a-modal>
  </div>
</template>

<script>
import uploadApi from '../../lib/api/upload';
import { getFilePath } from './core/utils.js';
import { ft, getApiPath, renderSize } from '../../lib/utils';
import { validateNull } from '../../lib/validate';
import { getUserInfo } from '../../lib/auth';
import cloneDeep from 'lodash/cloneDeep';
import * as dayjs from 'dayjs';

const BaseUrl = getApiPath();

export default {
  name: 'AttachmentList',
  props: {
    addBtn: {
      type: Boolean,
      default: true
    },

    /* 添加空行时，对数据进行初始化处理
      例如
      addEmptyRowProc(item) {
        item.budgetPrice = '0';
        item.quantity = 0;

        return item;
      }
    */
    addEmptyRowProcFn: {
      type: Function,
      default: null
    },

    attachmentTemplate: {
      type: Array,
      default: function () {
        return [];
      }
    },

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

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

    // 是否为供应商端
    client: {
      type: Boolean,
      default: true
    },

    // 是否为供应商tab
    clientTab: {
      type: Boolean,
      default: true
    },

    // customSlots: 自定义 slots, 只输出 slot name, 具体内容由使用都定义(不在组件内部定义), 最多支持 10 个自定义 slot
    customSlots: {
      type: Array,
      default: function () {
        return [];
      }
    },

    delBtn: {
      type: Boolean,
      default: true
    },

    // 是否屏蔽下载供应商附件
    downloadClient: {
      type: Boolean,
      default: true
    },

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

    /**
     * 清除附件时需要清理的属性，当某个属性对应下拉列表的必填字段时，由于附件还没有必填字段表单验证，请不要将该属性添加到这个数组中
     * @see baseProperties
     */
    extendProperties: {
      type: Array,
      default: function () {
        return [];
      }
    },

    // id: 业务单据编码
    id: {
      type: String,
      default: ''
    },

    labels: {
      type: Object,
      default: function () {
        return {
          addRow: ft('i18n_common_add_details', '新增行'),
          attachment: ft('i18n_common_attachment', '附件'),
          cancel: ft('i18n_common_cancel', '取消'),
          clear: ft('i18n_common_clear_attachments', '清除附件'),
          done: ft('i18n_common_done', '结束'),
          download: ft('i18n_common_download', '下载'),
          noData: ft('i18n_common_no_data', '暂无数据'),
          preview: ft('i18n_common_preview', '预览'),
          uploadAttachment: ft('i18n_common_upload_attachment', '上传附件'),
          uploadTitle: ft('i18n_common_upload_progress', '上传进度')
        };
      }
    },

    // 物料附件
    materialFileList: {
      type: Array,
      default: function () {
        return [];
      }
    },

    menu: {
      type: Boolean,
      default: true
    },

    // 用于识别采购方，供应商之外的第三附件
    moreFields: {
      type: String,
      default: ''
    },

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

    // 跳过 是否判断供应商以及供应商tab
    passClient: {
      type: Boolean,
      default: true
    },

    // 显示预览已上传文件的 button, 默认值 false, 且只支持 PDF 文件
    preview: {
      type: Boolean,
      default: false
    },

    previewOption: {
      type: Object,
      default: () => {
        return {
          enablePreviewFn: null, // enablePreviewFn(item) { return this.preview && item.attachmentType === 'pdf' }
          generatePreviewPathFn: null // generatePreviewPathFn(item, path)
        };
      }
    },

    questionList: {
      type: Array,
      default: function () {
        return [];
      }
    },

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

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

    showNumber: {
      type: Boolean,
      default: false
    },
    
    // 保留 version 选项, 如果需要输入配置 option，需要同时将 version 设置为 null
    version: {
      type: String,
      default: () => {
        return 'attahcment-fiels_4_3';
      }
    }
  },
  data() {
    return {
      businessId: '',
      currentUserName: '',
      currentElsAccount: '',
      currentElsSubAccount: '',
      fileList: [],
      progress: 0,
      showUpdate: true,
      uploading: false,
      uploadFileName: '',
      uploader: null,
      uploadRow: null,
      isHideBtn: false,
      itemIds: [],
      newIds: [],
      datetimeFormatTemplate: 'YYYY-MM-DD HH:mm:ss',

      baseProperties: [
        'attachmentName',
        'attachmentDesc',
        'attachmentUrl',
        'attachmentStatus',
        'attachmentType',
        'attachmentSize',
        'startValidity',
        'endValidity',
        'attachmentSize',
        'lastUpdateDate',
        'createDate',
        'createUser'
      ],

      // custom slot items
      customSlotItems: [],

      defaultColumns: [
        {
          prop: 'attachmentName',
          rules: [],
          span: 8,
          label: ft('i18n_common_file_name', '文件名称'),
          isRequired: 'N',
          isSystem: 'N',
          isSearch: 'N',
          isReadOnly: 'N',
          isIndexList: 'N'
        },
        {
          prop: 'annexType',
          label: ft('i18n_common_file_type', '文件名称'),
          type: 'input',
          span: 8,
          orderIndex: 0,
          order: 1,
          slot: true
        },
        {
          prop: 'lastUpdateDate',
          rules: [],
          span: 8,
          label: ft('i18n_common_upload_time', '上传时间'),
          isRequired: 'N',
          datatype: 'datetime',
          isSystem: 'N',
          isSearch: 'N',
          isReadOnly: 'N',
          isIndexList: 'N'
        },
        {
          prop: 'createUser',
          rules: [],
          span: 8,
          label: ft('i18n_common_uploader', '上传人'),
          isRequired: 'N',
          isSystem: 'N',
          isSearch: 'N',
          isReadOnly: 'N',
          isIndexList: 'N'
        },
        {
          prop: 'fileAction',
          label: ft('i18n_common_file', '文件'),
          slot: true
        }
      ],

      defaultOption: {
        editBtn: false,
        addBtn: false,
        delBtn: true,
        cancelBtn: false,
        showSummary: false,
        rowKey: 'businessItemId'
      }
    };
  },

  computed: {
    finalOption() {
      const finalOption = cloneDeep(this.defaultOption);
      const option = this.option || {};
      const columns = option.column || cloneDeep(this.defaultColumns);

      // set slot state for custom slots
      const customSlotPropItems = {};
      const customSlots = this.customSlots || [];

      customSlots.forEach((item) => {
        if (item.prop) {
          customSlotPropItems[item.prop] = 1;
        }
      });

      for (const column of columns) {
        if (customSlotPropItems[column.prop] && column.slot !== true) {
          column.slot = true;
        }
      }

      finalOption.column = columns;

      if (this.hasBusinessId) {
        finalOption.delBtn = this.delBtn;
      }

      return finalOption;
    },

    hasBusinessId() {
      return typeof this.businessId === 'string' && this.businessId;
    },

    hasId(id) {
      return typeof this.id === 'string' && this.id;
    },

    properties() {
      const properties = this.baseProperties.concat(this.extendProperties || []);
      return new Set(properties);
    }
  },

  watch: {
    attachmentTemplate() {
      this.initData();
    },

    customSlots: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.handleCustomSlotsChanged(newVal, oldVal);
        }
      },
      immediate: true,
      deep: true
    },

    id(newValue) {
      this.businessId = newValue;
      this.initData();
    },

    materialFileList(newVal) {
      this.fileList = [];
      newVal.forEach((item) => {
        this.fileList.push({
          elsAccount: this.elsAccount,
          attachmentType: item.attachmentType,
          attachmentSize: item.attachmentSize,
          attachmentName: item.attachmentName,
          attachmentDesc: item.attachmentDesc,
          attachmentUrl: item.attachmentUrl,
          attachmentStatus: 'N',
          businessModule: 'enquiry',
          businessElsAccount: this.elsAccount,
          createUser: item.createUser,
          createDate: item.createDate,
          lastUpdateDate: item.lastUpdateDate
        });
      });

      /*
      const attachmentNames = this.fileList.map((item) => item.attachmentName);
      newVal.forEach((item) => {
        if (!attachmentNames.includes(item.attachmentName)) {
          this.fileList.push({
            elsAccount: this.elsAccount,
            attachmentType: item.attachmentType,
            attachmentSize: item.attachmentSize,
            attachmentName: item.attachmentName,
            attachmentDesc: item.attachmentDesc,
            attachmentUrl: item.attachmentUrl,
            attachmentStatus: 'N',
            businessModule: 'enquiry',
            businessElsAccount: this.elsAccount,
            createUser: item.createUser,
            createDate: item.createDate
          });
        }
      });
      */
    }
  },

  mounted() {
    const currentUserInfo = getUserInfo();
    this.currentElsAccount = currentUserInfo.elsAccount;
    this.currentElsSubAccount = currentUserInfo.elsSubAccount;
    this.currentUserName = currentUserInfo.elsSubaccountInfoDTO.name || '';

    // this.initWebUpload();
    if (this.hasId) {
      this.businessId = this.id;
      this.initData();
    }
  },
  methods: {
    addFileList(file) {
      const checkProp = 'businessItemId';

      const fileItem = {
        ...this.uploadRow,
        elsAccount: this.elsAccount,
        attachmentType: file.fileType,
        attachmentSize: renderSize(file.fileSize),
        attachmentName: file.fileName,
        attachmentDesc: file.fileName,
        attachmentUrl: file.filePath,
        businessModule: this.businessModule,
        businessElsAccount: this.businessElsAccount,
        businessId: this.businessId,
        createUser: `${this.currentElsSubAccount}_${this.currentUserName}`,
        createDate: dayjs(new Date()).format(this.datetimeFormatTemplate),
        lastUpdateDate: dayjs(new Date()).format(this.datetimeFormatTemplate)
      };

      this.fileList = this.fileList.map((item) => {
        return item[checkProp] === fileItem[checkProp] ? fileItem : item;
      });
      this.isHideBtn = false;
      this.$message.success(this.$ft('i18n_common_upload_successfully', '上传成功'));
    },

    confirmDelete(uuid, index) {
      const _this = this;

      this.$confirm({
        title: this.$ft('i18n_common_confirm_deletion_of_selected_data', '确认删除所选数据?'),
        content: '',
        okText: this.$ft('i18n_common_confirm', '确认'),
        cancelText: this.$ft('i18n_common_cancel', '取消'),
        onOk() {
          _this.deleteAttachment(uuid, index);
        },
        onCancel() {}
      });
    },

    deleteAttachment(uuid, index) {
      uploadApi
        .deleteAttachment(uuid)
        .then((res) => {
          if (res.data && res.data.code === '200') {
            this.fileList.splice(index, 1);
          } else {
            console.log('Failed to delete a attachment, ', res.data || res);
            this.$message.error(
              res.data.message ||
                res.statusText ||
                this.$ft('i18n_common_failed_to_cancel_delete_attachment', '删除附件失败')
            );
          }
        })
        .catch((err) => {
          console.log('Error to delete a attachment, ', err);
          this.$message.error(
            this.$ft('i18n_common_failed_to_cancel_delete_attachment', '删除附件失败')
          );
        });
    },

    deleteFile(row) {
      const propertySet = this.properties;

      const item = this.fileList[row.$index];
      const array = Object.keys(item);

      for (const property of array) {
        if (propertySet.has(property)) {
          item[property] = null;
        }
      }

      this.$set(this.fileList, row.$index, row);

      // 没有可清除的附件
      if (!item.uuid) {
        const text = this.$ft('i18n_common_no_purgeable_attachments', '没有可清除的附件');
        return this.$message.warning(text);
      }

      // 删除文件
      uploadApi.deleteFile(item.uuid).then((res) => {
        if (res.data.code === '200') {
          delete item.uuid;
          const text = this.$ft('i18n_common_cleared_successfully', '清除成功');
          this.$message.success(text);
        }
      });
    },

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

    download(blobUrl, fileName) {
      const a = document.createElement('a');
      a.download = fileName;
      a.href = blobUrl;
      a.click();
    },

    defaultEnablePreview(item) {
      return this.preview === true && item.attachmentType === 'pdf';
    },

    defaultGeneratePreviewPath(item, path) {
      const pattern = /(http|https):\/\/([\w.]+\/?)\S*/;
      const url = item.attachmentUrl;
      return pattern.test(url) ? url : path + url;
    },

    enablePreview(item) {
      const previewOption = this.previewOption || {
        enablePreviewFn: null,
        generatePreviewPathFn: null
      };

      const { enablePreviewFn = null } = previewOption;
      const fn = enablePreviewFn || this.defaultEnablePreview;

      return fn(item);
    },

    fileSuccess(rootFile, file, message, chunk) {
      const data = JSON.parse(message).data;
      this.uploading = false;
      const fileData = {
        fileSize: data.size,
        fileName: data.name,
        fileType: data.type,
        filePath: data.url
      };

      this.$emit('upload-file', fileData);

      if (!this.id) {
        // 新建时, 没有业务单据编码
        this.addFileList(fileData);
      } else {
        this.updateFileList(fileData);
      }
    },

    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);
        };
      });
    },

    getList() {
      const action = 'findList';
      const params = {
        businessElsAccount: this.businessElsAccount,
        businessModule: this.businessModule,
        businessId: this.businessId
      };

      uploadApi
        .attachmentServer(action, params)
        .then((res) => {
          if (res.data && res.data.code === '200' && res.data.data) {
            this.handleItems(res.data.data.rows || []);
          } else {
            console.log('Failed to list attachments.', res.data || res);
            this.$message.error(
              res.data.message ||
                res.statusText ||
                this.$ft('i18n_common_failed_to_list_attachments', '查询附件失败')
            );
          }
        })
        .catch((err) => {
          console.log('Error to list attachments.', err);
          this.$message.error(this.$ft('i18n_common_failed_to_list_attachments', '查询附件失败'));
        });
    },

    getPermission(key, row, index) {
      if (this.readonly === true) {
        return false;
      }

      if (key === 'delBtn') {
        if (this.fileList.length !== 0 && row && row.annexType) {
          this.fileList.map((item) => {
            if (item.annexType === row.annexType) {
              index = row.$index;
            }
          });
          return false;
        }
      }
      return true;
    },

    handleCancelProgressDialog() {
      this.uploading = false;
    },

    handleCustomSlotsChanged(customSlots = []) {
      for (const customSlot of customSlots) {
        if (customSlot && customSlot.prop && customSlot.slotName) {
          this.customSlotItems.push(customSlot || {});
        }
      }
    },

    handleDelete(row, index) {
      if (row.uuid) {
        this.confirmDelete(row.uuid, index);
      } else {
        this.fileList.splice(index, 1);
      }
    },

    handleDownload(row) {
      const blobUrl = `${BaseUrl}/servlet/downloadServlet?filePath=${row.attachmentUrl}`;
      const fileName = row.attachmentName;
      this.download(blobUrl, fileName);
    },

    handleItems(items) {
      items.forEach((item) => {
        item.lastUpdateDate = dayjs(item.lastUpdateDate).format(this.datetimeFormatTemplate);
        item.createDate = dayjs(item.createDate).format(this.datetimeFormatTemplate);
      });

      if (this.passClient) {
        this.fileList = items;
      } else {
        if (this.client) {
          if (this.clientTab) {
            this.fileList = items.filter((item) => item.elsAccount === this.elsAccount);
          } else {
            this.fileList = items.filter((item) => item.elsAccount !== this.elsAccount);
          }
        } else {
          if (this.clientTab) {
            this.fileList = items.filter((item) => item.elsAccount !== this.businessElsAccount);
          } else {
            this.fileList = items.filter((item) => item.elsAccount === this.businessElsAccount);
          }
        }
      }

      // businessItemId 根据该值判断 替换或直接 push
      // const itemIds = this.fileList.map((item) => item.businessItemId);
      this.fileList.forEach((item) => {
        if (item.businessItemId) {
          this.itemIds.push(item.businessItemId);
        }
      });

      if (this.itemIds.length !== 0) {
        this.newIds = this.itemIds;
      } else {
        console.log('无');
      }

      this.attachmentTemplate.forEach((item) => {
        // item.isValidity = true; // TODO:
        if (this.itemIds.includes(item.businessItemId)) {
          const index = this.fileList.findIndex(
            (file) => file.businessItemId === item.businessItemId
          );

          const i = this.fileList[index];

          i.$cellEdit = !!(item.isValidity === 'Y' && this.readonly === false);
          i.isValidity = validateNull(item.isValidity) ? false : item.isValidity;
          i.startValidity = validateNull(item.startValidity) ? '' : item.startValidity;
          i.endValidity = validateNull(item.endValidity) ? '' : item.endValidity;

          this.fileList[index] = {
            ...item,
            ...i
          };
        } else {
          item.$cellEdit = !!(item.isValidity === 'Y' && this.readonly === false);
          // item.isValidity = validateNull(item.isValidity) ? false : item.isValidity;
          item.startValidity = validateNull(item.startValidity) ? '' : item.startValidity;
          item.endValidity = validateNull(item.endValidity) ? '' : item.endValidity;

          this.fileList.push(item);
        }
      });

      const fileData = JSON.parse(JSON.stringify(this.fileList));

      this.fileList = this.moreFields
        ? fileData.filter((item) => {
            return item.fbk1 === 'Y';
          })
        : fileData.filter((item) => {
            return item.fbk1 !== 'Y';
          });
    },

    handleOption(option) {
      const columns = option.column;

      option.emptyText = this.labels.noData;

      for (const column of columns) {
        if (column.i18nKey && column.label) {
          column.label = ft(column.i18nKey, column.label);
        }
      }

      return option;
    },

    handlePreview(item) {
      const previewOption = this.previewOption || {
        enablePreviewFn: null,
        generatePreviewPathFn: null
      };

      const { generatePreviewPathFn = null } = previewOption;
      const fn = generatePreviewPathFn || this.defaultGeneratePreviewPath;

      const path = getFilePath();
      const previewPath = fn(item, path);

      window.open(previewPath, '_blank'); // 新窗口打开外链接
    },

    initData() {
      this.showUpdate = this.hasId;

      if (this.hasBusinessId) {
        this.getList();
      }
    },

    // 如果存在模版数据，需要初始化
    initList() {
      // 先初始化待上传列表
      this.attachmentTemplate.map((item) => {
        this.listTempRowAdd(item);
      });
      //  有id 为读取模式， 没id 为模版预览模式
      if (this.id) {
        this.getList();
        this.$forceUpdate();
      }
    },

    listRowAdd() {
      let newId = this.id + '_00' + (this.fileList.length + 1);

      if (this.newIds.includes(newId)) {
        newId = this.id + '_00' + (this.fileList.length + 18);
      }

      const fileItem = {
        elsAccount: this.elsAccount,
        businessItemId: newId
      };

      if (typeof this.addEmptyRowProcFn === 'function') {
        this.fileList.push(this.addEmptyRowProcFn(fileItem));
      } else {
        this.fileList.push(fileItem);
      }
    },

    listTempRowAdd(item) {
      const type = item?.attachmentType || item.fileType;

      if (type) {
        const fileItem = {
          businessItemId: this.id + type + (this.fileList.length + 1),
          attachmentType: type
        };

        this.fileList.push(fileItem);
      }
    },

    onFileProgress(rootFile, file, chunk) {
      this.uploading = true;
      this.isHideBtn = true;
      const progress = (chunk.startByte / file.size) * 100;
      this.uploadFileName = file.name;
      if (this.progress < progress) {
        this.progress = parseInt(progress, 10);
      }
    },

    onFileError() {
      this.$message.error(
        this.$ft('i18n_common_upload_failed_please_try_again', '上传失败，请重试')
      );
    },

    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) => {
              if (res.data.code === '200') {
                resolve({ result: true, code: res.data.code });
              } else {
                resolve({
                  result: false,
                  message: res.data.message,
                  code: res.data.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'
          // });
        }
      });
    },

    setUploadRow(row) {
      this.uploadRow = row;
    },

    updateFileList(file) {
      const action = this.uploadRow.attachmentName && this.uploadRow.uuid ? 'update' : 'create';

      const checkProp = 'businessItemId';

      let itemRow = {
        ...this.uploadRow,
        elsAccount: this.elsAccount,
        attachmentType: file.fileType,
        attachmentSize: renderSize(file.fileSize),
        attachmentName: file.fileName,
        attachmentDesc: file.fileName,
        attachmentUrl: file.filePath,
        businessModule: this.businessModule,
        businessElsAccount: this.businessElsAccount,
        businessId: this.businessId
      };

      if (this.moreFields) {
        itemRow.fbk1 = 'Y';
      }

      const uploadRow = {
        ...this.uploadRow,
        elsAttachmentInDTOList: [itemRow]
      };

      delete uploadRow.createDate;

      uploadApi
        .attachmentServer(action, uploadRow)
        .then((res) => {
          if (res.data.code === '200') {
            const resData = res.data.data;
            const elsAttachment = action === 'create' ? resData[0] : resData;
            itemRow = {
              ...itemRow,
              ...elsAttachment,
              attachmentType: file.fileType,
              elsAccount: res.data.data.elsAccount,
              elsSubAccount: res.data.data.elsSubAccount,
              createUser:
                elsAttachment.createUser || `${this.currentElsSubAccount}_${this.currentUserName}`,
              createDate: dayjs(elsAttachment.createDate).format(this.datetimeFormatTemplate),
              lastUpdateDate: dayjs(elsAttachment.lastUpdateDate).format(
                this.datetimeFormatTemplate
              )
            };
            this.fileList = this.fileList.map((item) => {
              return item[checkProp] === uploadRow[checkProp] ? itemRow : item;
            });
            this.$message.success(this.$ft('i18n_common_upload_successfully', '上传成功'));
            this.isHideBtn = false;
          } else {
            this.$message.error(
              res.data.message ||
                res.statusText ||
                this.$ft('i18n_common_upload_failed_please_try_again', '上传失败, 请重试')
            );
            this.isHideBtn = false;
          }
        })
        .catch((err) => {
          console.log('Error to upload a file.', err);
          this.$message.error(
            this.$ft('i18n_common_upload_failed_please_try_again', '上传失败, 请重试')
          );
          this.isHideBtn = false;
        });
    }
  }
};
</script>
<style>
.preview-btn {
  margin-left: 10px;
}
.operation-button-container {
  display: flex;
}
.annexType::after {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
.uploader-btn {
  padding: 0 !important;
  border: 1px solid #d9d9d9 !important;
}
.uploader-btn span {
  display: inline-block;
  margin: 4px 8px !important;
}
.file-btns {
  margin-bottom: 16px;
}
</style>
