<script setup lang="ts">
import type { TableColumnsType, TableRowSelection } from 'ant-design-vue';
import {
  Button,
  Card,
  Input,
  Modal,
  Space,
  Table,
  Tag,
  message,
} from 'ant-design-vue';
import { computed, h, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import type { FinanceApi } from '#/api/core/finance';
import { useFinanceStore } from '#/store/finance';

import { formatStatus } from './status';

defineOptions({ name: 'FinanceReimbursementApproval' });

const financeStore = useFinanceStore();
const router = useRouter();

const selectedRowKeys = ref<number[]>([]);
const loading = computed(() => financeStore.loading.reimbursements);
const pendingStatuses: FinanceApi.TransactionStatus[] = ['draft', 'pending'];

const reimbursements = computed(() =>
  financeStore.reimbursements
    .filter(
      (item) =>
        !item.isDeleted && pendingStatuses.includes(item.status),
    )
    .sort(
      (a, b) =>
        new Date(a.transactionDate).getTime() -
        new Date(b.transactionDate).getTime(),
    ),
);

const rowSelection = computed<TableRowSelection<FinanceApi.Transaction>>(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys) => {
    selectedRowKeys.value = keys as number[];
  },
}));

const columns: TableColumnsType<FinanceApi.Transaction> = [
  {
    title: '报销事项',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '报销日期',
    dataIndex: 'transactionDate',
    key: 'transactionDate',
    width: 140,
  },
  {
    title: '金额',
    key: 'amount',
    width: 140,
  },
  {
    title: '提交人',
    dataIndex: 'submittedBy',
    key: 'submittedBy',
    width: 120,
  },
  {
    title: '状态',
    key: 'status',
    width: 120,
  },
  {
    title: '操作',
    key: 'actions',
    width: 220,
    fixed: 'right',
  },
];

async function refresh() {
  await financeStore.fetchReimbursements();
}

async function updateStatus(
  record: FinanceApi.Transaction,
  status: FinanceApi.TransactionStatus,
  reviewNotes?: string | null,
) {
  await financeStore.updateReimbursement(record.id, {
    status,
    reviewNotes: reviewNotes ?? record.reviewNotes ?? null,
  });
  message.success('状态已更新');
}

function handleApprove(record: FinanceApi.Transaction) {
  updateStatus(record, 'approved');
}

function handleReject(record: FinanceApi.Transaction) {
  let notes = record.reviewNotes ?? '';
  Modal.confirm({
    title: '驳回报销申请',
    content: () =>
      h(Input.TextArea, {
        value: notes,
        rows: 3,
        onChange(event: any) {
          notes = event.target.value;
        },
        placeholder: '请输入驳回原因',
      }),
    okText: '确认驳回',
    cancelText: '取消',
    okButtonProps: { danger: true },
    async onOk() {
      await updateStatus(record, 'rejected', notes);
    },
  });
}

async function handleBulkApprove() {
  if (selectedRowKeys.value.length === 0) return;
  const list = financeStore.reimbursements.filter((item) =>
    selectedRowKeys.value.includes(item.id),
  );
  await Promise.all(
    list.map((item) =>
      financeStore.updateReimbursement(item.id, { status: 'approved' }),
    ),
  );
  message.success('已批量通过审批');
  selectedRowKeys.value = [];
}

function handleView(record: FinanceApi.Transaction) {
  router.push(`/reimbursement/detail/${record.id}`);
}

onMounted(() => {
  if (financeStore.reimbursements.length === 0) {
    refresh();
  }
});
</script>

<template>
  <div class="p-6 space-y-4">
    <Card>
      <template #title>审批队列</template>
      <template #extra>
        <Space>
          <Button :loading="loading" @click="refresh">刷新</Button>
          <Button
            type="primary"
            :disabled="selectedRowKeys.length === 0"
            @click="handleBulkApprove"
          >
            批量通过
          </Button>
        </Space>
      </template>
      <Table
        :columns="columns"
        :data-source="reimbursements"
        :loading="loading"
        :row-key="(record) => record.id"
        :row-selection="rowSelection"
        bordered
        :scroll="{ x: 820 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'amount'">
            <span class="font-medium">
              {{ record.amount.toFixed(2) }} {{ record.currency }}
            </span>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="formatStatus(record.status).color">
              {{ formatStatus(record.status).label }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'actions'">
            <Space>
              <Button size="small" type="primary" @click="handleApprove(record)">
                通过
              </Button>
              <Button size="small" danger @click="handleReject(record)">
                驳回
              </Button>
              <Button size="small" type="link" @click="handleView(record)">
                查看详情
              </Button>
            </Space>
          </template>
        </template>
        <template #emptyText>
          <span>当前没有待审批的报销申请</span>
        </template>
      </Table>
    </Card>
  </div>
</template>
