import BaseModel from '@/components/Base/BaseModel';
import { _sendPushNotification } from '@/services/customer';
import { _getLeaveTime, _unlock, _updateRemark } from '@/services/transition';
import { ProColumns, ProFormTextArea } from '@ant-design/pro-components';
import { Button, message, Modal, ModalFuncProps, Select, Tag } from 'antd';
import { SelectProps } from 'antd/lib';
import dayjs from 'dayjs';

enum OrderStatus {
  notleaving = '13',
  started = '7',
  done = '8',
  cancelled = '9',
}
const modalFormProps: ModalFuncProps = {
  centered: true,
  maskClosable: true,
  keyboard: true,
};
export function OrderTransactionColumns({
  mainTableReload,
}: {
  mainTableReload: () => Promise<void> | undefined;
}): ProColumns<OrderTransaction>[] {
  return [
    {
      title: '訂單編號',
      dataIndex: 'format_order_id',
      width: 200,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '用戶信息',
      dataIndex: ['user', 'nickname'],
      width: 120,
      render: (_, record) => {
        return (
          <div>
            <div>{record.user?.nickname || '-'}</div>
            <div>{record.user?.phone || '-'}</div>
          </div>
        );
      },
    },
    {
      title: '充電槍',
      dataIndex: ['connector', 'ConnectorName'],
      width: 120,
      render: (_, record) => (
        <div>
          <div>{record.connector?.ConnectorName || '-'}</div>
          <div>車位: {record.connector?.park || '-'}</div>
        </div>
      ),
    },
    {
      title: '訂單狀態',
      dataIndex: ['status', 'description'],
      width: 100,
      valueEnum: {
        [OrderStatus.started]: '開始',
        [OrderStatus.done]: '完成',
        [OrderStatus.cancelled]: '取消',
        [OrderStatus.notleaving]: '未離場',
      },
      filters: [
        { text: '開始', value: OrderStatus.started },
        { text: '完成', value: OrderStatus.done },
        { text: '取消', value: OrderStatus.cancelled },
        { text: '未離場', value: OrderStatus.notleaving },
      ],
      filtered: true,
      filterMultiple: true,

      onFilter: (value, record) => {
        console.log(record.status?.id === value);
        return record.status?.id === value;
      },
      render: (_, record) => {
        const status = record.status?.description;
        const colorMap: Record<string, string> = {
          [OrderStatus.started]: 'processing',
          [OrderStatus.done]: 'success',
          [OrderStatus.cancelled]: 'default',
          [OrderStatus.notleaving]: 'error',
          // 添加其他状态
        };
        return <Tag color={colorMap[status] || 'default'}>{status}</Tag>;
      },
    },
    {
      title: '充電量',
      width: 120,
      render: (_, record) => (
        <div className="flex flex-col">
          <div>{record.actual_total_power ? `${record.actual_total_power}kWh` : '-'}</div>
        </div>
      ),
    },
    {
      title: '費用',
      dataIndex: 'total_fee',
      width: 100,
      render: (fee) => (fee ? `HKD$${fee}` : '-'),
    },
    {
      title: '罰金',
      dataIndex: 'penalty_fee',
      width: 100,
      render: (fee) => (fee ? `HKD$${fee}` : '-'),
    },
    {
      title: '退款',
      dataIndex: 'refund_fee',
      width: 100,
      render: (_, record) => (record.withdraw_fee ? `HKD$${record.withdraw_fee}` : '-'),
    },
    {
      title: '實際費用',
      dataIndex: 'actual_fee',
      width: 100,
      sorter: (a, b) => a.total_fee - a.withdraw_fee - (b.total_fee - b.withdraw_fee),
      render: (_, record) =>
        record.total_fee - record.withdraw_fee
          ? `HKD$${record.total_fee - record.withdraw_fee}`
          : '-',
    },
    {
      title: '罰金',
      dataIndex: 'penalty_fee',
      width: 100,
      sorter: (a, b) => a.penalty_fee - b.penalty_fee,
      render: (fee) => (fee ? `HKD$${fee}` : '-'),
    },

    {
      title: '實際開始時間',
      dataIndex: 'actual_start_time',
      width: 160,
      sorter: (a, b) => {
        // 处理空值情况
        if (!a.actual_start_time) return -1;
        if (!b.actual_start_time) return 1;

        // 转换为时间戳进行比较
        return dayjs(a.actual_start_time).valueOf() - dayjs(b.actual_start_time).valueOf();
      },
      render: (time) => (time ? dayjs(time as string).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },

    {
      title: '實際結束時間',
      dataIndex: 'actual_end_time',
      width: 160,
      sorter: (a, b) => {
        // 处理空值情况
        if (!a.actual_end_time) return -1;
        if (!b.actual_end_time) return 1;

        // 转换为时间戳进行比较
        return dayjs(a.actual_end_time).valueOf() - dayjs(b.actual_end_time).valueOf();
      },
      render: (time) => (time ? dayjs(time as string).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },
    {
      title: '支付狀態',
      width: 120,
      render: (_, record) => (
        <div>
          <div>
            <Tag color={record.paid_status ? 'success' : 'warning'}>
              {record.paid_status ? '已支付' : '未支付'}
            </Tag>
          </div>
          {record.penalty_fee > 0 && (
            <div>
              <Tag color={record.penalty_paid_status ? 'success' : 'error'}>
                {record.penalty_paid_status ? '罰金已付' : '罰金未付'}
              </Tag>
            </div>
          )}
        </div>
      ),
    },
    {
      title: '備註',
      dataIndex: 'remark',
      width: 180,
      align: 'center',
      ellipsis: {
        showTitle: true,
      },
      onCell: () => ({
        style: {
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          maxWidth: 100,
        },
      }),

      copyable: true,

      render: (_, record) => {
        return (
          <BaseModel
            title={'修改備註'}
            modalProps={{
              destroyOnClose: true,
              centered: true,
              width: 400,
            }}
            allowUpdate={false}
            readOnly={false}
            submit={() => {
              console.log('submit');
            }}
            modalFormProps={{
              trigger: (
                <Button type={record.remark ? 'text' : 'primary'}>
                  {record.remark ? record.remark : '添加備註'}
                </Button>
              ),
              // onInit: (values) => {
              //   setCurrentCustomer(customerId.customerId);
              // },
              onFinish: async (values: { remark: string }) => {
                console.log('values', values);
                try {
                  await _updateRemark({
                    orderId: record.id,
                    remark: values.remark,
                  });
                  message.success('修改備註成功');
                  mainTableReload?.();
                  return true;
                } catch (error) {
                  console.log('error', error);
                  message.error('修改備註失敗');
                  return true;
                }
              },
              submitter: {
                submitButtonProps: {
                  children: '修改備註',
                },
              },
            }}
          >
            <ProFormTextArea label="備註" name="remark" initialValue={record.remark} />
          </BaseModel>
        );
      },
    },
    {
      title: '創建時間',
      dataIndex: 'createdAt',
      width: 160,
      sorter: (a, b) => {
        // 处理空值情况
        if (!a.createdAt) return -1;
        if (!b.createdAt) return 1;

        // 转换为时间戳进行比较
        return dayjs(a.createdAt).valueOf() - dayjs(b.createdAt).valueOf();
      },
      render: (time) => dayjs(time as string).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '更新時間',
      dataIndex: 'updatedAt',
      width: 160,
      sorter: (a, b) => {
        // 处理空值情况
        if (!a.updatedAt) return -1;
        if (!b.updatedAt) return 1;

        // 转换为时间戳进行比较
        return dayjs(a.updatedAt).valueOf() - dayjs(b.updatedAt).valueOf();
      },
      render: (time) => dayjs(time as string).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 100,
      valueType: 'select',
      render: (_, record) => {
        const getLeaveTime = async () => {
          const res = await _getLeaveTime(record.id);
          console.log(res);
          return res?.data?.leaving_time
            ? dayjs(res.data.leaving_time as string).format('YYYY-MM-DD HH:mm:ss')
            : '-';
        };

        const handleActionChange = async (value: string) => {
          switch (value) {
            case 'viewLeaveTime':
              Modal.info({
                ...modalFormProps,
                title: '離場時間',
                content: `離場時間：${await getLeaveTime()}`,
                okText: '確認',
                cancelText: '取消',
              });

              break;
            case 'unlock':
              Modal.confirm({
                ...modalFormProps,
                title: '清除罚款状态',
                content: (
                  <>
                    <div>是否确认清除该订单的罚款状态？</div>
                    <div>清除罚款状态后，订单将不再为罚款状态，请确认是否继续。</div>
                  </>
                ),
                okText: '確認',
                cancelText: '取消',

                onOk: async () => {
                  const res = await _unlock(record.id);
                  console.log(res);
                  if (res.status === 200) {
                    await _sendPushNotification(record.user?.id, '罰金清除', '已为您清除罰金');
                    message.success('清除罚款状态成功');
                  } else {
                    message.error('清除罚款状态失败');
                  }
                  return true;
                },
              });
              break;
          }
        };

        // 根据订单状态动态生成可用操作
        const getOptions = (record: OrderTransaction): SelectProps['options'] => {
          const options = [
            { label: '查看离场时间', value: 'viewLeaveTime' },
            { label: '清除罚款状态', value: 'unlock' },
          ];

          // 只有未开始的订单可以取消
          if (record.status?.description === 'pending') {
            options.push({ label: '取消訂單', value: 'cancel' });
          }

          // 已支付的订单可以退款
          if (record.paid_status && record.status?.description === 'completed') {
            options.push({ label: '申請退款', value: 'refund' });
          }

          // 有未支付罚金的订单
          if (record.penalty_fee && !record.penalty_paid_status) {
            options.push({ label: '處理罰金', value: 'penalty' });
          }

          return options;
        };

        return (
          <Select
            defaultValue="viewLeaveTime"
            style={{ width: '100%' }}
            options={getOptions(record)}
            // onChange={handleActionChange}
            onSelect={(value) => {
              handleActionChange(value);
              // 重置选择
              setTimeout(() => {
                const select = document.querySelector('.ant-select') as HTMLElement;
                if (select) {
                  select.click();
                }
              }, 100);
            }}
          />
        );
      },
    },
  ];
}
