import {
  MyBetaModalFormProps,
  MyButtons,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { Apis } from '@/gen/Apis';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Form, message } from 'antd';

interface BatchSerialNumbersProps extends MyBetaModalFormProps {
  items?: any[];
}

export default function BatchSerialNumbers(props: BatchSerialNumbersProps) {
  const [form] = Form.useForm();
  const { items = [] } = props;
  // 计算总收款金额
  const totalAmount = items.reduce((sum, item) => {
    return sum + Number(item.actual_paid_amount || 0);
  }, 0);
  // 计算总收款手续费
  const totalFee = items.reduce((sum, item) => {
    return sum + Number(item.fee || 0);
  }, 0);
  // 计算到账金额（总收款金额 - 总手续费）
  const actualReceivedAmount = totalAmount - totalFee;
  // 获取收款账号信息（所有项目都相同）
  const receiptAccount = items[0]?.receipt_account || {};
  // 验证是否所有项目都有相同的收款账号
  const validateSameAccount = () => {
    if (items.length === 0) return true;

    const firstAccount = items[0].receipt_account?.company_account;
    return items.every(
      (item) => item.receipt_account?.company_account === firstAccount,
    );
  };

  return (
    <BetaSchemaForm<ApiTypes.HouseOrder.HouseOrders.BatchUpdateSerialNumber>
      {...MyModalFormProps.props}
      title={`关联银行流水`}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      labelAlign="left"
      width="500px"
      trigger={
        <MyButtons.Edit
          title={props.title || `批量关联`}
          size="middle"
          disabled={items.length === 0}
        />
      }
      key={new Date().getTime()}
      form={form}
      onOpenChange={(open: any) => {
        if (open && items.length > 0) {
          form.resetFields(); // 清空表单数据
          // 验证收款账号是否相同
          if (!validateSameAccount()) {
            message.error('请选择相同收款账号的收款单');
            return false;
          }
        }
      }}
      onFinish={async (values: any) => {
        // 再次验证收款账号是否相同
        if (!validateSameAccount()) {
          message.error('请选择相同收款账号的收款单');
          return false;
        }

        return Apis.HouseOrder.HouseOrders.BatchUpdateSerialNumber({
          ...values,
          ids: items.map((item) => item.id),
        })
          .then(() => {
            props.reload?.();
            message.success(props.title + '成功');
            return true;
          })
          .catch(() => false);
      }}
      columns={[
        {
          key: 'company_name',
          title: '收款账户',
          valueType: 'text',
          initialValue: receiptAccount.company_name || '-',
          fieldProps: {
            disabled: true,
          },
          colProps: { span: 24 },
        },
        {
          key: 'company_bank',
          title: '收款银行',
          valueType: 'text',
          initialValue: receiptAccount.company_bank || '-',
          fieldProps: {
            disabled: true,
          },
          colProps: { span: 24 },
        },
        {
          key: 'company_account',
          title: '收款账号',
          valueType: 'text',
          initialValue: receiptAccount.company_account || '-',
          fieldProps: {
            disabled: true,
          },
          colProps: { span: 24 },
        },
        {
          key: 'total_amount',
          title: '收款单汇总',
          valueType: 'number',
          initialValue: totalAmount,
          fieldProps: {
            disabled: true,
          },
          colProps: { span: 24 },
        },
        {
          key: 'totalFee',
          title: '手续费汇总',
          valueType: 'number',
          initialValue: totalFee,
          fieldProps: {
            disabled: true,
          },
          colProps: { span: 24 },
        },
        {
          key: 'actual_received_amount',
          title: '应到账金额',
          valueType: 'number',
          initialValue: actualReceivedAmount,
          fieldProps: {
            disabled: true,
          },
          colProps: { span: 24 },
        },

        {
          key: 'serial_number',
          title: '银行流水号',
          formItemProps: { ...rulesHelper.text },
          colProps: { span: 24 },
        },
      ]}
    />
  );
}
