<template>
  <div class="container-fluid">
    <div>
      <h4 class="m-h4">
        {{ $t("lang.attachmentPanel.attachment") }}
        <a role="button" class="btn btn-primary" @click="addAttachment()">
          <i class="fa fa-upload" />&nbsp;{{
            $t("lang.attachmentPanel.addAttachment")
          }}
        </a>
      </h4>
    </div>
    <Modal
      v-model:show="attachmentUploadModal"
      :show-ok-button="false"
      full="true"
      @cancel="showAttachmentUpload = false"
    >
      <template #header>
        {{ $t("lang.attachmentPanel.uploadAttachment") }}
      </template>
      <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"
      />
    </Modal>
    <div class="row">
      <div
        v-for="(fileProperty, index) in fileProperties"
        :key="'attachment' + index"
        style="display: table-cell"
        class="col-xs-3 col-sm-3 col-md-2 col-lg-2"
      >
        <FileImage :file-property="fileProperty" :show-image="true" />
        <div style="display: flex">
          <a
            role="button"
            class="btn btn-link btn-sm"
            @click="downloadAttachment(fileProperty.fileName)"
          >
            <i class="fa fa-download" /> &nbsp;{{
              $t("lang.attachmentPanel.download")
            }}
          </a>
          <a
            v-if="isShowEdit == undefined || isShowEdit"
            role="button"
            class="btn btn-link btn-sm"
            @click="deleteAttachment(fileProperty.fileName)"
          >
            <i class="fa fa-trash-o" /> &nbsp;{{
              $t("lang.attachmentPanel.remove")
            }}
          </a>
          <a
            role="button"
            class="btn btn-link btn-sm"
            @click="previewFile(fileProperty.fileName)"
          >
            预览
          </a>
        </div>
        <div class="clearfix" />
        <a-modal
          v-model:open="visible"
          style="text-align:center"
          title="预览"
          ok-text="确认"
          cancel-text="取消"
          @ok="handleOk"
        >
          <a-image :width="200" :src="imgUrl" />
        </a-modal>
      </div>
    </div>
    <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';

export default {
  components: {
    FileImage,
    AttachmentUpload,
  },
  /**
   * 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 => {},
      );
    },

    /**
     * 下载附件
     */
    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,
      };
      AttachmentService.deleteAttachment(data).then(successData => {
        if (data.errorCode != 0) {
          // Notify.error(
          //   _self.$t('lang.Notify.warning'),
          //   successData.errorMessage,
          //   false,
          // );
        }
        _self.refresh();
      });
    },

    // 预览文件
    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>
.m-h4 {
  border: 1px solid #eee;
  border-top: none;
  border-left: none;
  border-right: none;
  padding-bottom: 10px;
}
</style>