import { FC, forwardRef, useImperativeHandle, useState } from 'react';
import { Col, Form, Input, Radio, Row, Select } from 'antd';
import { MakeItemEntity } from '~/api/interface/makeManage';
import { sharedCouponType } from '~/api/interface/couponManage';
import { splitCouponType, splitCouponUseType } from '~/utils/dictionary';

interface selfProps {
  ref: any;
  makeList: MakeItemEntity[];
  shareCouponRef: any;
  isDetail: boolean;
}

const SharedCouponInfo: FC<selfProps> = forwardRef(
  ({ makeList, shareCouponRef, isDetail }, ref) => {
    const [sharedCouponForm] = Form.useForm<sharedCouponType>();
    // 优惠券类型
    const [couponType, setCouponType] = useState<number>(3);

    useImperativeHandle(ref, () => ({
      getForm: () => sharedCouponForm,
      setCouponType: (type: number) => setCouponType(type),
    }));
    // 门槛类型选择
    const couponTypeChange = (e: any) => {
      sharedCouponForm.setFieldValue(
        'beSharedVerificationType',
        e.target.value === 3 ? 0 : undefined,
      );
      sharedCouponForm.setFieldValue('beSharedMinPrice', undefined);
      setCouponType(e.target.value);
    };
    // 获取被分享者最低发行量
    const getMinBeSharedCouponTotal = (): number => {
      const shareCouponRefObj = shareCouponRef.current;
      const couponTotal = shareCouponRefObj.getForm().getFieldValue('couponTotal');
      const peopleNumber = shareCouponRefObj.getForm().getFieldValue('peopleNumber');
      return (couponTotal && peopleNumber && Number(couponTotal) * Number(peopleNumber) * 1.5) || 0;
    };
    // 表单规则
    // 钱-基本校验
    const moneyValidator = (value: string) => {
      if (Number(value) < 0) {
        return Promise.reject(new Error('金额不能为负值!'));
      }
      if (Number(value) > 99999.99) {
        return Promise.reject(new Error('金额不能大于99999.99!'));
      }
      if (Number(value) < 0) {
        return Promise.reject(new Error('金额不能为负值!'));
      }
      const reg = /^0\.([1-9]|\d[1-9])$|^[0-9]\d{0,8}\.\d{0,2}$|^[0-9]\d{0,8}$/;
      if (!reg.test(value) && value) {
        return Promise.reject(new Error('金额应为整数,小数且小数保留后两位'));
      }
      return Promise.resolve();
    };
    // 优惠金额是否超标
    const isOverstep = () => {
      const minPrice = sharedCouponForm.getFieldValue('beSharedMinPrice');
      const discount = sharedCouponForm.getFieldValue('beSharedCouponDiscount');
      const couponMoney = sharedCouponForm.getFieldValue('beSharedCouponMoney');
      return (
        minPrice &&
        discount &&
        couponMoney &&
        Number(couponMoney) > Number(minPrice) * Number(discount) * 0.1
      );
    };
    const couponMoneyValidator = async (rule: any, value: string) => {
      if (!value) {
        return Promise.reject(new Error('请输入优惠金额'));
      }
      const res: any = await moneyValidator(value);
      if (res) {
        return Promise.reject(res);
      }
      const minPrice = sharedCouponForm.getFieldValue('beSharedMinPrice');
      if (couponType === 1) {
        if (isOverstep()) {
          return Promise.reject(new Error('优惠金额超出最高优惠金额，请重新输入'));
        }
        if (
          sharedCouponForm.getFieldValue('beSharedCouponDiscount') &&
          !sharedCouponForm.isFieldValidating('beSharedCouponDiscount')
        ) {
          await sharedCouponForm.validateFields(['beSharedCouponDiscount']);
        }
      }
      if (couponType !== 3) {
        if (minPrice && Number(minPrice) < Number(value)) {
          return Promise.reject(new Error('优惠金额应小于减免券金额'));
        }
        if (minPrice && !sharedCouponForm.isFieldValidating('beSharedMinPrice')) {
          await sharedCouponForm.validateFields(['minPrice']);
        }
      }
      return Promise.resolve();
    };
    const minPriceValidator = async (rule: any, value: string) => {
      if (!value) {
        return Promise.reject(new Error('请输入满减金额'));
      }
      const res: any = await moneyValidator(value);
      if (res) {
        return Promise.reject(res);
      }
      const couponMoney = sharedCouponForm.getFieldValue('beSharedCouponMoney');
      if (couponMoney && Number(couponMoney) > Number(value)) {
        return Promise.reject(new Error('满减金额应大于优惠金额!'));
      }
      if (couponMoney && !sharedCouponForm.isFieldValidating('beSharedCouponMoney')) {
        sharedCouponForm.validateFields(['couponMoney']).then().catch();
      }
      return Promise.resolve();
    };
    const discountValidator = (rule: any, value: string) => {
      if (value === '') {
        return Promise.reject(new Error(`请输入折扣!`));
      }
      if (Number(value) <= 0) {
        return Promise.reject(new Error('折扣不能小于等于0!'));
      }
      if (Number(value) >= 10) {
        return Promise.reject(new Error('折扣应小于10'));
      }
      const reg = /^0\.([1-9]|\d[1-9])$|^[0-9]\d{0,8}\.\d{0,2}$|^[0-9]\d{0,8}$/;
      if (!reg.test(value)) {
        return Promise.reject(new Error('折扣应为整数,小数且小数保留后两位'));
      }
      if (isOverstep()) {
        return Promise.reject(new Error('优惠金额超出最高优惠金额!'));
      }
      if (
        sharedCouponForm.getFieldValue('beSharedCouponMoney') &&
        !sharedCouponForm.isFieldValidating('beSharedCouponMoney')
      ) {
        sharedCouponForm.validateFields(['beSharedCouponMoney']).then().catch();
      }
      return Promise.resolve();
    };
    const beSharedCouponTotalValidator = (rule: any, value: string) => {
      if (!value) {
        return Promise.reject(new Error(`请输入被分享者优惠券发行量`));
      }
      const reg = /^[0-9]*$/;
      if (!reg.test(value)) {
        return Promise.reject(new Error(`被分享者优惠券发行量为正数!`));
      }
      if (Number(value) < getMinBeSharedCouponTotal()) {
        return Promise.reject(new Error('被分享者券发行量大于等于分享者券发行量*分享人数*1.5'));
      }
      return Promise.resolve();
    };
    return (
      <div className='shared-coupon-info'>
        <div className='title'>被分享者优惠券</div>
        <div className='shared-coupon-form'>
          <Form
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 5 }}
            form={sharedCouponForm}
            initialValues={{
              beSharedUseType: 2,
              beSharedCouponType: 3,
              beSharedVerificationType: 0,
            }}
            disabled={isDetail}
          >
            <Form.Item
              label='券类型'
              name='beSharedUseType'
              rules={[{ required: true, message: '请选择券类型' }]}
            >
              <Radio.Group>
                {splitCouponUseType.map((v) => (
                  <Radio value={v.val} key={v.val} disabled={v.val !== 2}>
                    {v.label}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label='品牌'
              name='beSharedPrimaryKey'
              rules={[{ required: true, message: '请选择品牌' }]}
            >
              <Select
                placeholder='请选择品牌'
                mode='multiple'
                maxTagCount={50}
                filterOption={(input, option) =>
                  (option!.children as unknown as string)
                    .toLowerCase()
                    .includes(input.toLowerCase())
                }
              >
                {makeList.map((v) => (
                  <Select.Option value={v.id} key={v.id}>
                    {v.brandName}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              label='优惠金额'
              name='beSharedCouponMoney'
              rules={[
                {
                  required: true,
                  validator: couponMoneyValidator,
                },
              ]}
            >
              <Input placeholder='请输入优惠券金额' suffix='元' />
            </Form.Item>
            <Form.Item
              label='使用门槛'
              name='beSharedCouponType'
              rules={[{ required: true, message: '请选择使用门槛' }]}
            >
              <Radio.Group onChange={couponTypeChange}>
                {splitCouponType.map((v) => (
                  <Radio value={v.val} key={v.val}>
                    {v.label}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            {couponType !== 3 && (
              <Form.Item
                label='满'
                style={{ marginLeft: '30px' }}
                name='beSharedMinPrice'
                rules={[
                  {
                    required: true,
                    validator: minPriceValidator,
                  },
                ]}
              >
                <Input placeholder='请输入金额' suffix='元' />
              </Form.Item>
            )}
            {couponType === 1 && (
              <Form.Item
                label='打'
                style={{ marginLeft: '30px' }}
                name='beSharedCouponDiscount'
                rules={[
                  {
                    required: true,
                    validator: discountValidator,
                  },
                ]}
              >
                <Input placeholder='请输入折扣' suffix='折' />
              </Form.Item>
            )}
            {/* <Form.Item */}
            {/*  label="最多优惠" */}
            {/*  style={{ marginLeft: "30px" }} */}
            {/*  name="beSharedPreferentialLimit" */}
            {/*  rules={[ */}
            {/*    { */}
            {/*      required: false, */}
            {/*      validator: (rule, value, callback) => */}
            {/*        moneyValidator(rule, value, callback, "最多优惠"), */}
            {/*    }, */}
            {/*  ]} */}
            {/* > */}
            {/*  <Input placeholder="请输入最多优惠" suffix="元" /> */}
            {/* </Form.Item> */}
            {couponType === 3 && (
              <Form.Item
                label='核销方式'
                name='beSharedVerificationType'
                rules={[{ required: true, message: '请选择核销方式' }]}
              >
                <Radio.Group>
                  <Radio value={0}>单次核销</Radio>
                  <Radio value={1}>多次核销</Radio>
                </Radio.Group>
              </Form.Item>
            )}

            <Form.Item
              label='发行量'
              name='beSharedCouponTotal'
              rules={[
                {
                  required: true,
                  validator: beSharedCouponTotalValidator,
                },
              ]}
            >
              <Input placeholder='请输入发行量' suffix='张' />
            </Form.Item>
            <Row>
              <Col span={2} />
              <Col span={22} style={{ color: '#1677ff' }}>
                被分享者券发行量大于等于分享者券发行量*分享人数*1.5
              </Col>
            </Row>
            <Form.Item label='每人限领'>1张</Form.Item>
          </Form>
        </div>
      </div>
    );
  },
);
export default SharedCouponInfo;
