import { PlusOutlined } from '@ant-design/icons';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, Modal, Tag, message } from 'antd';
import { useRef } from 'react';
import { history } from '@umijs/max';
import { cancelPurchaseOrder, confirmPurchaseOrder, listPurchaseOrders } from '@/services/api';
import type { PurchaseOrder } from '@/types/api';

const STATUS_MAP: Record<number, { text: string; color: string }> = {
  0: { text: '草稿', color: 'default' },
  1: { text: '已确认', color: 'processing' },
  2: { text: '已取消', color: 'error' },
};

const RECEIPT_STATUS_MAP: Record<number, string> = {
  0: '未入库',
  1: '部分入库',
  2: '已入库',
};

const PAYMENT_STATUS_MAP: Record<number, string> = {
  0: '未付款',
  1: '部分付款',
  2: '已付清',
};

const OrdersPage: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const handleConfirm = async (id: string) => {
    await confirmPurchaseOrder(id);
    message.success('确认成功');
    actionRef.current?.reload();
  };

  const handleCancel = async (id: string) => {
    await cancelPurchaseOrder(id);
    message.success('取消成功');
    actionRef.current?.reload();
  };

  const columns: ProColumns<PurchaseOrder>[] = [
    { title: '订单编号', dataIndex: 'orderNo', copyable: true },
    { title: '供应商', dataIndex: 'supplierName', search: false },
    { title: '采购日期', dataIndex: 'orderDate', search: false },
    { title: '合同金额', dataIndex: 'contractAmount', search: false },
    {
      title: '入库状态',
      dataIndex: 'receiptStatus',
      search: false,
      render: (_, r) => RECEIPT_STATUS_MAP[r.receiptStatus] ?? '-',
    },
    {
      title: '付款状态',
      dataIndex: 'paymentStatus',
      search: false,
      render: (_, r) => PAYMENT_STATUS_MAP[r.paymentStatus] ?? '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      search: false,
      render: (_, r) => {
        const s = STATUS_MAP[r.status] ?? STATUS_MAP[0];
        return <Tag color={s.color}>{s.text}</Tag>;
      },
    },
    { title: '创建时间', dataIndex: 'createdAt', valueType: 'dateTime', search: false },
    {
      title: '操作',
      valueType: 'option',
      render: (_, r) => [
        <a key="view" onClick={() => history.push(`/purchase/orders/${r.orderId}`)}>详情</a>,
        r.status === 0 && (
          <a key="confirm" onClick={() => Modal.confirm({ title: '确认采购订单?', onOk: () => handleConfirm(r.orderId) })}>确认</a>
        ),
        r.status === 1 && r.receiptStatus === 0 && (
          <a key="cancel" style={{ color: '#ff4d4f' }} onClick={() => Modal.confirm({ title: '确认取消?', onOk: () => handleCancel(r.orderId) })}>取消</a>
        ),
      ].filter(Boolean),
    },
  ];

  return (
    <ProTable<PurchaseOrder>
      actionRef={actionRef}
      headerTitle="采购订单"
      rowKey="orderId"
      columns={columns}
      request={async (params) => {
        const res = await listPurchaseOrders({ page: params.current, pageSize: params.pageSize });
        return { data: res?.data?.list || [], total: res?.data?.total || 0, success: res?.code === 0 };
      }}
      toolBarRender={() => [
        <Button key="add" type="primary" icon={<PlusOutlined />} onClick={() => history.push('/purchase/orders/new')}>创建采购订单</Button>,
      ]}
    />
  );
};

export default OrdersPage;
