import { EyeOutlined, SendOutlined, CloseCircleOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProFormDateTimeRangePicker,
  ProFormSelect,
  ProFormText,
  ProTable,
  QueryFilter,
} from '@ant-design/pro-components';
import { useIntl, FormattedMessage } from '@umijs/max';
import { Button, Tag, theme, Drawer, message } from 'antd';
import React, { useRef, useState } from 'react';
import type { Order, OrderListParams, ShipForm, CancelForm } from './data';
import { queryOrderList, shipOrder, cancelOrder } from '@/services/order';
import {
  ORDER_STATUS_CONFIG,
  PAYMENT_METHOD_CONFIG,
  ORDER_STATUS_OPTIONS,
  PAYMENT_METHOD_OPTIONS,
} from './constants';
import OrderDetail from './components/OrderDetail';
import ShipFormComponent from './components/ShipForm';
import CancelOrderFormComponent from './components/CancelOrderForm';

const { useToken } = theme;

const OrderManagement: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const intl = useIntl();
  const { token } = useToken();

  // 搜索参数状态
  const [searchParams, setSearchParams] = useState<OrderListParams>({});

  // 订单详情抽屉
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [currentOrder, setCurrentOrder] = useState<Order | null>(null);

  // 发货表单
  const [shipFormVisible, setShipFormVisible] = useState<boolean>(false);
  const [shipOrderId, setShipOrderId] = useState<string>('');

  // 取消订单表单
  const [cancelFormVisible, setCancelFormVisible] = useState<boolean>(false);
  const [cancelOrderId, setCancelOrderId] = useState<string>('');

  // 表格列定义
  const columns: ProColumns<Order>[] = [
    {
      title: intl.formatMessage({ id: 'order.column.orderNo', defaultMessage: '订单编号' }),
      dataIndex: 'orderNo',
      width: 160,
      render: (text) => <span style={{ fontWeight: 'bold' }}>{text}</span>,
    },
    {
      title: intl.formatMessage({ id: 'order.column.customerName', defaultMessage: '客户姓名' }),
      dataIndex: 'customerName',
      width: 100,
    },
    {
      title: intl.formatMessage({ id: 'order.column.customerPhone', defaultMessage: '联系电话' }),
      dataIndex: 'customerPhone',
      width: 130,
    },
    {
      title: intl.formatMessage({ id: 'order.column.items', defaultMessage: '商品数量' }),
      dataIndex: 'items',
      width: 90,
      hideInSearch: true,
      render: (_, record) => (
        <Tag color="blue">{record.items.length} 件商品</Tag>
      ),
    },
    {
      title: intl.formatMessage({ id: 'order.column.totalAmount', defaultMessage: '订单金额' }),
      dataIndex: 'totalAmount',
      width: 120,
      hideInSearch: true,
      render: (_, record) => (
        <span style={{ color: token.colorError, fontWeight: 'bold', fontSize: 15 }}>
          ¥{record.totalAmount.toLocaleString()}
        </span>
      ),
    },
    {
      title: intl.formatMessage({ id: 'order.column.status', defaultMessage: '订单状态' }),
      dataIndex: 'status',
      width: 100,
      render: (_, record) => (
        <Tag color={ORDER_STATUS_CONFIG[record.status].color}>
          {ORDER_STATUS_CONFIG[record.status].label}
        </Tag>
      ),
    },
    {
      title: intl.formatMessage({ id: 'order.column.paymentMethod', defaultMessage: '支付方式' }),
      dataIndex: 'paymentMethod',
      width: 100,
      hideInSearch: true,
      render: (_, record) => (
        <Tag color={PAYMENT_METHOD_CONFIG[record.paymentMethod].color}>
          {PAYMENT_METHOD_CONFIG[record.paymentMethod].label}
        </Tag>
      ),
    },
    {
      title: intl.formatMessage({ id: 'order.column.createdAt', defaultMessage: '下单时间' }),
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      width: 160,
      hideInSearch: true,
      sorter: true,
    },
    {
      title: intl.formatMessage({ id: 'common.action', defaultMessage: '操作' }),
      valueType: 'option',
      width: 200,
      fixed: 'right',
      render: (_, record) => {
        const actions = [
          <Button
            type="link"
            key="view"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => {
              setCurrentOrder(record);
              setDetailVisible(true);
            }}
          >
            <FormattedMessage id="order.action.viewDetail" defaultMessage="查看详情" />
          </Button>,
        ];

        // 已支付状态可以发货
        if (record.status === 'paid') {
          actions.push(
            <Button
              type="link"
              key="ship"
              size="small"
              icon={<SendOutlined />}
              onClick={() => {
                setShipOrderId(record.id);
                setShipFormVisible(true);
              }}
            >
              <FormattedMessage id="order.action.ship" defaultMessage="发货" />
            </Button>,
          );
        }

        // 待支付或已支付状态可以取消
        if (record.status === 'pending' || record.status === 'paid') {
          actions.push(
            <Button
              type="link"
              key="cancel"
              size="small"
              danger
              icon={<CloseCircleOutlined />}
              onClick={() => {
                setCancelOrderId(record.id);
                setCancelFormVisible(true);
              }}
            >
              <FormattedMessage id="order.action.cancel" defaultMessage="取消" />
            </Button>,
          );
        }

        return actions;
      },
    },
  ];

  // 处理搜索表单提交
  const handleSearchFinish = (values: OrderListParams) => {
    const { timeRange, ...restValues } = values;
    if (timeRange && timeRange.length === 2) {
      setSearchParams({
        ...restValues,
        timeRange,
      });
    } else {
      setSearchParams(restValues);
    }
    actionRef.current?.reload();
  };

  // 卡片样式
  const cardStyle: React.CSSProperties = {
    background: token.colorBgContainer,
    borderRadius: token.borderRadius,
    marginBottom: token.marginLG,
  };

  // 表格请求方法
  const fetchOrderList = async (params: any, sort: any, filter: any) => {
    const result = await queryOrderList({
      ...searchParams,
      ...params,
    });
    return {
      data: result.data || [],
      success: result.success,
      total: result.total || 0,
    };
  };

  // 发货提交
  const handleShipSubmit = async (values: ShipForm) => {
    const hide = message.loading(intl.formatMessage({ id: 'common.loading', defaultMessage: '处理中...' }));
    try {
      await shipOrder(shipOrderId, values);
      hide();
      message.success(intl.formatMessage({ id: 'order.ship.success', defaultMessage: '发货成功' }));
      setShipFormVisible(false);
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error(intl.formatMessage({ id: 'order.ship.error', defaultMessage: '发货失败' }));
      return false;
    }
  };

  // 取消订单提交
  const handleCancelSubmit = async (values: CancelForm) => {
    const hide = message.loading(intl.formatMessage({ id: 'common.loading', defaultMessage: '处理中...' }));
    try {
      await cancelOrder(cancelOrderId, values);
      hide();
      message.success(intl.formatMessage({ id: 'order.cancel.success', defaultMessage: '订单已取消' }));
      setCancelFormVisible(false);
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error(intl.formatMessage({ id: 'order.cancel.error', defaultMessage: '取消失败' }));
      return false;
    }
  };

  return (
    <PageContainer
      header={{
        title: intl.formatMessage({ id: 'order.page.title', defaultMessage: '订单管理' }),
      }}
    >
      {/* 搜索区域 */}
      <div style={cardStyle}>
        <QueryFilter<OrderListParams>
          layout="vertical"
          defaultColsNumber={4}
          onFinish={handleSearchFinish}
          onReset={() => {
            setSearchParams({});
            actionRef.current?.reload();
          }}
          submitter={{
            searchConfig: {
              submitText: intl.formatMessage({ id: 'common.search', defaultMessage: '查询' }),
              resetText: intl.formatMessage({ id: 'common.reset', defaultMessage: '重置' }),
            },
          }}
        >
          <ProFormText
            name="orderNo"
            label={intl.formatMessage({ id: 'order.search.orderNo', defaultMessage: '订单编号' })}
            placeholder={intl.formatMessage({ id: 'order.search.orderNo.placeholder', defaultMessage: '请输入订单编号' })}
          />
          <ProFormText
            name="customerName"
            label={intl.formatMessage({ id: 'order.search.customerName', defaultMessage: '客户姓名' })}
            placeholder={intl.formatMessage({ id: 'order.search.customerName.placeholder', defaultMessage: '请输入客户姓名' })}
          />
          <ProFormSelect
            name="status"
            label={intl.formatMessage({ id: 'order.search.status', defaultMessage: '订单状态' })}
            placeholder={intl.formatMessage({ id: 'order.search.status.placeholder', defaultMessage: '请选择订单状态' })}
            options={ORDER_STATUS_OPTIONS}
          />
          <ProFormSelect
            name="paymentMethod"
            label={intl.formatMessage({ id: 'order.search.paymentMethod', defaultMessage: '支付方式' })}
            placeholder={intl.formatMessage({ id: 'order.search.paymentMethod.placeholder', defaultMessage: '请选择支付方式' })}
            options={PAYMENT_METHOD_OPTIONS}
          />
          <ProFormDateTimeRangePicker
            name="timeRange"
            label={intl.formatMessage({ id: 'order.search.timeRange', defaultMessage: '下单时间' })}
            placeholder={[
              intl.formatMessage({ id: 'order.search.startTime', defaultMessage: '开始时间' }),
              intl.formatMessage({ id: 'order.search.endTime', defaultMessage: '结束时间' }),
            ]}
            fieldProps={{
              showTime: true,
              format: 'YYYY-MM-DD HH:mm:ss',
            }}
          />
        </QueryFilter>
      </div>

      {/* 表格区域 */}
      <div style={cardStyle}>
        <ProTable<Order>
          headerTitle={intl.formatMessage({ id: 'order.table.title', defaultMessage: '订单列表' })}
          actionRef={actionRef}
          rowKey="id"
          search={false}
          options={{
            reload: true,
            density: true,
            fullScreen: true,
            setting: true,
          }}
          columns={columns}
          request={fetchOrderList}
          pagination={{
            pageSize: 20,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total: number) =>
              intl.formatMessage(
                {
                  id: 'order.pagination.total',
                  defaultMessage: '共 {total} 条记录',
                },
                { total },
              ),
          }}
          scroll={{ x: 1400 }}
        />
      </div>

      {/* 订单详情抽屉 */}
      <Drawer
        title={intl.formatMessage({ id: 'order.detail.title', defaultMessage: '订单详情' })}
        placement="right"
        width={720}
        open={detailVisible}
        onClose={() => {
          setDetailVisible(false);
          setCurrentOrder(null);
        }}
      >
        <OrderDetail visible={detailVisible} order={currentOrder} onClose={() => setDetailVisible(false)} />
      </Drawer>

      {/* 发货表单 */}
      <ShipFormComponent
        visible={shipFormVisible}
        onVisibleChange={setShipFormVisible}
        onSubmit={handleShipSubmit}
      />

      {/* 取消订单表单 */}
      <CancelOrderFormComponent
        visible={cancelFormVisible}
        onVisibleChange={setCancelFormVisible}
        onSubmit={handleCancelSubmit}
      />
    </PageContainer>
  );
};

export default OrderManagement;
