import BaseIndex from '@/components/Base/BaseIndex';
import BaseModel from '@/components/Base/BaseModel';
import BaseSearch from '@/components/Base/BaseSearch';
import BaseTable from '@/components/Base/BaseTable';
import {
  _bindingIc,
  _deduct,
  _getCouponList,
  _getCouponListByCustomerId,
  _getCustomerTopUp,
  _getCustomerTransactionList,
  _refund,
  _sendCoupon,
  _sendPushNotification,
  _updateCouponPermission,
} from '@/services/customer';
import Helper from '@/util/searchHelper';
import {
  ActionType,
  DrawerForm,
  ProColumns,
  ProFormDigit,
  ProFormMoney,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, message, Switch, Tag, Typography } from 'antd';
import { useEffect, useRef, useState } from 'react';
// import DetailModal from "./detailModal";
import { exportToExcel } from '@/util/exportToExcel';
import { DownloadOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import dayjs from 'dayjs';
import TransactionDetail from './transactionDetail';

export function CustomerTransactionColumns(): ProColumns<API.CustomerTransaction>[] {
  return [
    {
      title: '訂單ID',
      dataIndex: 'id',
      key: 'id',
      width: 300,
      align: 'center',
      render: (text) => (
        <Typography.Text ellipsis={{ tooltip: text }} copyable>
          {text}
        </Typography.Text>
      ),
    },
    {
      title: '交易時間',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      align: 'center',
      sorter: (a, b) => dayjs(a.createdAt).unix() - dayjs(b.createdAt).unix(),
      render: (text) => dayjs(text as any).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '交易類型',
      dataIndex: 'goods_name',
      key: 'goods_name',
      width: 120,
      align: 'center',
      ellipsis: true,
      render: (text) => <Typography.Text ellipsis={{ tooltip: text }}>{text}</Typography.Text>,
    },
    {
      title: '金額',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      align: 'center',
      sorter: (a, b) => a.amount - b.amount,
      render: (text) => `HK$${Number(text)?.toFixed(2)}`,
    },
    {
      title: '狀態',
      dataIndex: 'status_fk',
      key: 'status_fk',
      width: 100,
      align: 'center',
      valueEnum: {
        1: { text: '成功', status: 'Success' },
        2: { text: '失敗', status: 'Error' },
        3: { text: '處理中', status: 'Processing' },
      },
    },
    {
      title: '詳情',
      dataIndex: 'snapshot',
      key: 'snapshot',
      width: 300,
      align: 'center',
      ellipsis: true,
      render: (_, record) => {
        // ... 原有的格式化代码 ...

        return (
          <>
            <TransactionDetail snapshot={record.snapshot} />
          </>
        );
      },
    },
  ];
}

export function CustomerTransactionTable({ customerId }: { customerId: string }) {
  const [transitionSearchKey, setTransitionSearchKey] = useState('');
  const transitionTableRef = useRef<ActionType>();
  const [exporting, setExporting] = useState(false);

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

      if (transitionSearchKey) {
        data = Helper<Page_Customer.CustomerTable>({
          dataSource: data,
          keyWord: transitionSearchKey,
        });
      }
      await exportToExcel({
        filename: `交易記錄_${customerId}`,
        data,
        columns: [
          {
            title: '交易時間',
            dataIndex: 'createdAt',
            width: 20,
            render: (value) => dayjs(value).format('YYYY-MM-DD HH:mm:ss'),
          },
          {
            title: '交易類型',
            dataIndex: ['snapshot', 'type'],
            width: 15,
          },
          {
            title: '充電站ID',
            dataIndex: ['snapshot', 'stationID'],
            width: 25,
          },
          {
            title: '充電槍ID',
            dataIndex: ['snapshot', 'connector'],
            width: 25,
          },
          {
            title: '預約時間',
            dataIndex: ['snapshot', 'book_time'],
            width: 20,
            render: (value) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
          },
          {
            title: '結束時間',
            dataIndex: ['snapshot', 'end_time'],
            width: 20,
            render: (value) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
          },
          {
            title: '充電量',
            dataIndex: ['snapshot', 'total_power'],
            width: 15,
            render: (value) => (value ? `${value}kWh` : '-'),
          },
          {
            title: '金額',
            dataIndex: 'amount',
            width: 15,
            render: (value) => `HK$${value}`,
          },
          {
            title: '訂單編號',
            dataIndex: 'id',
            width: 40,
          },
          {
            title: '使用優惠券',
            dataIndex: ['snapshot', 'with_coupon'],
            width: 15,
            render: (value) => (value ? '是' : '否'),
          },

          {
            title: '備註',
            dataIndex: 'goods_name',
            width: 15,
          },
          {
            title: '車輛ID',
            dataIndex: ['snapshot', 'car'],
            width: 40,
          },
          {
            title: 'IC卡充電',
            dataIndex: ['snapshot', 'is_ic_call'],
            width: 15,
            render: (value) => (value ? '是' : '否'),
          },
        ],
      });
    } finally {
      setExporting(false);
    }
  };
  return (
    <BaseIndex title="Customer 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: 'Transaction List',
          actionRef: transitionTableRef,
          pagination: {
            pageSize: 16,
          },
          toolBarRender() {
            return [
              <Button
                key="export"
                type="primary"
                onClick={handleExport}
                loading={exporting}
                icon={<DownloadOutlined />}
              >
                {exporting ? '導出中...' : '匯出表格'}
              </Button>,
            ];
          },
          columns: CustomerTransactionColumns(),
          request: async () => {
            const dataSource = await _getCustomerTransactionList(customerId);
            if (transitionSearchKey) {
              return {
                ...dataSource,
                data: Helper<Page_Customer.CustomerTable>({
                  dataSource: dataSource.data,
                  keyWord: transitionSearchKey,
                }) as Page_Customer.CustomerTable[],
              };
            }
            return dataSource;
          },
        }}
      />
    </BaseIndex>
  );
}
function CustomerTopUpColumns(): ProColumns<API.TopUpTransaction>[] {
  return [
    {
      title: '交易時間',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '金額',
      dataIndex: 'amount',
      key: 'amount',
    },
    {
      title: '交易單號',
      dataIndex: 'out_trade_no',
      key: 'out_trade_no',
    },
    {
      title: '用戶ID',
      dataIndex: 'user_id',
      key: 'user_id',
    },
  ];
}
function CustomerCouponTableColumns({
  mainTableReload,
}: {
  mainTableReload: (() => Promise<void>) | undefined;
}): ProColumns<any>[] {
  return [
    {
      title: '發放時間',
      dataIndex: 'issue_date',
      key: 'issue_date',
      valueType: 'dateTime',
    },
    {
      title: '過期時間',
      dataIndex: 'expire_date',
      key: 'expire_date',
      valueType: 'dateTime',
    },
    {
      title: '優惠券名稱',
      dataIndex: ['coupon', 'name'],
      key: 'coupon_name',
    },
    {
      title: '金額',
      dataIndex: ['coupon', 'amount'],
      key: 'amount',
      render: (_, record) => `${record.coupon.unit}${record.coupon.amount}`,
    },
    {
      title: '使用狀態',
      dataIndex: 'is_consumed',
      key: 'is_consumed',
      valueEnum: {
        true: { text: '已使用', status: 'Default' },
        false: { text: '未使用', status: 'Processing' },
      },
    },
    {
      title: '使用時間',
      dataIndex: 'used_at',
      key: 'used_at',
      valueType: 'dateTime',
    },
    {
      title: '持有人',
      dataIndex: ['receiver', 'nickname'],
      key: 'receiver',
      width: '10%',
    },
    {
      title: '發放方式',
      dataIndex: 'distributor_type',
      key: 'distributor_type',
      valueEnum: {
        admin: { text: '管理員發放', status: 'Success' },
        system: { text: '系統發放', status: 'Processing' },
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (_, record) => (
        <Switch
          checked={record.permission}
          onChange={async (value) => {
            await _updateCouponPermission({ id: record.id, permission: value });
            console.log('record', mainTableReload);
            mainTableReload?.();
            message.success('更新成功');
          }}
        />
      ),
    },
  ];
}

export function CustomerTableColumns({
  mainTableReload,
}: {
  mainTableReload: (() => Promise<void>) | undefined;
}): ProColumns<Page_Customer.CustomerTable>[] {
  const BindIcCardModalForm = ({ customerId }: { customerId: string }) => {
    return (
      <BaseModel
        title="綁定ic卡"
        modalProps={{
          destroyOnClose: true,
          centered: true,
          width: 400,
        }}
        allowUpdate={false}
        readOnly={false}
        submit={() => {
          console.log('submit');
        }}
        modalFormProps={{
          trigger: <Button type="default">綁定ic卡</Button>,
          // onInit: (values) => {
          //   setCurrentCustomer(customerId.customerId);
          // },
          onFinish: async (values) => {
            console.log('values', values);
            console.log('currentCustomer', customerId);
            try {
              await _bindingIc({
                id: customerId,
                icCardId: values.icCardId,
              });
              await _sendPushNotification(customerId, '優惠券通知', '您有新的優惠券，請查收');

              mainTableReload?.();
              message.success('綁定成功');
              return true;
            } catch (error) {
              console.log('error', error);
              message.error('綁定失敗');
              return true;
            }
          },
          submitter: {
            submitButtonProps: {
              children: '綁定',
            },
          },
        }}
      >
        <ProFormText
          label="ic卡號碼"
          name="icCardId"
          width="md"
          rules={[{ required: true }, { max: 16, message: 'ic卡號碼最多10位' }]}
        />
      </BaseModel>
    );
  };
  const UpdateIcCardModalForm = ({
    customerId,
    icCardId,
  }: {
    customerId: string;
    icCardId: string | null;
  }) => {
    return (
      <BaseModel
        title="ic卡更新"
        modalProps={{
          destroyOnClose: true,
          centered: true,
          width: 400,
        }}
        allowUpdate={false}
        readOnly={false}
        submit={() => {
          console.log('submit');
        }}
        modalFormProps={{
          trigger: <Button type="text">{icCardId || '無'}</Button>,
          // onInit: (values) => {
          //   setCurrentCustomer(customerId.customerId);
          // },
          onFinish: async (values) => {
            console.log('values', values);
            console.log('currentCustomer', customerId);
            try {
              await _bindingIc({
                id: customerId,
                icCardId: values.icCardId,
              });
              await _sendPushNotification(customerId, 'ic卡更新', '已更新您的ic卡号');

              mainTableReload?.();
              message.success('ic卡更新成功');
              return true;
            } catch (error) {
              console.log('error', error);
              message.error('ic卡更新失敗');
              return true;
            }
          },
          submitter: {
            submitButtonProps: {
              children: '更新',
            },
          },
        }}
      >
        <ProFormText
          label="新ic卡號碼"
          name="icCardId"
          width="md"
          initialValue={icCardId}
          rules={[{ required: true }, { max: 16, message: 'ic卡號碼最多10位' }]}
        />
      </BaseModel>
    );
  };
  const WalletAction = ({ customerId, isRefund }: { customerId: string; isRefund: boolean }) => {
    return (
      <BaseModel
        title={isRefund ? '退款' : '扣款'}
        modalProps={{
          destroyOnClose: true,
          centered: true,
          width: 400,
        }}
        allowUpdate={false}
        readOnly={false}
        submit={() => {
          console.log('submit');
        }}
        modalFormProps={{
          trigger: <Button type="default">{isRefund ? '退款' : '扣款'}</Button>,
          // onInit: (values) => {
          //   setCurrentCustomer(customerId.customerId);
          // },
          onFinish: async (values: API.RefundData) => {
            console.log('values', values);
            console.log('currentCustomer', customerId);
            try {
              if (isRefund) {
                await _refund({
                  ...values,
                  reserverId: customerId,
                });
              } else {
                await _deduct({
                  ...values,
                  reserverId: customerId,
                });
              }
              await _sendPushNotification(
                customerId,
                isRefund ? '退款通知' : '扣款通知',
                isRefund
                  ? `已退還$${values.amount}到您的錢包`
                  : `已從您的錢包餘額扣款 $${values.amount}`,
              );
              mainTableReload?.();
              message.success(isRefund ? '退款成功' : '扣款成功');
              return true;
            } catch (error) {
              console.log('error', error);
              message.error(isRefund ? '退款失敗' : '扣款失敗');
              return true;
            }
          },
          submitter: {
            submitButtonProps: {
              children: isRefund ? '退款' : '扣款',
            },
          },
        }}
      >
        <ProFormMoney
          locale="en-US"
          label="金額"
          name="amount"
          width="md"
          rules={[{ required: true }]}
        />
        <ProFormText label="執行者" name="executor" width="md" required />
        <ProFormText label="參考訂單" name="referenceReservationId" width="md" />

        <ProFormTextArea label="原因" name="reason" />
      </BaseModel>
    );
  };
  // const CustomerTransactionModal = ({ customerId }: { customerId: string }) => {
  //   return (
  //     <DrawerForm
  //       title="交易紀錄"
  //       submitter={false}
  //       key="transaction"
  //       drawerProps={{
  //         placement: 'top',
  //         destroyOnClose: true,
  //         height: '70vh',
  //       }}
  //       open={transactionOpen}
  //       onOpenChange={setTransactionOpen}
  //       trigger={<Button>交易紀錄</Button>}
  //     >
  //       <BaseIndex title="Customer transaction page">
  //         <BaseSearch
  //           title="Search bar"
  //           submitFun={transitionTableRef.current?.reload}
  //           inputProps={{
  //             value: transitionSearchKey,
  //             onChange: ({ currentTarget: { value } }) => setTransitionSearchKey(value),
  //           }}
  //         />
  //         <BaseTable<Page_Customer.CustomerTable>
  //           searchKey={transitionSearchKey}
  //           props={{
  //             headerTitle: 'Transaction List',
  //             actionRef: transitionTableRef,
  //             pagination: {
  //               pageSize: 16,
  //             },
  //             columns: CustomerTransactionColumns({
  //               mainTableReload: transitionTableRef.current?.reload,
  //             }),
  //             request: async () => {
  //               const dataSource = await _getCustomerTransactionList(customerId);
  //               console.log('dataSource', dataSource);
  //               if (transitionSearchKey) {
  //                 dataSource.data = Helper<Page_Customer.CustomerTable>({
  //                   dataSource: dataSource.data,
  //                   keyWord: transitionSearchKey,
  //                 }) as Page_Customer.CustomerTable[];

  //                 return dataSource;
  //               } else {
  //                 return dataSource;
  //               }
  //             },
  //           }}
  //         />
  //       </BaseIndex>
  //     </DrawerForm>
  //   );
  // };
  const CustomerTransactionModal: React.FC<{
    customerId: string;
  }> = ({ customerId }) => {
    // 将状态移动到组件内部
    const [open, setOpen] = useState(false);

    return (
      <>
        <Button onClick={() => setOpen(true)}>交易紀錄</Button>
        {/* 使用 open 状态控制抽屉显示 */}
        {open && (
          <DrawerForm
            title="交易紀錄"
            submitter={false}
            open={open}
            onOpenChange={setOpen}
            drawerProps={{
              placement: 'top',
              destroyOnClose: true,
              height: 'auto',

              style: {
                maxHeight: '80vh', // 最大高度为视窗高度的80%
                overflow: 'auto', // 启用滚动
              },
              bodyStyle: {
                padding: '24px',
                minHeight: '200px', // 最小高度
                height: 'fit-content', // 高度自适应内容
              },
              contentWrapperStyle: {
                height: 'auto', // 包装器高度自适应
                maxHeight: '80vh', // 与drawer一致的最大高度
              },
              // height: 'auto',
              onClose: () => setOpen(false),
            }}
          >
            <CustomerTransactionTable customerId={customerId} />
          </DrawerForm>
        )}
      </>
    );
  };
  const CustomerTopUpModal: React.FC<{
    customerId: string;
  }> = ({ customerId }) => {
    // 将状态移动到组件内部
    const [open, setOpen] = useState(false);
    const [transitionSearchKey, setTransitionSearchKey] = useState('');
    const transitionTableRef = useRef<ActionType>();

    return (
      <>
        <Button onClick={() => setOpen(true)}>充值紀錄</Button>
        {/* 使用 open 状态控制抽屉显示 */}
        {open && (
          <DrawerForm
            title="充值紀錄"
            submitter={false}
            open={open}
            onOpenChange={setOpen}
            drawerProps={{
              placement: 'top',
              destroyOnClose: true,
              height: 'auto',
              style: {
                maxHeight: '80vh', // 最大高度为视窗高度的80%
                overflow: 'auto', // 启用滚动
              },
              bodyStyle: {
                padding: '24px',
                minHeight: '200px', // 最小高度
                height: 'fit-content', // 高度自适应内容
              },
              contentWrapperStyle: {
                height: 'auto', // 包装器高度自适应
                maxHeight: '80vh', // 与drawer一致的最大高度
              },
              // height: 'auto',
              onClose: () => setOpen(false),
            }}
          >
            <BaseIndex title="Customer top up 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: 'Top up List',
                  actionRef: transitionTableRef,
                  pagination: {
                    pageSize: 16,
                  },
                  columns: CustomerTopUpColumns(),
                  request: async () => {
                    const dataSource = await _getCustomerTopUp(customerId);
                    if (transitionSearchKey) {
                      return {
                        ...dataSource,
                        data: Helper<Page_Customer.CustomerTable>({
                          dataSource: dataSource.data,
                          keyWord: transitionSearchKey,
                        }) as Page_Customer.CustomerTable[],
                      };
                    }
                    return dataSource;
                  },
                }}
              />
            </BaseIndex>
          </DrawerForm>
        )}
      </>
    );
  };

  const SendCouponModal: React.FC<{
    customerId: string;
  }> = ({ customerId }) => {
    return (
      <BaseModel
        title={'發送優惠券'}
        modalProps={{
          destroyOnClose: true,
          centered: true,
          width: 400,
        }}
        allowUpdate={false}
        readOnly={false}
        submit={() => {
          console.log('submit');
        }}
        modalFormProps={{
          trigger: <Button type="default">{'發送優惠券'}</Button>,
          // onInit: (values) => {
          //   setCurrentCustomer(customerId.customerId);
          // },
          onFinish: async (values: API.SendCouponData) => {
            console.log('values', values);
            console.log('currentCustomer', customerId);
            try {
              await _sendCoupon({
                ...values,
                receiver_id: customerId,
              });

              await _sendPushNotification(
                customerId,
                '優惠券通知',
                '您有新的優惠劵，打開App立即使用！',
              );
              mainTableReload?.();
              message.success('發送優惠券成功');
              return true;
            } catch (error) {
              console.log('error', error);
              message.error('發送優惠券失敗');
              return true;
            }
          },
          submitter: {
            submitButtonProps: {
              children: '确认发送',
            },
          },
        }}
      >
        <ProFormSelect
          label="優惠券名稱"
          name="coupon_id"
          width="md"
          // options={couponList.data}
          request={async () => {
            const couponList = await _getCouponList();
            console.log('couponList', couponList);
            return couponList.data.map((item: any) => ({
              label: item.name,
              value: item.id,
            }));
          }}
        />
        <ProFormDigit label="優惠券數量" name="quantity" width="md" />
      </BaseModel>
    );
  };

  const CustomerCouponTable: React.FC<{
    customerId: string;
  }> = ({ customerId }) => {
    // 将状态移动到组件内部
    const [open, setOpen] = useState(false);
    const [couponSearchKey, setCouponSearchKey] = useState('');
    const couponTableRef = useRef<ActionType>();
    const [reload, setReload] = useState(() => couponTableRef.current?.reload);
    useEffect(() => {
      setReload(() => couponTableRef.current?.reload);
    }, []);
    return (
      <>
        <Button onClick={() => setOpen(true)}>優惠券紀錄</Button>
        {/* 使用 open 状态控制抽屉显示 */}
        {open && (
          <DrawerForm
            title="優惠券紀錄"
            submitter={false}
            open={open}
            onOpenChange={setOpen}
            drawerProps={{
              placement: 'top',
              destroyOnClose: true,
              height: 'auto',
              style: {
                maxHeight: '80vh', // 最大高度为视窗高度的80%
                overflow: 'auto', // 启用滚动
              },
              bodyStyle: {
                padding: '24px',
                minHeight: '200px', // 最小高度
                height: 'fit-content', // 高度自适应内容
              },
              contentWrapperStyle: {
                height: 'auto', // 包装器高度自适应
                maxHeight: '80vh', // 与drawer一致的最大高度
              },
              // height: 'auto',
              onClose: () => setOpen(false),
            }}
          >
            <BaseIndex title="Customer coupon page">
              <BaseSearch
                title="Search bar"
                submitFun={couponTableRef.current?.reload}
                inputProps={{
                  value: couponSearchKey,
                  onChange: (e) => {
                    setCouponSearchKey(e.target.value);
                    // 可选：自动触发搜索
                    reload?.();
                  },
                }}
              />
              <BaseTable
                searchKey={couponSearchKey}
                props={{
                  headerTitle: 'Coupon List',
                  actionRef: couponTableRef,
                  pagination: {
                    pageSize: 16,
                  },
                  columns: CustomerCouponTableColumns({
                    mainTableReload: reload,
                  }),
                  request: async () => {
                    const dataSource = await _getCouponListByCustomerId(customerId);
                    console.log('dataSource', dataSource);
                    setReload(() => couponTableRef.current?.reload);
                    if (couponSearchKey) {
                      return {
                        ...dataSource,
                        data: Helper<Page_Customer.CustomerTable>({
                          dataSource: dataSource.data,
                          keyWord: couponSearchKey,
                        }) as Page_Customer.CustomerTable[],
                      };
                    }
                    return dataSource;
                  },
                }}
              />
            </BaseIndex>
          </DrawerForm>
        )}
      </>
    );
  };
  return [
    {
      title: '用戶名稱',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      fixed: 'left', // 固定第一列
      width: 120,
      copyable: true,
    },
    {
      title: '用戶ID',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      copyable: true,
      ellipsis: {
        showTitle: true, // 懸停時顯示完整內容
      },
      width: 150,
    },
    {
      title: '註冊時間',
      dataIndex: 'createdAt',
      key: 'createdAt',
      align: 'center',
      width: 150,
      render: (text) =>
        dayjs(text as any)
          .local()
          .format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
      align: 'center',
      width: 200,
      copyable: true,
    },
    {
      title: '手機號碼',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
      width: 120,
      copyable: true,
    },
    {
      title: '錢包',
      dataIndex: 'wallet',
      key: 'wallet',
      sorter: (a, b) => a.wallet - b.wallet,
      render: (text) => `HK$${Number(text)?.toFixed(2)}`,
      align: 'center',
      width: 120,
    },
    {
      title: 'IC卡',
      dataIndex: 'icCard',
      key: 'icCard',
      align: 'center',
      width: 150,
      sorter: (a, b) => {
        // 处理 null/undefined 值
        if (!a.icCard && !b.icCard) return 0;
        if (!a.icCard) return 1; // null 值排在后面
        if (!b.icCard) return -1; // null 值排在后面

        // 正常字符串比较
        return a.icCard.localeCompare(b.icCard);
      },
      render: (text, record) => {
        console.log('text', text);
        if (text === '-') {
          return <BindIcCardModalForm customerId={record.id} />;
        }
        return <UpdateIcCardModalForm customerId={record.id} icCardId={record.icCard} />;
      },
    },
    {
      title: '預設車牌',
      dataIndex: ['defaultCar', 'license_plate'],
      key: 'defaultCar',
      render: (text) => (text === '0000' ? '_' : text),
      align: 'center',
      width: 100,
    },
    {
      title: '狀態',
      dataIndex: ['group', 'is_active'],
      key: 'groupStatus',
      render: (active) => (
        <Tag color={active ? 'success' : 'error'}>{active ? 'Active' : 'Inactive'}</Tag>
      ),
      align: 'center',
      width: 100,
    },
    {
      title: '驗證狀態',
      dataIndex: ['phoneVerification', 'status'],
      key: 'phoneVerification',
      render: (text) => {
        if (text === 1) {
          return <Tag color="success">已驗證</Tag>;
        }
        if (text === 2) {
          return <Tag color="warning">忘记密码</Tag>;
        }
        return <Tag color="error">未驗證</Tag>;
      },
      align: 'center',
      width: 100,
    },
    {
      title: '当前验证码',
      dataIndex: ['phoneVerification', 'otp'],
      key: 'phoneVerification',
      render: (text) => text,
      align: 'center',
      width: 100,
    },
    {
      title: '发送时间',
      dataIndex: ['phoneVerification', 'updatedAt'],
      key: 'phoneVerification',
      render: (text) => dayjs(text as any).format('YYYY-MM-DD HH:mm:ss'),
      align: 'center',
      width: 100,
    },
    {
      title: '錢包操作',
      dataIndex: 'action',
      key: 'action',
      sorter: (a, b) => a.wallet - b.wallet,
      render: (_, record) => (
        <span className="flex justify-center items-center gap-2">
          <WalletAction customerId={record.id} isRefund={false} />
          <WalletAction customerId={record.id} isRefund={true} />
        </span>
      ),
      align: 'center',
    },
    {
      title: '帳戶操作',
      dataIndex: 'action',
      key: 'action',
      render: (_, record) => (
        <span className="flex justify-center items-center gap-2">
          <CustomerTransactionModal customerId={record.id} />
          <CustomerTopUpModal customerId={record.id} />
          <Button
            type="text"
            onClick={() => {
              console.log('record', record);
              history.push(`/transaction/order?customerId=${record.id}`);
            }}
          >
            查询该用户订单
          </Button>
        </span>
      ),
      align: 'center',
    },
    {
      title: '下發優惠券',
      dataIndex: 'action',
      key: 'action',
      width: 100,
      render: (_, record) => (
        <span className="flex justify-center items-center gap-2">
          <SendCouponModal customerId={record.id} />
          <CustomerCouponTable customerId={record.id} />
        </span>
      ),
      align: 'center',
    },
  ];
}
