import { Form, Input, message, Modal, Radio, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import { BonusRuleListQueryType } from '@/api/interface/pointManageType';

// 编辑的数据类型
type DataType = (ReturnType<BonusRuleListQueryType> extends Promise<infer T>
  ? T
  : never)['result']['list'][0];

// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  push: any;
  data?: any;
  state?: { propObjCode?: { label: string; value: number }[] };
  selected: DataType['bonusSet'];
}

const DivideAddEditObject: React.FC<propType> = (props: propType) => {
  // 组件默认值
  DivideAddEditObject.defaultProps = {
    data: null,
    state: {},
  };
  // 参数
  const { title, open, closed, data, state, push, selected } = props;
  // 表单钩子
  const [form] = Form.useForm();
  // 分成方式
  const [divideMethod, setDivideMethod] = useState(0);
  // 分成方式列表
  const [proportionModeList, setProportionModeList] = useState<
    { label: string; value: number; disabled?: true }[]
  >([
    { label: '分成比例', value: 0 },
    { label: '差价分成', value: 1, disabled: true },
  ]);
  // 关闭弹窗
  const handleCancel = () => {
    // 重置表单
    form.resetFields();
    // 重置分成方式
    setDivideMethod(proportionModeList[0].value);
    // 重置分成对象
    form.setFieldValue('proportionMode', 0);
    // 重置分成方式列表
    setProportionModeList([
      { label: '分成比例', value: 0 },
      { label: '差价分成', value: 1, disabled: true },
    ]);
    // 关闭弹窗
    closed();
  };
  // 校验数据
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        // 处理数据并准备提交数据
        await handleSubmit({
          ...values,
          proportionParam: Number(values.proportionParam) / 100,
        });
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交数据
  const handleSubmit = async (values: any) => {
    // 添加数据的时候用时间戳当id
    push({
      id: new Date().getTime(),
      ...data,
      ...values,
    });
    message.success(data?.id ? '修改成功' : '添加成功').then();
    handleCancel();
  };
  // 分成对象选择渠道监听
  const handleChange = (e: number) => {
    if (e === 300) {
      setProportionModeList([
        { label: '分成比例', value: 0, disabled: true },
        { label: '差价分成', value: 1 },
      ]);
      form.setFieldValue('proportionMode', proportionModeList[1].value);
      setDivideMethod(proportionModeList[1].value);
    } else {
      setProportionModeList([
        { label: '分成比例', value: 0 },
        { label: '差价分成', value: 1, disabled: true },
      ]);
      form.setFieldValue('proportionMode', proportionModeList[0].value);
      setDivideMethod(proportionModeList[0].value);
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    // console.log("selected --->", selected);
    if (!data) return;
    form.setFieldsValue({
      ...data,
      proportionParam: (Number(data.proportionParam) * 100).toFixed(1),
    });
    setDivideMethod(data.proportionMode);
  }, [open]);
  return (
    <Modal open={open} title={title} onCancel={handleCancel} onOk={handleOk} destroyOnClose>
      <Form
        name='addForm'
        form={form}
        labelAlign='right'
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 10 }}
      >
        <Form.Item
          label='分成对象'
          name='propObjCode'
          rules={[{ required: true, message: '请选择分成对象' }]}
        >
          <Select
            placeholder='请选择分成对象'
            options={state?.propObjCode?.map((i) => ({
              label: i.label,
              value: i.value,
              disabled: selected.some((j) => j.propObjCode === i.value),
            }))}
            onChange={handleChange}
          />
        </Form.Item>
        <Form.Item
          label='分成方式'
          name='proportionMode'
          rules={[{ required: true, message: '请选择分成方式' }]}
          initialValue={divideMethod}
        >
          <Radio.Group
            options={proportionModeList}
            onChange={({ target: { value } }) => setDivideMethod(value)}
          />
        </Form.Item>
        {divideMethod === 0 && (
          <>
            <Form.Item
              label='分成参数'
              name='proportionParam'
              rules={[
                { required: true, message: '请输入分成额度百分比' },
                // 只能输入0.1到100.0的一位小数,不能大于100.0
                {
                  pattern: /^(100(\.0)?|[1-9]?\d(\.\d)?)$/,
                  message: '只能输入0.1到100.0的一位小数',
                },
              ]}
            >
              <Input placeholder='请输入分成额度百分比' maxLength={10} type='number' suffix='%' />
            </Form.Item>
            <div style={{ margin: '0 0 10px 60px' }}>
              说明：分成比例基数以订单金额减去相关渠道利润的得数为基准
            </div>
          </>
        )}
      </Form>
    </Modal>
  );
};

export default DivideAddEditObject;
