<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">
        {{ labels.addRow }}
      </el-button>
    </h4>
    <fast2-theme-provider :option="readonly ? readOption : option" theme="block" :version="version">
      <template v-slot="component">
        <div v-if="component.option && component.option.column && component.option.column.length">
          <avue-crud
            ref="crud"
            :data="fileList"
            :option="handleOption(component.option)"
            @row-del="handleDelete"
            @row-update="handleUpdate"
          >
            <template v-slot:fileAction="scope">
              <div v-if="!readonly && downloadClient" @mouseover="setUploadRow(scope.row)">
                <fast2-upload
                  @file-success="fileSuccess"
                  @file-progress="onFileProgress"
                  @file-error="onFileError"
                  @click="setUploadRow(scope.row)"
                />
                <el-link
                  class="uploader-btn"
                  v-if="scope.row.attachmentUrl"
                  download
                  target="_blank"
                  @click="handleDownload(scope.row)"
                >
                  {{ labels.download }}
                </el-link>
              </div>
              <div v-else-if="downloadClient">
                <el-link
                  class="uploader-btn"
                  v-if="scope.row.attachmentUrl"
                  download
                  target="_blank"
                  @click="handleDownload(scope.row)"
                >
                  {{ labels.download }}
                </el-link>
              </div>
            </template>
            <template slot="annexType" slot-scope="{ row }">
              <span v-if="row.isRequired === 'Y'" class="annexType" />{{ row.annexType }}
            </template>
          </avue-crud>
        </div>
      </template>
    </fast2-theme-provider>
  </div>
</template>

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

const BaseUrl = getApiPath();

export default {
  name: 'RfqAttachmentList',
  props: {
    // 是否屏蔽下载供应商附件
    downloadClient: {
      type: Boolean,
      default: true
    },
    // 跳过 是否判断供应商以及供应商tab
    passClient: {
      type: Boolean,
      default: true
    },
    // 是否为供应商端
    client: {
      type: Boolean,
      default: true
    },
    // 是否为供应商tab
    clientTab: {
      type: Boolean,
      default: true
    },
    version: {
      type: String,
      default: 'attahcment-fiels_rfq'
    },
    readonly: {
      type: Boolean,
      default: false
    },
    menu: {
      type: Boolean,
      default: true
    },
    id: {
      type: String,
      default: null
    },
    elsAccount: {
      type: String,
      default: null
    },
    attachmentTemplate: {
      type: Array,
      default: function () {
        return [];
      }
    },
    businessElsAccount: {
      type: String,
      default: null
    },
    businessModule: {
      type: String,
      default: null
    },
    addBtn: {
      type: Boolean,
      default: true
    },
    delBtn: {
      type: Boolean,
      default: true
    },
    labels: {
      type: Object,
      default: function () {
        return {
          addRow: ft('i18n_common_add_details', '新增行'),
          attachment: ft('i18n_common_attachment', '附件'),
          cancel: ft('i18n_common_cancel', '取消'),
          confirm: ft('i18n_common_confirm', '确认'),
          done: ft('i18n_common_done', '结束'),
          download: ft('i18n_common_download', '下载'),
          noData: ft('i18n_common_no_data', '暂无数据'),
          uploadAttachment: ft('i18n_common_upload_attachment', '上传附件'),
          confirmDeleteTitle: ft('i18n_common_confirm_to_delete_this_attachment', '确认删除此附件?')
        };
      }
    },

    option: {
      type: Object,
      default: () => {
        return {
          editBtn: false,
          addBtn: false,
          delBtn: true,
          cancelBtn: false,
          cellBtn: true,
          showSummary: false,
          rowKey: 'businessItemId',
          column: [
            {
              i18nKey: 'i18n_common_file_type',
              label: '文件类型',
              prop: 'attachmentDesc',
              type: 'input',
              span: 8,
              cell: true,
              orderIndex: 0,
              order: 0
            },
            {
              i18nKey: 'i18n_common_file',
              label: '文件',
              prop: 'fileAction',
              slot: true
            }
          ]
        };
      }
    },
    readOption: {
      type: Object,
      default: () => {
        return {
          menu: false,
          detail: true,
          editBtn: false,
          addBtn: false,
          delBtn: false,
          cancelBtn: false,
          showSummary: false,
          column: [
            {
              i18nKey: 'i18n_common_file_type',
              label: '文件类型',
              prop: 'attachmentDesc',
              type: 'input',
              span: 8,
              orderIndex: 0,
              order: 1,
              slot: true
            },
            {
              i18nKey: 'i18n_common_file',
              label: '文件',
              prop: 'fileAction',
              slot: true
            }
          ]
        };
      }
    }
  },
  data() {
    return {
      currentUserName: '',
      currentElsAccount: '',
      currentElsSubAccount: '',
      showUpdate: true,
      uploadRow: null,
      fileList: [],
      businessId: '',
      uploader: null
    };
  },
  watch: {
    id(newValue) {
      this.businessId = newValue;
      this.initData();
    },
    attachmentTemplate() {
      this.initData();
    },
    fileList(newVal) {
      // console.log(newVal);
    }
  },
  mounted() {
    const currentUserInfo = getUserInfo();
    this.currentElsAccount = currentUserInfo.elsAccount;
    this.currentElsSubAccount = currentUserInfo.elsSubAccount;
    this.currentUserName = currentUserInfo.elsSubaccountInfoDTO.name || '';
    // this.initWebUpload();
    if (!validateNull(this.id)) {
      this.businessId = this.id;
      this.initData();
    }
  },
  methods: {
    doAction(action, data) {
      this.$emit(action, data);
      // this.$message.success(action)
    },

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

      const _this = this;

      this.$confirm({
        cancelText: this.labels.cancel,
        content: '',
        okText: this.labels.confirm,
        title: this.labels.confirmDeleteTitle,
        onOk() {
          uploadApi
            .deleteAttachment(row.uuid)
            .then((res) => {
              if (res.data && res.data.code === '200') {
                _this.fileList.splice(index, 1);
              } else {
                console.log('Failed to delete this 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 this attachment.', err);
              _this.$ft('i18n_common_failed_to_cancel_delete_attachment', '删除附件失败');
            });
        },
        onCancel() {}
      });
    },

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

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

    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) {
            const data = res.data.data;
            if (data && data.rows) {
              if (this.passClient) {
                this.fileList = data.rows;
              } else {
                if (this.client && this.clientTab) {
                  this.fileList = data.rows.filter((item) => item.elsAccount === this.elsAccount);
                } else if (this.client && !this.clientTab) {
                  this.fileList = data.rows.filter((item) => item.elsAccount !== this.elsAccount);
                } else if (!this.client && !this.clientTab) {
                  this.fileList = data.rows.filter(
                    (item) => item.elsAccount === this.businessElsAccount
                  );
                } else if (!this.client && this.clientTab) {
                  this.fileList = data.rows.filter(
                    (item) => item.elsAccount !== this.businessElsAccount
                  );
                }
              }
            }
            // businessItemId 根据该值判断 替换或直接push
            const itemIds = this.fileList.map((item) => item.businessItemId);
            this.attachmentTemplate.forEach((item) => {
              // item.isValidity = true; // TODO:
              if (itemIds.includes(item.businessItemId)) {
                const index = this.fileList.findIndex(
                  (file) => file.businessItemId === item.businessItemId
                );
                const i = this.fileList[index];
                item.isValidity === 'Y' && this.readonly === false
                  ? (i.$cellEdit = true)
                  : (i.$cellEdit = 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.isValidity === 'Y' && this.readonly === false
                  ? (item.$cellEdit = true)
                  : (item.$cellEdit = 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);
              }
            });
          } 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', '查询附件失败'));
        });
    },

    handleOption(option) {
      option.emptyText = this.labels.noData;

      const columns = option.column || [];

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

      return option;
    },

    initData() {
      this.showUpdate = !validateNull(this.id);
      if (!validateNull(this.businessId)) {
        this.option.delBtn = this.delBtn;
        this.getList();

        /*
        const dic = await this.$getDicItem('attachmentType');
        this.readOption.column.unshift({
          label: '文件类型',
          prop: 'attachmentType',
          type: 'select',
          order: 0,
          dicData: dic
        });
        */
      }
    },

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

    listRowAdd() {
      const fileItem = {
        $cellEdit: true,
        elsAccount: this.elsAccount,
        businessItemId: this.id + '_00' + (this.fileList.length + 1)
      };
      this.fileList.push(fileItem);
    },

    listTempRowAdd(item) {
      if (!item) {
        return;
      }
      const type = item.attachmentType || item.fileType;
      if (!type) {
        return;
      }
      const fileItem = {
        businessItemId: this.id + type + (this.fileList.length + 1),
        attachmentType: type
      };
      this.fileList.push(fileItem);
    },

    /*
    removeFile() {
      const action = 'delete';
      if (this.uploadRow.uuid) {
        uploadApi.attachmentServer(action, { uuid: this.uploadRow.uuid });
      }
    },
    */

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

    setUploadRow(row) {
      this.uploadRow = row;
    },
    fileSuccess(rootFile, file, message, chunk) {
      const data = JSON.parse(message).data;
      // 将面试邀请code和文件路径去保存到数据库中
      const fileData = {
        fileSize: data.size,
        fileName: data.name,
        fileType: data.type,
        filePath: data.url
      };
      this.$emit('upload-file', fileData);
      this.updateFileList(fileData);
    },
    onFileProgress() {
      console.log('文件上传中');
    },
    onFileError() {
      this.$message.error(
        this.$ft('i18n_common_upload_failed_please_try_again', '上传失败, 请重试')
      );
    },
    // 更新、创建文件数据接口
    uploadServer(action, itemRow, uploadRow) {
      uploadApi.attachmentServer(action, uploadRow).then((res) => {
        const code = res.data.statusCode || res.data.code;
        if (code === '200') {
          const resData = res.data.data;
          const elsAttachment = action === 'create' ? resData[0] : resData;
          itemRow = {
            ...itemRow,
            ...elsAttachment,
            elsAccount: res.data.data.elsAccount,
            elsSubAccount: res.data.data.elsSubAccount,
            createUser:
              elsAttachment.createUser || `${this.currentElsSubAccount}_${this.currentUserName}`,
            createDate: elsAttachment.createDate
              ? dayjs(new Date(elsAttachment.createDate)).format('YYYY-MM-DD HH:mm:ss')
              : dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
          };
          const checkProp = 'businessItemId';
          this.fileList = this.fileList.map((item) => {
            return item[checkProp] === uploadRow[checkProp] ? itemRow : item;
          });
          this.$message.success(
            action === 'create'
              ? this.$ft('i18n_common_upload_successfully', '上传成功')
              : this.$ft('i18n_common_update_successfully', '更新成功')
          );
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 行编辑保存
    handleUpdate(row, index, done, loading) {
      loading();
      this.$set(this.fileList, index, row);
      const uploadRow = {
        ...row,
        elsAttachmentVOList: [row]
      };
      this.uploadServer('update', row, uploadRow);
      done();
    },
    updateFileList(file) {
      const _this = this;
      const action = _this.uploadRow?.attachmentName
        ? 'update'
        : _this.uploadRow.uuid
        ? 'update'
        : 'create';
      const itemRow = {
        ...this.uploadRow,
        elsAccount: this.elsAccount,
        anneType: 'test',
        attachmentType: file.fileType,
        attachmentSize: renderSize(file.fileSize),
        attachmentName: file.fileName,
        attachmentUrl: file.filePath,
        businessModule: this.businessModule,
        businessElsAccount: this.businessElsAccount,
        businessId: this.businessId
      };
      const uploadRow = {
        ...this.uploadRow,
        elsAttachmentVOList: [itemRow]
      };
      delete uploadRow.createDate;
      this.uploadServer(action, itemRow, uploadRow);
    }
  }
};
</script>

<style lang="scss" scoped>
.annexType::after {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
</style>
