import BaseIndex from '@/components/Base/BaseIndex';
import BaseSearch from '@/components/Base/BaseSearch';
import BaseTable from '@/components/Base/BaseTable';
import Helper from '@/util/searchHelper';
import { ActionType } from '@ant-design/pro-components';
import { Button } from 'antd';
import { useEffect, useRef, useState } from 'react';
// import DetailModal from "./detailModal";
import { _getOrderTransactionList } from '@/services/transition';
import { exportToExcel } from '@/util/exportToExcel';
import { DownloadOutlined } from '@ant-design/icons';
import { history, useLocation } from '@umijs/max';
import dayjs from 'dayjs';
import { OrderTransactionColumns } from './OrderTransactionColumns';
export default function Index() {
  const [transitionSearchKey, setTransitionSearchKey] = useState('');
  const transitionTableRef = useRef<ActionType>();
  const [exporting, setExporting] = useState(false);
  const location = useLocation();

  // 处理 URL 参数
  useEffect(() => {
    const params = new URLSearchParams(location.search);
    const customerIdFromUrl = params.get('customerId');
    if (customerIdFromUrl) {
      setTransitionSearchKey(customerIdFromUrl);
    }
  }, [location]);

  const handleExport = async () => {
    setExporting(true);
    try {
      const response = await _getOrderTransactionList();
      let data = response.data;

      if (transitionSearchKey) {
        data = Helper<Page_Customer.CustomerTable>({
          dataSource: data,
          keyWord: transitionSearchKey,
        });
      }
      await exportToExcel({
        filename: `交易記錄`,
        data,
        columns: [
          {
            title: '訂單編號',
            dataIndex: 'format_order_id',
            width: 30,
          },
          {
            title: '用戶暱稱',
            dataIndex: ['user', 'nickname'],
            width: 15,
          },
          {
            title: '用戶電話',
            dataIndex: ['user', 'phone'],
            width: 15,
          },
          {
            title: '充電槍',
            dataIndex: ['connector', 'ConnectorName'],
            width: 15,
          },
          {
            title: '車位號',
            dataIndex: ['connector', 'park'],
            width: 10,
          },
          {
            title: '訂單狀態',
            dataIndex: ['status', 'description'],
            width: 15,
          },
          {
            title: '充電量(kWh)',
            dataIndex: 'actual_total_power',
            width: 15,
            render: (value) => value || '-',
          },
          {
            title: '预收費用(HK$)',
            dataIndex: 'total_fee',
            width: 15,
            render: (value) => value || 0,
          },
          {
            title: '實際費用',
            dataIndex: 'actual_fee',
            width: 100,
            render: (_, record) =>
              record.total_fee - record.withdraw_fee
                ? `HKD$${record.total_fee - record.withdraw_fee}`
                : '-',
          },
          {
            title: '退款',
            dataIndex: 'refund_fee',
            width: 100,
            render: (_, record) => (record.withdraw_fee ? `HKD$${record.withdraw_fee}` : '-'),
          },
          {
            title: '罰金(HK$)',
            dataIndex: 'penalty_fee',
            width: 15,
            render: (value) => value || '-',
          },
          {
            title: '預約時間',
            dataIndex: 'book_time',
            width: 20,
            render: (value) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
          },
          {
            title: '實際開始時間',
            dataIndex: 'actual_start_time',
            width: 20,
            render: (value) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
          },
          {
            title: '預計結束時間',
            dataIndex: 'end_time',
            width: 20,
            render: (value) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
          },
          {
            title: '實際結束時間',
            dataIndex: 'actual_end_time',
            width: 20,
            render: (value) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
          },
          {
            title: '支付狀態',
            dataIndex: 'paid_status',
            width: 15,
            render: (value) => (value ? '已支付' : '未支付'),
          },
          {
            title: '罰金支付狀態',
            dataIndex: 'penalty_paid_status',
            width: 15,
            render: (value, record) => (record.penalty_fee ? (value ? '已支付' : '未支付') : '-'),
          },
          {
            title: '備註',
            dataIndex: 'remark',
            width: 20,
          },
          {
            title: '創建時間',
            dataIndex: 'createdAt',
            width: 20,
            render: (value) => dayjs(value as string).format('YYYY-MM-DD HH:mm:ss'),
          },
          {
            title: '更新時間',
            dataIndex: 'updatedAt',
            width: 20,
            render: (value) => dayjs(value as string).format('YYYY-MM-DD HH:mm:ss'),
          },
        ],
      });
    } finally {
      setExporting(false);
    }
  };
  return (
    <BaseIndex title="Order transaction page">
      <BaseSearch
        title="Search bar"
        submitFun={transitionTableRef.current?.reload}
        inputProps={{
          value: transitionSearchKey,
          onChange: (e) => {
            setTransitionSearchKey(e.target.value);
            // 可选：自动触发搜索
            transitionTableRef.current?.reload();
          },
        }}
      />
      <BaseTable
        searchKey={transitionSearchKey}
        props={{
          headerTitle: 'Order transaction page',
          actionRef: transitionTableRef,
          pagination: {
            pageSize: 16,
          },
          toolBarRender() {
            const domList: React.ReactNode[] = [
              <Button
                key="export"
                type="primary"
                onClick={handleExport}
                loading={exporting}
                icon={<DownloadOutlined />}
              >
                {exporting ? '導出中...' : '匯出表格'}
              </Button>,
            ];
            if (transitionSearchKey) {
              domList.push(
                <Button
                  key="back"
                  type="primary"
                  onClick={() => {
                    setTransitionSearchKey('');
                    history.push('/customer');
                  }}
                >
                  返回用户列表
                </Button>,
              );
            }
            return domList;
          },
          columns: OrderTransactionColumns({
            mainTableReload: () => {
              return transitionTableRef.current?.reload();
            },
          }),
          request: async () => {
            const dataSource = await _getOrderTransactionList();
            console.log('order transaction dataSource==>', dataSource);
            if (transitionSearchKey) {
              return {
                ...dataSource,
                data: Helper<Page_Customer.CustomerTable>({
                  dataSource: dataSource.data,
                  keyWord: transitionSearchKey,
                }) as Page_Customer.CustomerTable[],
              };
            }
            return dataSource;
          },
        }}
      />
    </BaseIndex>
  );
}
