<script lang="ts" setup>
/**
 * 财务开票中心：各方分别受理/开票（平台仅操作本方份额）
 */
import { computed, onMounted, ref } from 'vue';

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

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

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

import {
  acceptInvoiceApi,
  getInvoiceStatusStatsApi,
  resendInvoiceEmailApi,
} from './api';
import CompleteModal from './components/CompleteModal.vue';
import RejectModal from './components/RejectModal.vue';
import { formOptions } from './config/search';
import { createGridOptions } from './config/table';

defineOptions({ name: 'FinanceInvoiceCenter' });

const TAB_STORAGE_KEY = 'finance-invoice-center-tab';
const TAB_KEYS = ['0', '1', '2', '9', 'all'] as const;

function readStoredTab(): string {
  const stored = localStorage.getItem(TAB_STORAGE_KEY);
  if (stored && (TAB_KEYS as readonly string[]).includes(stored)) {
    return stored;
  }
  return '0';
}

const activeTab = ref<string>(readStoredTab());
const statusFilter = computed(() =>
  activeTab.value === 'all' ? '' : activeTab.value,
);

const statusStats = ref<Record<string, number>>({
  '0': 0,
  '1': 0,
  '2': 0,
  '9': 0,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions: createGridOptions(() => statusFilter.value),
});

function reloadAll() {
  gridApi.reload();
  loadStatusStats();
}

const gridApiWithStats = {
  reload: reloadAll,
};

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

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

async function loadStatusStats() {
  try {
    const res: any = await getInvoiceStatusStatsApi();
    const data = res?.data ?? res ?? {};
    statusStats.value = {
      '0': Number(data['0'] ?? data[0] ?? 0),
      '1': Number(data['1'] ?? data[1] ?? 0),
      '2': Number(data['2'] ?? data[2] ?? 0),
      '9': Number(data['9'] ?? data[9] ?? 0),
    };
  } catch {
    // ignore
  }
}

function handleTabChange(key: string | number) {
  const next = String(key);
  activeTab.value = next;
  localStorage.setItem(TAB_STORAGE_KEY, next);
  reloadAll();
}

/** 本方 party 状态：0待受理 1待开票 2已开票 */
function myPartyStatus(row: any) {
  return Number(row?.my_party?.status ?? -1);
}

async function handleAccept(row: any) {
  Modal.confirm({
    title: '确认受理本方开票？',
    content: `仅受理平台份额（￥${row?.my_party?.amount || '0'}），不影响其他分账方`,
    async onOk() {
      await acceptInvoiceApi({ id: row.id, party_id: row?.my_party?.id });
      message.success('本方已受理');
      reloadAll();
    },
  });
}

function openReject(row: any) {
  rejectModalApi.setData({ id: row.id, gridApi: gridApiWithStats });
  rejectModalApi.open();
}

function openComplete(row: any) {
  const party = row.my_party;
  if (!party?.id) {
    message.warning('当前账号在该申请下无平台开票份额');
    return;
  }
  completeModalApi.setData({
    id: row.id,
    party_id: party.id,
    amount: party.amount,
    party_name: party.party_name || '平台',
    email: row.email,
    gridApi: gridApiWithStats,
  });
  completeModalApi.open();
}

async function handleResend(row: any) {
  Modal.confirm({
    title: '确认重发邮件？',
    content: `将再次发送至 ${row.email || ''}`,
    async onOk() {
      await resendInvoiceEmailApi({ id: row.id });
      message.success('邮件已重发');
      reloadAll();
    },
  });
}

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

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

onMounted(() => {
  loadStatusStats();
});
</script>

<template>
  <Page auto-content-height title="开票中心">
    <RejectModalComp />
    <CompleteModalComp />
    <FilePreviewModal v-model:open="previewOpen" :files="previewFiles" title="发票预览" />
    <Tabs :active-key="activeTab" class="mb-2" @change="handleTabChange">
      <Tabs.TabPane key="0">
        <template #tab>
          <Badge :count="statusStats['0']" :offset="[10, 0]" :number-style="{ fontSize: '12px' }">
            <span>待受理</span>
          </Badge>
        </template>
      </Tabs.TabPane>
      <Tabs.TabPane key="1">
        <template #tab>
          <Badge :count="statusStats['1']" :offset="[10, 0]" :number-style="{ fontSize: '12px' }">
            <span>开票中</span>
          </Badge>
        </template>
      </Tabs.TabPane>
      <Tabs.TabPane key="2">
        <template #tab>
          <Badge :count="statusStats['2']" :offset="[10, 0]" :number-style="{ fontSize: '12px' }">
            <span>已完成</span>
          </Badge>
        </template>
      </Tabs.TabPane>
      <Tabs.TabPane key="9">
        <template #tab>
          <Badge :count="statusStats['9']" :offset="[10, 0]" :number-style="{ fontSize: '12px' }">
            <span>已拒绝</span>
          </Badge>
        </template>
      </Tabs.TabPane>
      <Tabs.TabPane key="all" tab="全部" />
    </Tabs>
    <Grid>
      <template #toolbar-actions />
      <template #status="{ row }">
        <Tag :color="statusColor(row.status)">{{ row.status_text }}</Tag>
      </template>
      <template #party_progress="{ row }">
        <span>{{ row.party_progress || '-' }}</span>
        <Tag v-if="row.my_party" class="ml-1" color="blue">
          本方：{{ row.my_party.status_text || '-' }}
        </Tag>
      </template>
      <template #action="{ row }">
        <Space>
          <Button
            v-if="myPartyStatus(row) === 0 && row.status !== 9"
            type="link"
            size="small"
            @click="handleAccept(row)"
          >
            受理本方
          </Button>
          <Button
            v-if="row.status === 0 && myPartyStatus(row) === 0"
            type="link"
            size="small"
            danger
            @click="openReject(row)"
          >
            拒绝
          </Button>
          <Button
            v-if="myPartyStatus(row) === 1"
            type="link"
            size="small"
            @click="openComplete(row)"
          >
            上传本方发票
          </Button>
          <Button
            v-if="row.my_party?.invoice_files?.length"
            type="link"
            size="small"
            @click="openPreview(row.my_party.invoice_files)"
          >
            预览本方
          </Button>
          <Button
            v-if="row.status === 2 && row.invoice_files?.length"
            type="link"
            size="small"
            @click="openPreview(row.invoice_files)"
          >
            查看全部
          </Button>
          <Button
            v-if="row.status === 2 && row.email"
            type="link"
            size="small"
            @click="handleResend(row)"
          >
            重发邮件
          </Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
