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 { _getTopUpTransactionList } 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 { TopUpTransactionColumns } from './TopUpTransactionColumns';
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 _getTopUpTransactionList();
      let data = response.data;

      if (transitionSearchKey) {
        data = Helper<API.TopUpTransaction>({
          dataSource: data,
          keyWord: transitionSearchKey,
        });
      }

      await exportToExcel({
        filename: `充值記錄`,
        data,
        columns: [
          {
            title: '訂單編號',
            dataIndex: 'out_trade_no',
            width: 30,
          },
          {
            title: '用戶暱稱',
            dataIndex: ['user', 'nickname'],
            width: 15,
          },
          {
            title: '用戶電話',
            dataIndex: ['user', 'phone'],
            width: 15,
          },
          {
            title: '用戶郵箱',
            dataIndex: ['user', 'email'],
            width: 20,
          },
          {
            title: '充值金額(HKD$)',
            dataIndex: 'amount',
            width: 15,
          },
          {
            title: '支付方式',
            dataIndex: ['snapshot', 'pay_type'],
            width: 15,
            render: (payType) => {
              const payTypeMap: Record<string, string> = {
                '801512': 'AlipayHK',
              };
              return payTypeMap[payType] || payType;
            },
          },
          {
            title: '支付狀態',
            dataIndex: ['snapshot', 'status'],
            width: 15,
            render: (status) => (status === '1' ? '支付成功' : '支付失敗'),
          },
          {
            title: '支付時間',
            dataIndex: ['snapshot', 'paydtm'],
            width: 20,
            render: (time) => (time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'),
          },
          {
            title: '錢包餘額(HKD$)',
            dataIndex: ['user', 'wallet'],
            width: 15,
            render: (wallet) => wallet?.toFixed(2),
          },
          {
            title: '交易流水號',
            dataIndex: ['snapshot', 'syssn'],
            width: 30,
          },
          {
            title: '支付卡號',
            dataIndex: ['snapshot', 'outcardnm'],
            width: 20,
          },
          {
            title: '創建時間',
            dataIndex: 'createdAt',
            width: 20,
            render: (time) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
          },
          {
            title: '更新時間',
            dataIndex: 'updatedAt',
            width: 20,
            render: (time) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
          },
        ],
      });
    } finally {
      setExporting(false);
    }
  };
  return (
    <BaseIndex title="Top up 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: TopUpTransactionColumns({
            mainTableReload: () => {
              return transitionTableRef.current?.reload();
            },
          }),
          request: async () => {
            const dataSource = await _getTopUpTransactionList();
            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>
  );
}
