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

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

      await exportToExcel({
        filename: `錢包交易記錄`,
        data,
        columns: [
          {
            title: '訂單編號',
            dataIndex: ['reservation', 'format_order_id'],
            width: 30,
          },
          {
            title: '用戶暱稱',
            dataIndex: ['user', 'nickname'],
            width: 15,
          },
          {
            title: '用戶電話',
            dataIndex: ['user', 'phone'],
            width: 15,
          },
          {
            title: '交易類型',
            dataIndex: 'goods_name',
            width: 15,
          },
          {
            title: '金額(HKD$)',
            dataIndex: 'amount',
            width: 15,
          },
          {
            title: '交易狀態',
            dataIndex: 'status_fk',
            width: 15,
            render: (status) => (status === 1 ? '成功' : '失敗'),
          },
          {
            title: '錢包餘額(HKD$)',
            dataIndex: ['user', 'wallet'],
            width: 15,
            render: (wallet) => wallet?.toFixed(2),
          },
          {
            title: '充電開始時間',
            dataIndex: ['reservation', 'actual_start_time'],
            width: 20,
            render: (time) => (time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'),
          },
          {
            title: '充電結束時間',
            dataIndex: ['reservation', 'actual_end_time'],
            width: 20,
            render: (time) => (time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'),
          },
          {
            title: '充電量(kWh)',
            dataIndex: ['reservation', 'actual_total_power'],
            width: 15,
          },
          {
            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="錢包交易記錄">
      <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: '錢包交易記錄',
          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: WalletTransactionColumns({
            mainTableReload: () => {
              return transitionTableRef.current?.reload();
            },
          }),
          request: async () => {
            const dataSource = await _getWalletTransactionList();
            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>
  );
}
