import {
  MyBetaModalFormProps,
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import {
  HouseBillsBillStatusEnum,
  HouseOrdersPaymentMethodEnum,
} from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Form, message } from 'antd';
import { debounce } from 'lodash';
import * as React from 'react';

// 定义表单字段类型接口
interface BillItem {
  id: string | number;
  total_payable_amount: number;
  amount?: number;
  remark?: string;
}

interface FormValues {
  payment_method: string;
  total_paid_amount: number;
  paid_date: string | null;
  bill_ids: BillItem[];
}

export interface PayCreateProps extends MyBetaModalFormProps {
  selectedBillIds?: React.Key[];
  selectedRows?: Array<{
    id: string | number;
    total_payable_amount: number;
    [key: string]: any;
  }>;
}

export default function PayCreate(props: PayCreateProps): React.ReactElement {
  const [form] = Form.useForm<FormValues>();
  // 在组件外部定义防抖函数
  const debouncedUpdateTotal = debounce(() => {
    let total_paid_amount = 0;
    const newBillIds = form.getFieldValue('bill_ids');
    newBillIds?.forEach((res: { amount?: number }) => {
      total_paid_amount += Number(res?.amount) || 0;
    });
    form.setFieldValue('total_paid_amount', total_paid_amount);
    // form.setFieldValue('bill_ids', newBillIds);
  }, 500); // 500ms延迟

  const debouncedUpdateTotalList = debounce(async (value: React.Key | null) => {
    if (!value) return;
    try {
      // 根据选择的账单ID获取账单详情
      const billDetail = await Apis.Bill.HouseBills.Show({
        id: Number(value) as number,
      });
      if (billDetail?.data) {
        // 在BetaSchemaForm的formList中，我们需要找到当前修改的项
        let allBillIds = form.getFieldValue('bill_ids') || [];
        // 查找当前修改的项
        const index = allBillIds.findIndex(
          (item: BillItem) => String(item.id) === String(value),
        );
        let total_paid_amount = 0;
        let total_payable_amount =
          Number(billDetail.data.total_payable_amount) || 0;
        allBillIds?.map((res: any, idx: number) => {
          total_paid_amount += res.total_payable_amount
            ? Number(res?.total_payable_amount) || 0
            : total_payable_amount;
          if (index === idx) {
            res.total_payable_amount = total_payable_amount;
            res.amount =
              res?.amount !== total_payable_amount
                ? res.amount > 0
                  ? res.amount
                  : total_payable_amount
                : total_payable_amount;
          }
        });
        form.setFieldValue('bill_ids', allBillIds);
        form.setFieldValue('total_paid_amount', total_paid_amount);
        console.log('allBillIds', allBillIds);
      }
    } catch (error) {
      console.error('获取账单详情失败:', error);
    }
  }, 500); // 500ms延迟

  return (
    <BetaSchemaForm<FormValues>
      {...MyModalFormProps.props}
      title="录入收款信息"
      trigger={<MyButtons.Create title="录入收款" />}
      labelAlign="left"
      width="800px"
      form={form}
      key={new Date().getTime()}
      onOpenChange={(open: boolean): void => {
        if (open) {
          form.resetFields(); // 清空表单数据

          let formValues: Record<string, any> = {};
          // 如果有item数据，先设置基础字段
          if (props.item) {
            formValues = {
              ...props.item,
              // total_paid_amount: props?.item?.total_payable_sum,
              accept_name: props.item?.receipt_account?.accept_name || '',
              accept_bank: props.item?.receipt_account?.accept_bank || '',
              accept_account: props.item?.receipt_account?.accept_account || '',
            };
          }
          console.log('props', props);
          // 如果有选中的账单ID，处理并设置到bill_ids
          if (props.selectedBillIds && props.selectedBillIds.length > 0) {
            // 构建bill_ids数组，包含id和未付金额
            formValues.bill_ids = props.selectedBillIds.map((res: any) => {
              return {
                id: res?.id,
                total_payable_amount: Number(res?.total_payable_amount) || 0,
              };
            });
          }

          form.setFieldsValue(formValues);
        }
      }}
      onFinish={async (values: any): Promise<boolean> => {
        // 校验amount汇总金额是否等于total_payable_amount
        const billIds = values.bill_ids || [];
        const amountSum = billIds.reduce(
          (acc: number, item: BillItem) => acc + (Number(item.amount) || 0),
          0,
        );
        const totalPaid = Number(values.total_paid_amount) || 0;

        if (Math.abs(amountSum - totalPaid) > 0.0) {
          // 考虑浮点数精度问题
          message.error('关联金额汇总必须等于收款金额');
          return false;
        }

        try {
          await Apis.HouseOrder.HouseOrders.Store({
            ...values,
          });
          props.reload?.();
          message.success(props.title + '成功');
          return true;
        } catch (error) {
          console.error('保存失败:', error);
          return false;
        }
      }}
      columns={[
        MyFormItems.EnumRadio({
          key: 'payment_method',
          title: '收款方式',
          colProps: { span: 12 },
          valueEnum: () => {
            const obj: Record<string, any> = JSON.parse(
              JSON.stringify(HouseOrdersPaymentMethodEnum),
            );
            delete obj.WeChat;
            delete obj.Alipay;
            delete obj.TongLian;
            delete obj.Prepayment;
            return obj;
          },
          required: true,
        }),
        {
          key: 'total_paid_amount',
          title: '收款金额',
          valueType: 'digit',
          colProps: { span: 6 },
          fieldProps: {
            style: { width: '100%' },
            addonAfter: '元',
            disabled: true,
          },
          formItemProps: { ...rulesHelper.number },
        },
        {
          key: 'paid_time',
          title: '收款日期',
          valueType: 'date',
          formItemProps: { ...rulesHelper.text },
          colProps: { span: 6 },
        },
        {
          valueType: 'divider',
          fieldProps: {
            orientation: 'left',
            children: '选择关联账单金额',
          },
        },
        {
          valueType: 'formList',
          dataIndex: 'bill_ids',
          formItemProps: { ...rulesHelper.array },
          fieldProps: {
            copyIconProps: false,
          },
          columns: [
            {
              valueType: 'group',
              colProps: { span: 24 },
              columns: [
                Selects?.HouseBill({
                  title: '选择关联账单',
                  key: 'id',
                  colProps: { span: 8 },
                  params: {
                    asset_houses_id: props.item?.asset_houses_id,
                    bill_status: [
                      HouseBillsBillStatusEnum.PendingPayment.value,
                      HouseBillsBillStatusEnum.PartiallyPaid.value,
                      HouseBillsBillStatusEnum.Overdue.value,
                    ],
                  },
                  formItemProps: { ...rulesHelper.number },
                  fieldProps: {
                    placeholder: '选择账单',
                    onChange: (value: React.Key | null) => {
                      console.log(value, 'value');
                      debouncedUpdateTotalList(value);
                    },
                  },
                  required: true,
                }),
                {
                  title: '未收金额',
                  valueType: 'number',
                  dataIndex: 'total_payable_amount',
                  colProps: { span: 6 },
                  fieldProps: {
                    style: { width: '100%' },
                    addonAfter: '元',
                    disabled: true,
                  },
                  dependencies: ['id'],
                  shouldUpdate: (
                    prevValues: Record<string, any>,
                    currentValues: Record<string, any>,
                  ) => {
                    return prevValues?.id !== currentValues?.id;
                  },
                },
                {
                  valueType: 'dependency',
                  name: ['total_payable_amount'],
                  columns: ({ total_payable_amount }) => {
                    console.log(total_payable_amount, 'total_payable_amount');
                    return [
                      {
                        title: '关联金额',
                        valueType: 'digit',
                        dataIndex: 'amount',
                        colProps: { span: 6 },
                        formItemProps: {
                          ...rulesHelper.number,
                          validateFirst: true,
                        },
                        fieldProps: {
                          max: total_payable_amount,
                          min: 0,
                          style: { width: '100%' },
                          addonAfter: '元',
                          onChange: () => {
                            debouncedUpdateTotal();
                            // let newBillIds = form.getFieldValue('bill_ids');
                            // let total_paid_amount = 0;
                            // newBillIds?.map((res: { amount?: number }) => {
                            //   total_paid_amount += Number(res?.amount) || 0;
                            // });
                            // console.log(newBillIds, value, 'newBillIds');
                            // form.setFieldValue(
                            //   'total_paid_amount',
                            //   total_paid_amount,
                            // );
                          },
                        },
                      },
                    ];
                  },
                },

                {
                  title: '备注',
                  dataIndex: 'remark',
                  colProps: { span: 4 },
                },
              ],
            },
          ],
        },
        {
          colProps: { span: 24 },
          renderFormItem: () => (
            <span style={{ color: '#5b5b5bff' }}>
              提示：确认后，需财务审核。
            </span>
          ),
        },
      ]}
    />
  );
}
