<template>
  <a-tag
    v-for="attachment in attachments"
    :key="attachment.id"
    :closable="enableDelete"
  >
    <template #icon>
      <paper-clip-outlined />
    </template>

    <template #closeIcon>
      <a-popconfirm
        title="您确定要删除此附件吗?"
        ok-text="确定"
        cancel-text="取消"
        @confirm="deleteAttachment(attachment)"
      >
        <close-outlined />
      </a-popconfirm>
    </template>

    <a-popover title="附件信息" trigger="click">
      <template #content>
        <p class="attachment-prop">附件名称: {{ attachment.name }}</p>
        <p class="attachment-prop">上传人: {{ attachment.createUserName }}</p>
        <p class="attachment-prop">上传时间: {{ attachment.time }}</p>
        <p class="attachment-prop">
          <a href="javascript: void(0)" @click="downloadAttachment(attachment)">
            下载
          </a>
        </p>
      </template>
      <span style="cursor: pointer">
        {{ attachment.name }}
      </span>
    </a-popover>
  </a-tag>
</template>

<script>
import Common from '../common/Common.js';
import { message } from 'ant-design-vue';
import { PaperClipOutlined, CloseOutlined } from '@ant-design/icons-vue';
export default {
  components: {
    PaperClipOutlined,
    CloseOutlined,
  },
  props: {
    /**
     * 是否启用删除附件
     */
    enableDelete: {
      type: Boolean,
      default: false,
    },
    /**
     * 附件列表
     */
    attachments: {
      type: Array,
      default: function () {
        return [];
      },
    },
  },

  methods: {
    deleteAttachment: function (attachment) {
      var _self = this;
    },

    /**
     * 下载附件
     */
    downloadAttachment: function (attachment) {
      const url = Common.getApiURL(
        'WorkflowResource/downloadAttachment?url=' +
          encodeURIComponent(attachment.url),
      );
      const xhr = new XMLHttpRequest();
      xhr.open('get', url, true);
      const token = localStorage.getItem('#token');
      xhr.setRequestHeader('token', token);
      xhr.setRequestHeader('Content-type', 'application/json');
      xhr.responseType = 'blob';
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          let res = xhr.response;
          let blob = new Blob([res]);
          const blobUrl = URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.download = attachment.name;
          link.style.display = 'none';
          link.href = blobUrl;
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(blobUrl);
          document.body.removeChild(link);
          message.success('下载成功');
        }
      };
      xhr.send();
    },
  },
};
</script>

<style scoped>
.attachment-prop{
    margin-bottom: 0px;
}
</style>
