<script lang="ts" setup>
import { ref } from 'vue';

import { Modal, notification, Tag, Upload } from 'ant-design-vue';

import { importBillsApi } from '#/api/posting';

interface Props {
  row: any;
  type: string;
  field: string;
}
const props = withDefaults(defineProps<Props>(), {});

// 定义自定义事件
const emit = defineEmits<{
  uploadSuccess: [];
}>();

const uploadRef = ref<any>(null);

function downloadFile(url: string) {
  window.open(url);
}

function handleClickUpload() {
  if (props.row[props.field]) {
    Modal.confirm({
      title: '提示',
      content: '重传会清空已上传的数据，确认重传吗？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        openFileDialog();
      },
    });
  } else {
    openFileDialog();
  }
}

function openFileDialog() {
  const input = uploadRef.value?.$el?.querySelector('input[type="file"]');
  input && input.click();
}

function beforeUpload() {
  return true;
}

async function uploadFile(options: any) {
  const { file } = options;

  // 使用 requestClient.upload 方法，它会自动处理 FormData
  await importBillsApi.uploadFile({
    file,
    year: props.row.year,
    month: props.row.month,
    type: props.type,
  });
  notification.success({
    message: '上传成功',
  });

  // message.success(`上传成功，大概需要10分钟解析核对数据，请耐心等待稍后查询。`);
  // 通知父组件刷新列表
  emit('uploadSuccess');
}
</script>

<template>
  <div>
    <span>
      <Tag v-if="props.row[props.field]" color="green">已上传</Tag>
      <Tag v-else color="orange">未上传</Tag>
    </span>

    <Tag v-if="props.row[props.field]" class="btn" @click="downloadFile(props.row[props.field])">
      下载文件
    </Tag>

    <Upload
      ref="uploadRef"
      :before-upload="beforeUpload"
      :custom-request="uploadFile"
      :show-upload-list="false"
      :open-file-dialog-on-click="false"
    >
      <Tag class="btn" @click="handleClickUpload">
        {{ props.row[props.field] ? '点击重传' : '点击上传' }}
      </Tag>
    </Upload>
  </div>
</template>

<style lang="scss" scoped>
.btn {
  cursor: pointer;
}
</style>
