<template>
  <div>
    <a-space class="attachment-header">
      <a-page-header :title="$t('lang.attachmentPanel.attachment')" :back-icon="false" style="padding: 0;">
        <template #extra>
          <!-- <a-button type="primary" @click="addAttachment()">
            <template #icon><upload-outlined /></template>
            {{ $t("lang.attachmentPanel.addAttachment") }}
          </a-button> -->
          <UploadWidget
            v-if="isShowEdit == undefined || isShowEdit" :file-type="fileType"
            @upload="uploadAttachment($event)"
          />
        </template>
      </a-page-header>
    </a-space>
    <a-modal
      v-model:open="attachmentUploadModal" :show-ok-button="false" width="60%"
      :title="$t('lang.attachmentPanel.uploadAttachment')" @cancel="showAttachmentUpload = false"
    >
      <AttachmentUpload
        v-if="showAttachmentUpload" :class-name="className" :record-id="recordId" :window-no="windowNo"
        :is-show-edit="isShowEdit" :file-type="fileType" @upload-success="refresh" @get-file="getFile"
      />
    </a-modal>


    <a-row :gutter="[16, 8]" class="file-list">
      <a-col
        v-for="(fileProperty, index) in fileProperties" :key="'attachment' + index" :xs="24" :sm="12" :md="8"
        :lg="6" :xl="4"
      >
        <div class="file-item">
          <FileImage :file-property="fileProperty" :show-image="true" />

          <a-space style="width: 100%;justify-content: center;">
            <a-button type="link" @click="downloadAttachment(fileProperty.fileName)">
              <download-outlined /> {{ $t("lang.attachmentPanel.download") }}
            </a-button>

            <a-button
              v-if="isShowEdit == undefined || isShowEdit" type="link" danger
              @click="deleteAttachment(fileProperty.fileName)"
            >
              <delete-outlined /> {{ $t("lang.attachmentPanel.remove") }}
            </a-button>

            <a-button type="link" @click="previewFile(fileProperty.fileName)">
              <eye-outlined /> 预览
            </a-button>
          </a-space>
        </div>
      </a-col>
    </a-row>

    <a-modal
      v-model:open="visible" title="预览" ok-text="确认" cancel-text="取消"
      :body-style="{ display: 'flex', justifyContent: 'center', alignItems: 'center' }" @ok="handleOk"
    >
      <a-image :width="200" :src="imgUrl" />
    </a-modal>
    <Loading v-if="loading" />
  </div>
</template>

<script>
import Common from '../../common/Common.js';
import AttachmentService from '../../resource/file/AttachmentService.js';
import DownloadService from '../../resource/file/DownloadService.js';
import { getImageSrc } from '../../common/image-src';
import FileImage from '../../widget/FileImage.vue';
import AttachmentUpload from './AttachmentUpload.vue';
import { Notify, Uuid } from 'pc-component-v3';
import {
  UploadOutlined,
  DownloadOutlined,
  DeleteOutlined,
  EyeOutlined,
} from '@ant-design/icons-vue';
export default {
  components: {
    FileImage,
    AttachmentUpload,
    UploadOutlined,
    DownloadOutlined,
    DeleteOutlined,
    EyeOutlined,
  },
  /**
   * className: 类名称
   * recordId: 记录Id
   * tabId: 页签Id
   * fileType: 附件类型,eg:".xls,.doc,.txt,.pdf"
   * isShowEdit: 显示上传控件(true:显示上传控件，false：不显示上传控件)
   */
  props: {
    className: {
      type: String,
      default: null,
    },
    recordId: {
      type: Number,
      default: null,
    },
    tabId: {
      type: Number,
      default: null,
    },
    fileType: {
      type: String,
      default: null,
    },
    isShowEdit: {
      type: Boolean,
      default: null,
    },
    windowNo: {
      type: String,
      default: null,
    },
    curdWindowFunctionAccess: {
      type: Object,
      default: function () {
        return null;
      },
    },
  },

  data: function () {
    return {
      fileProperties: [],
      type: 1,
      showAttachmentUpload: false,
      loading: false,
      attachmentUploadModal: false,
      imgUrl: '',
      visible: false,
    };
  },

  watch: {
    recordId: function () {
      this.refresh();
    },

    className: function () {
      this.refresh();
    },

    tabId: function () {
      this.refresh();
    },
  },

  mounted: function () {
    this.refresh();
  },

  methods: {
    getImageName: function (name) {
      const _self = this;
      return getImageSrc(_self.className, name);
    },
    /**
     * 刷新(获取文件属性)
     */
    refresh: function () {
      var _self = this;
      this.type = 1;
      this.attachmentUploadModal = false;
      this.showAttachmentUpload = false;
      if (
        this.className == undefined ||
        this.recordId == undefined ||
        this.windowNo == undefined
      ) {
        this.fileProperties.splice(0, this.fileProperties.length);
        return;
      }

      var data = {
        className: _self.className,
        recordId: _self.recordId,
      };

      AttachmentService.getFileProperties(data).then(
        successData => {
          _self.fileProperties.splice(0, _self.fileProperties.length);
          if (successData == undefined || successData.length == 0) {
            return;
          }

          for (var i = 0, len = successData.length; i < len; i++) {
            _self.fileProperties.push(successData[i]);
          }
        },
        error => { },
      );
    },

    // 上传附件
    uploadAttachment: function (files) {
      var _self = this;
      var selectedFile = files[0];
      if (selectedFile == undefined) {
        Notify.error(_self.$t('lang.Notify.prompt'), _self.$t('lang.attachmentUpload.mustSelectFile'), false);
        return;
      }
      var formData = new FormData();
      formData.append('attachment', selectedFile);
      formData.append('windowNo', _self.windowNo);
      formData.append('className', _self.className);
      formData.append('recordId', _self.recordId);
      formData.append('fileName', selectedFile.name);
      _self.loading = true;
      AttachmentService.uploadAttachment(formData).then(successData => {
        _self.loading = false;
        if (successData.errorCode == 0) {
          Notify.success(_self.$t('lang.attachmentUpload.uploadSucceeded'), _self.$t('lang.attachmentUpload.attachmentUploadedSuccessfully'), 1500);
        }
        if (successData.errorCode == 1) {
          Notify.error(_self.$t('lang.Notify.warning'), _self.$t('lang.attachmentUpload.noPermissionUploadAttachments'), false);
        }

        if (successData.errorCode) {
          Notify.error(_self.$t('lang.Notify.warning'), successData.errorMessage, false);
        }

        _self.refresh();
      }, error => {
        _self.loading = false;
        Common.processException(error);
      });
    },

    /**
     * 下载附件
     */
    downloadAttachment: function (fileName) {
      var _self = this;
      var className = _self.className;
      var recordId = _self.recordId;
      var windowNo = _self.windowNo;
      var url =
        Common.getApiURL('file/attachmentDownload') +
        '?className=' +
        className +
        '&windowNo=' +
        windowNo +
        '&recordId=' +
        recordId +
        '&fileName=' +
        fileName;
      DownloadService.downloadFile(url, fileName);
    },

    /**
     * 删除附件
     */
    deleteAttachment: function (fileName) {
      var _self = this;
      var data = {
        windowNo: _self.windowNo,
        className: _self.className,
        recordId: _self.recordId,
        tabId: _self.tabId,
        fileName: fileName,
      };
      _self.loading = true;
      AttachmentService.deleteAttachment(data).then(successData => {
        _self.loading = false;
        _self.refresh();
      }, error => {
        _self.loading = false;
        Common.processException(error);
      });
    },

    // 预览文件
    previewFile: function (name) {
      let flag = this.isPhotoPdf(name);
      let pdf = this.isPdf(name);
      var _self = this;
      var className = _self.className;
      var recordId = _self.recordId;
      var windowNo = _self.windowNo;
      let url =
        Common.getApiURL('file/attachmentDownload') +
        '?className=' +
        className +
        '&windowNo=' +
        windowNo +
        '&recordId=' +
        recordId +
        '&fileName=' +
        name;
      const xhr = new XMLHttpRequest();
      xhr.responseType = 'blob'; // 返回类型blob
      xhr.open('get', url, true);
      const token = localStorage.getItem('#token');
      xhr.setRequestHeader('token', token);
      xhr.onload = function () {
        if (this.status === 200) {
          if (flag) {
            // 图片
            _self.visible = true;
            _self.imgUrl = window.URL.createObjectURL(this.response);
          } else if (pdf) {
            // pdf文件
            let type = xhr.getResponseHeader('Content-Type');
            let blob = new Blob([this.response], {
              type: type,
            });
            let href = window.URL.createObjectURL(blob);
            window.open(href, '_blank');
          } else {
            // 其他文件
            _self.$message.error('仅支持预览图片和pdf文件');
          }

        }
      };
      xhr.send();
    },
    handleOk: function () {
      this.visible = false;
    },
    isPdf: function (name) {
      if (name.endsWith('.pdf')) {
        return true;
      } else {
        return false;
      }
    },
    isPhotoPdf: function (name) {
      var fileName = name;
      if (
        fileName.endsWith('.jpg') || //图片
        fileName.endsWith('.jpeg') ||
        fileName.endsWith('.bmp') ||
        fileName.endsWith('.gif') ||
        fileName.endsWith('.png')
      ) {
        return true;
      } else {
        return false;
      }
    },
    /**
     * 显示附件面板
     */
    addAttachment: function () {
      this.attachmentUploadModal = true;
      this.showAttachmentUpload = true;
    },
  },
};
</script>

<style scoped>
.attachment-header {
  padding: 8px 0;
}

.file-list {
  width: 100%;
}

.file-item {
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 8px;
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: all 0.3s;
}

.file-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 按钮组样式 */
:deep(.ant-space) {
  width: 100%;
}

/* :deep(.ant-space-item) {
  width: 100%;
} */
:deep(.ant-modal .ant-modal-body) {
  text-align: center;
}

:deep(.ant-btn-link) {
  width: 100%;
  text-align: left;
  height: 32px;
  padding: 4px 0;
}

:deep(.ant-btn-link:hover) {
  background: #f5f5f5;
}

/* 响应式调整 */
@media screen and (max-width: 576px) {
  .file-item {
    padding: 12px;
  }
}

@media screen and (min-width: 577px) and (max-width: 768px) {
  .file-list {
    margin-top: 16px;
  }
}

:deep(.ant-page-header .ant-page-header-heading-title) {
  font-size: 16px !important;
  font-weight: 500 !important;
}
</style>