<script lang="ts" setup>
/**
 * 门店/供应商/配送仓「我的开票」：仅本方受理与开票
 */
import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button, Modal, Space, Tag, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import FilePreviewModal from '#/components/file-preview/FilePreviewModal.vue';

import { acceptMyInvoiceApi } from './api';
import CompleteModal from './components/CompleteModal.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';

defineOptions({ name: 'MyInvoiceTodo' });

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [CompleteModalComp, completeModalApi] = useVbenModal({
  connectedComponent: CompleteModal,
});

const previewOpen = ref(false);
const previewFiles = ref<string[]>([]);

function partyStatusColor(status: number) {
  if (status === 0) return 'processing';
  if (status === 1) return 'warning';
  if (status === 2) return 'success';
  return 'default';
}

function handleAccept(row: any) {
  Modal.confirm({
    title: '确认受理本方开票？',
    content: `开票方 ${row.party_name || ''}，金额 ￥${row.amount || '0'}`,
    async onOk() {
      await acceptMyInvoiceApi({ party_id: row.id, invoice_id: row.invoice_id });
      message.success('本方已受理');
      gridApi.reload();
    },
  });
}

function openComplete(row: any) {
  completeModalApi.setData({ ...row, gridApi });
  completeModalApi.open();
}

function openPreview(files: string[]) {
  if (!files?.length) {
    message.info('暂无文件');
    return;
  }
  previewFiles.value = files;
  previewOpen.value = true;
}
</script>

<template>
  <Page auto-content-height title="我的开票">
    <CompleteModalComp />
    <FilePreviewModal v-model:open="previewOpen" :files="previewFiles" title="发票预览" />
    <Grid>
      <template #toolbar-actions />
      <template #status="{ row }">
        <Tag :color="partyStatusColor(row.status)">
          {{ row.status_text }}
        </Tag>
      </template>
      <template #action="{ row }">
        <Space>
          <Button
            v-if="row.status === 0"
            type="link"
            size="small"
            @click="handleAccept(row)"
          >
            受理
          </Button>
          <Button
            v-if="row.status === 1"
            type="link"
            size="small"
            @click="openComplete(row)"
          >
            上传发票
          </Button>
          <Button
            v-if="row.status === 2 && row.invoice_files?.length"
            type="link"
            size="small"
            @click="openPreview(row.invoice_files)"
          >
            预览
          </Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
