import {
  BetaSchemaForm,
  ProCard,
  type ProFormColumnsType,
} from '@ant-design/pro-components';
import {
  Badge,
  Button,
  Divider,
  Form,
  Input,
  InputNumber,
  message,
  Radio,
  Space,
  Statistic,
  Table,
  Typography,
} from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import CommonModal from '@/components/ModalCom/CommonModal';
import styles from './createSales.module.less';

const { Title, Text } = Typography;

type DataSourceType = {
  id: React.Key;
  prod: string;
  num: number;
  state: string;
  availableNum: number; // 新增：可退款数量
};

const CreateSalesModal = () => {
  const [loading, setLoading] = useState(false);
  const [formSales] = Form.useForm();
  const [formApply] = Form.useForm();
  const [open, setOpen] = useState<boolean>(false);
  const [cancelRemarkType, setCancelRemarkType] = useState<string>('');

  const handleOk = useCallback(async () => {
    try {
      setLoading(true);
      const values1 = await formApply.validateFields();
      const values2 = await formSales.validateFields();

      console.log('申请信息:', values1);
      console.log('售后信息:', values2);
      console.log('表格数据:', values2.extendRefunds);

      message.success('提交成功');
      onOpen(false);
    } catch (error) {
      console.error('表单验证失败:', error);
      message.error('请完善表单信息');
    } finally {
      setLoading(false);
    }
  }, [formApply, formSales]);

  const onOpen = useCallback(
    (flag: boolean) => {
      setOpen(flag);
      if (!flag) {
        setCancelRemarkType('');
        formSales.resetFields();
        formApply.resetFields();
      }
    },
    [formSales, formApply],
  );

  const applyColumns: ProFormColumnsType[] = [
    {
      title: '售后类型',
      dataIndex: 'cancelReason1',
      valueType: 'radio',
      formItemProps: {
        rules: [{ required: true }],
      },
      fieldProps: {
        options: [
          { value: '用户主动取消', label: '用户主动取消' },
          { value: '选项二', label: '选项二' },
          { value: '选项三', label: '选项三' },
          { value: '选项四', label: '选项四' },
          { value: '选项五', label: '选项五' },
          { value: '选项六', label: '选项六' },
          { value: '选项七', label: '选项七' },
        ],
        style: {
          display: 'flex',
          flexDirection: 'column',
          gap: '8px',
          marginTop: '6px',
          background: '#f0f0f0',
          padding: '8px',
          borderRadius: '8px',
        },
      },
    },
    {
      title: '问题描述',
      dataIndex: 'cancelRemark22',
      valueType: 'textarea',
    },
    {
      title: '商家备注',
      dataIndex: 'cancelRemark2311',
      valueType: 'textarea',
    },
  ];

  return (
    <>
      <Button onClick={() => onOpen(true)}>新建售后</Button>
      <CommonModal
        title="新建售后单"
        open={open}
        onOk={handleOk}
        onCancel={() => onOpen(false)}
        confirmLoading={loading}
        width={1000}
      >
        <Space
          direction="vertical"
          style={{ width: '100%' }}
          size={16}
          className={styles.sales}
        >
          {/* 统计卡片 */}
          <ProCard.Group direction="row">
            <ProCard layout="center">
              <Statistic title="实付金额" value={1000} precision={2} />
            </ProCard>
            <ProCard layout="center">
              <Statistic title="累计退款金额" value={200} precision={2} />
            </ProCard>
            <ProCard layout="center">
              <Statistic title="可退款金额" value={800} precision={2} />
            </ProCard>
          </ProCard.Group>

          {/* 售后选项 */}
          <ProCard title="售后选项">
            <Form
              form={formSales}
              layout="horizontal"
              labelCol={{ style: { width: '80px' } }}
              labelAlign="right"
            >
              <Form.Item
                name="cancelReason"
                label="售后类型"
                rules={[{ required: true, message: '请选择售后类型' }]}
              >
                <Radio.Group buttonStyle="solid">
                  <Radio.Button value="仅退款">仅退款</Radio.Button>
                </Radio.Group>
              </Form.Item>

              <Form.Item
                name="cancelRemark"
                label="退款类型"
                rules={[{ required: true, message: '请选择退款类型' }]}
              >
                <Radio.Group
                  buttonStyle="solid"
                  onChange={(e) => {
                    setCancelRemarkType(e.target.value);
                    // 切换类型时清空相关字段
                    formSales.setFieldsValue({
                      cancelRemarkText: undefined,
                      extendRefunds: undefined,
                    });
                  }}
                >
                  <Radio.Button value="整单退款（通用）">整单退款</Radio.Button>
                  <Radio.Button value="选项二">商品退款</Radio.Button>
                  <Radio.Button value="选项三">扩展服务退款</Radio.Button>
                  <Radio.Button value="服务附加费退款">
                    服务附加费退款
                  </Radio.Button>
                  <Radio.Button value="选项五">退运费</Radio.Button>
                  <Radio.Button value="其他">其他</Radio.Button>
                </Radio.Group>
              </Form.Item>

              {cancelRemarkType === '其他' && (
                <Form.Item
                  name="cancelRemarkText"
                  label=""
                  rules={[{ required: true, message: '请输入内容' }]}
                  labelCol={{ style: { width: '80px' } }}
                >
                  <Input.TextArea placeholder="请输入" rows={4} />
                </Form.Item>
              )}

              {cancelRemarkType === '服务附加费退款' && (
                <Form.Item
                  name="extendRefunds"
                  label=""
                  labelCol={{ style: { width: '80px' } }}
                  rules={[
                    {
                      required: true,
                      validator: (_, value) => {
                        if (!value || value.length === 0) {
                          return Promise.reject(
                            new Error('请至少选择一项服务附加费'),
                          );
                        }

                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <ExtendRefundsTable />
                </Form.Item>
              )}
            </Form>
          </ProCard>

          {/* 申请信息 */}
          <ProCard title="申请信息（通用表单样式，根据当前订单状态调用不同的申请原因表单）">
            <BetaSchemaForm
              layoutType="Form"
              form={formApply}
              columns={applyColumns}
              layout="horizontal"
              submitter={false}
              labelCol={{ style: { width: '80px' } }}
              labelAlign="right"
            />
          </ProCard>

          {/* 预估退款明细 */}
          <ProCard split="vertical" headerBordered title="预估退款明细">
            <ProCard
              colSpan={'50%'}
              headerBordered
              title="预估退款明细"
              size="small"
            >
              <Space align="center" style={{ marginBottom: 16 }}>
                <div>
                  <Text type="danger">最高退款金额</Text>
                  <Text type="secondary">（不含虚拟资产）</Text>
                </div>
                <InputNumber
                  min={1}
                  max={10000}
                  precision={0}
                  prefix="￥"
                  style={{ width: '120px' }}
                  defaultValue={700}
                />
              </Space>
              <div>
                <Text type="secondary">
                  退款金额上限 <Text type="danger">¥700</Text>
                  ，金额不支持修改，优惠券、积分、余额等虚拟资产不支持修改，虚拟资产将随退款而原路退回，具体金额以实际情况为准。
                </Text>
              </div>
              <Divider />
              <Title level={5}>预估退款项</Title>
              <Space direction="vertical" size={8} style={{ width: '100%' }}>
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>商品/服务</Text>
                      <Text>合计¥500</Text>
                    </div>
                  }
                />
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>增值/扩展服务</Text>
                      <Text>合计¥500</Text>
                    </div>
                  }
                />
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>运费</Text>
                      <Text>合计¥500</Text>
                    </div>
                  }
                />
              </Space>
            </ProCard>
            <ProCard
              size="small"
              headerBordered
              title="预估退款至"
              colSpan={'50%'}
            >
              <Title level={5}>
                预估退款项
                <Text type="secondary">（退款方式：原支付方式返还）</Text>
              </Title>
              <Space direction="vertical" size={8} style={{ width: '100%' }}>
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>
                        微信支付
                        <Text type="secondary">（建设银行 尾号1626）</Text>
                      </Text>
                      <Text>¥500</Text>
                    </div>
                  }
                />
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>
                        钱包余额
                        <Text type="secondary">（个人钱包 编号1090）</Text>
                      </Text>
                      <Text>¥500</Text>
                    </div>
                  }
                />
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>宠豆豆(积分)</Text>
                      <Text>¥500</Text>
                    </div>
                  }
                />
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>红包</Text>
                      <Text>¥500</Text>
                    </div>
                  }
                />
              </Space>
              <Divider />
              <Title level={5}>预估扣除项</Title>
              <Text type="secondary">
                如果后续有设计退款时扣除比例的设定才会存在此字段。目前暂时不做这个业务逻辑，仅为布局占位。
              </Text>
              <Space direction="vertical" size={8} style={{ width: '100%' }}>
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>
                        违约金
                        <Text type="secondary">（服务开始前60分钟内退款）</Text>
                      </Text>
                      <Text>¥500</Text>
                    </div>
                  }
                />
              </Space>
            </ProCard>
          </ProCard>
        </Space>
      </CommonModal>
    </>
  );
};

const ExtendRefundsTable: React.FC<{
  value?: DataSourceType[];
  onChange?: (value: DataSourceType[]) => void;
}> = ({ value, onChange }) => {
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 初始化数据 - 默认值为 1，并设置可退款数量
  useEffect(() => {
    const initData: DataSourceType[] = Array.from({ length: 10 }).map(
      (_, index) => ({
        id: `service_${index}`,
        prod: `服务附加费项目${index + 1}`,
        num: 1,
        state: '待退款',
        availableNum: index % 3 === 0 ? 0 : Math.floor(Math.random() * 10) + 1, // 模拟数据，每3个有一个为0
      }),
    );

    if (!value) {
      setDataSource(initData);
      // 初始化时通知父组件，只选中可退款数量 > 0 的项
      const validItems = initData.filter((item) => item.availableNum > 0);
      const validKeys = validItems.map((item) => item.id);
      notifyChange(initData, validKeys);
      setSelectedRowKeys(validKeys);
    }
  }, []);

  // 当外部 value 变化时更新
  useEffect(() => {
    if (value && value.length > 0) {
      // 更新选中状态，只保留可退款数量 > 0 的项
      setSelectedRowKeys((prev) =>
        prev.filter((key) => {
          const item = value.find((v) => v.id === key);
          return item && item.availableNum > 0;
        }),
      );
    }
  }, [value]);

  // 通知父组件数据变化（包含选中信息）
  const notifyChange = (data: DataSourceType[], selected: React.Key[]) => {
    // 只返回选中的项
    const selectedData = data.filter((item) => selected.includes(item.id));
    onChange?.(selectedData);
  };

  const handleNumChange = (id: React.Key, num: number | null) => {
    const record = dataSource.find((item) => item.id === id);
    if (!record) return;

    // 如果可退款数量为0，不允许修改
    if (record.availableNum <= 0) return;

    const finalNum = num ?? 1;
    // 不能超过可退款数量
    const validNum = Math.min(finalNum, record.availableNum);

    const newData = dataSource.map((item) =>
      item.id === id ? { ...item, num: validNum } : item,
    );
    setDataSource(newData);

    // 如果数量变为 0 或负数，取消选中
    let newSelectedKeys = selectedRowKeys;
    if (validNum <= 0) {
      newSelectedKeys = selectedRowKeys.filter((key) => key !== id);
      setSelectedRowKeys(newSelectedKeys);
    }

    notifyChange(newData, newSelectedKeys);
  };

  // 判断是否有错误
  const isInvalid = (num: number | undefined | null): boolean => {
    if (num === undefined || num === null) return true;
    if (typeof num !== 'number') return true;
    if (num <= 0) return true;
    return false;
  };

  const columns = [
    {
      title: '服务项目',
      dataIndex: 'prod',
      key: 'prod',
      width: '30%',
      ellipsis: true,
    },
    {
      title: '退款信息',
      dataIndex: 'state',
      key: 'state',
      width: '20%',
    },
    {
      title: '可退款数量',
      dataIndex: 'availableNum',
      key: 'availableNum',
      width: '20%',
    },
    {
      title: <span style={{ color: 'red' }}>* 退款数量</span>,
      dataIndex: 'num',
      key: 'num',
      width: '30%',
      render: (value: number, record: DataSourceType) => {
        const hasError = isInvalid(value);
        const isDisabled = record.availableNum <= 0;

        return (
          <InputNumber
            min={1}
            max={record.availableNum} // 最大值为可退款数量
            value={value}
            onChange={(val) => handleNumChange(record.id, val)}
            disabled={isDisabled}
            style={{
              width: '100%',
            }}
            placeholder={isDisabled ? '不可退款' : '请输入退款数量'}
            precision={0}
          />
        );
      },
    },
  ];

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
      notifyChange(dataSource, newSelectedRowKeys);
    },
    getCheckboxProps: (record: DataSourceType) => ({
      disabled: record.availableNum <= 0, // 可退款数量为 0 时禁用选中
      name: record.prod,
    }),
  };

  return (
    <div>
      <div
        style={{
          marginBottom: 8,
          fontWeight: 500,
          fontSize: 14,
          color: '#000',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <span>服务附加费退款明细</span>
        <span style={{ fontSize: 12, fontWeight: 'normal', color: '#666' }}>
          已选择 {selectedRowKeys.length} 项
        </span>
      </div>
      <Table
        rowKey="id"
        dataSource={dataSource}
        columns={columns}
        rowSelection={rowSelection}
        size="small"
        bordered
        scroll={{ y: 300 }}
      />
    </div>
  );
};
export default CreateSalesModal;
