import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType, ProTableProps } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { App, Tag, Button } from 'antd';
import dayjs from 'dayjs';
import { ordercontrollerGetorders } from '@/servers/api/order';
import OrderDetailDrawer from './OrderDetailDrawer';
import { sitecontrollerAll } from '@/servers/api/site';

interface OrderItemRow {
  id: number;
  externalOrderId: string;
  siteId: string;
  date_created: string;
  customer_email: string;
  payment_method: string;
  total: number;
  orderStatus: string;
}

const OrdersPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const { message } = App.useApp();
  // 抽屉状态:改为复用订单详情抽屉组件
  const [detailOpen, setDetailOpen] = useState(false);
  const [detailRecord, setDetailRecord] = useState<any | null>(null);
  const [detailOrderId, setDetailOrderId] = useState<number | null>(null);
  const Noop: React.FC<any> = () => null;

  const columns: ProColumns<OrderItemRow>[] = [
    {
      title: '订单ID',
      dataIndex: 'externalOrderId',
      width: 120,
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '站点',
      dataIndex: 'siteId',
      width: 120,
      valueType: 'select',
      request: async () => {
        const { data = [] } = await sitecontrollerAll();
        return (data || []).map((item: any) => ({ label: item.siteName, value: item.id }));
      },
    },
    {
      title: '下单时间',
      dataIndex: 'date_created',
      width: 180,
      hideInSearch: true,
      render: (_, row) => (row?.date_created ? dayjs(row.date_created).format('YYYY-MM-DD HH:mm') : '-'),
    },
    {
      title: '邮箱',
      dataIndex: 'customer_email',
      width: 200,
    },
    {
      title: '支付方式',
      dataIndex: 'payment_method',
      width: 140,
    },
    {
      title: '金额',
      dataIndex: 'total',
      width: 100,
      hideInSearch: true,
    },
    {
      title: 'ERP状态',
      dataIndex: 'orderStatus',
      width: 120,
      hideInSearch: true,
      render: (_, row) => <Tag>{row.orderStatus}</Tag>,
    },
    {
      title: '订阅关联',
      dataIndex: 'subscription_related',
      width: 120,
      hideInSearch: true,
      render: (_, row) => (
        <Button
          size="small"
          onClick={() => {
            setDetailRecord(row as any);
            setDetailOrderId(row.id as number);
            setDetailOpen(true);
          }}
        >
          查看
        </Button>
      ),
    },
    {
      title: '时间范围',
      dataIndex: 'dateRange',
      valueType: 'dateRange',
      hideInTable: true,
    },
    {
      title: '商品关键字',
      dataIndex: 'keyword',
      hideInTable: true,
    },
  ];

  const request: ProTableProps<OrderItemRow>['request'] = async (params) => {
    try {
      const { current = 1, pageSize = 10, siteId, keyword, customer_email, payment_method } = params as any;
      const [startDate, endDate] = (params as any).dateRange || [];
      const resp = await ordercontrollerGetorders({
        current,
        pageSize,
        siteId,
        keyword,
        customer_email,
        payment_method,
        isSubscriptionOnly: true as any,
        startDate: startDate ? (dayjs(startDate).toISOString() as any) : undefined,
        endDate: endDate ? (dayjs(endDate).toISOString() as any) : undefined,
      } as any);
      const { success, data, message: errMsg } = resp as any;
      if (!success) throw new Error(errMsg || '获取失败');
      return {
        data: (data?.items ?? []) as OrderItemRow[],
        total: data?.total ?? 0,
        success: true,
      };
    } catch (e: any) {
      message.error(e?.message || '获取失败');
      return { data: [], total: 0, success: false };
    }
  };

  return (
    <PageContainer title='订阅订单'>
      <ProTable<OrderItemRow>
        actionRef={actionRef}
        rowKey='id'
        columns={columns}
        request={request}
        pagination={{ showSizeChanger: true }}
        search={{
          labelWidth: 90,
          span: 6,
        }}
        toolBarRender={false}
      />
      {/* 订阅关联:直接使用订单详情抽屉组件 */}
      {detailRecord && detailOrderId !== null && (
        <OrderDetailDrawer
          open={detailOpen}
          onClose={() => setDetailOpen(false)}
          tableRef={actionRef}
          orderId={detailOrderId as number}
          record={detailRecord as any}
          setActiveLine={() => {}}
          OrderNoteComponent={Noop}
          SalesChangeComponent={Noop}
        />
      )}
    </PageContainer>
  );
};

export default OrdersPage;
