import { FC, forwardRef, useImperativeHandle, useState } from "react";
import { DatePicker, Form, Input, Radio, Select } from "antd";
import dayjs from "dayjs";
import { RangePickerProps } from "antd/es/date-picker";
import { shareCouponType } from "~/api/interface/couponManage";
import { MakeItemEntity } from "~/api/interface/makeManage";
import { splitCouponType, splitCouponUseType } from "~/utils/dictionary";

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

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

    useImperativeHandle(ref, () => ({
      getForm: () => shareCouponForm,
      setCouponType: (type: number) => setCouponType(type),
    }));

    // 门槛类型选择
    const couponTypeChange = (e: any) => {
      shareCouponForm.setFieldValue(
        "verificationType",
        e.target.value === 3 ? 0 : undefined
      );
      setCouponType(e.target.value);
      shareCouponForm.setFieldValue("minPrice", undefined);
    };

    // 表单规则
    // 钱-基本校验
    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 = shareCouponForm.getFieldValue("minPrice");
      const discount = shareCouponForm.getFieldValue("couponDiscount");
      const couponMoney = shareCouponForm.getFieldValue("couponMoney");
      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 = shareCouponForm.getFieldValue("minPrice");
      if (couponType === 1) {
        if (isOverstep()) {
          return Promise.reject(
            new Error("优惠金额超出最高优惠金额，请重新输入")
          );
        }
        if (
          shareCouponForm.getFieldValue("couponDiscount") &&
          !shareCouponForm.isFieldValidating("couponDiscount")
        ) {
          await shareCouponForm.validateFields(["couponDiscount"]);
        }
      }
      if (couponType !== 3) {
        if (minPrice && Number(minPrice) < Number(value)) {
          return Promise.reject(new Error("优惠金额应小于减免券金额"));
        }
        if (minPrice && !shareCouponForm.isFieldValidating("minPrice")) {
          await shareCouponForm.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 = shareCouponForm.getFieldValue("couponMoney");
      if (couponMoney && Number(couponMoney) > Number(value)) {
        return Promise.reject(new Error("满减金额应大于优惠金额!"));
      }
      if (couponMoney && !shareCouponForm.isFieldValidating("couponMoney")) {
        shareCouponForm.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 (
        shareCouponForm.getFieldValue("couponMoney") &&
        !shareCouponForm.isFieldValidating("couponMoney")
      ) {
        shareCouponForm.validateFields(["couponMoney"]).then().catch();
      }
      return Promise.resolve();
    };
    const negativeNumberValidator = (
      rule: any,
      value: string,
      callback: (error?: string) => void,
      label: string
    ) => {
      if (!value) {
        return Promise.reject(new Error(`请输入${label}!`));
      }
      const reg = /^[0-9]*$/;
      if (!reg.test(value)) {
        return Promise.reject(new Error(`${label}为正数!`));
      }
      switch (label) {
        case "发行量":
          if (Number(value) < 1 || Number(value) > 100000) {
            return Promise.reject(new Error(`${label}至少1张且不超过10万`));
          }
          break;
        case "限领数量":
          if (Number(value) > 5) {
            return Promise.reject(new Error(`${label}限领数量最大为5`));
          }
          break;
      }
      return Promise.resolve();
    };
    // 选择时间禁用
    const disabledDate: RangePickerProps["disabledDate"] = (current) => {
      // Can not select days before today
      return current && current < dayjs().subtract(1, "day");
    };
    return (
      <div className="share-coupon-info">
        <div className="title">分享者优惠券</div>
        <div className="share-coupon-form">
          <Form
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 5 }}
            form={shareCouponForm}
            initialValues={{ useType: 2, couponType: 3, verificationType: 0 }}
            disabled={isDetail}
          >
            <Form.Item
              label="券类型"
              name="useType"
              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="primaryKey"
              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="time"
              rules={[{ required: true, message: "请选择有效期" }]}
            >
              <DatePicker.RangePicker disabledDate={disabledDate} />
            </Form.Item>
            <Form.Item
              label="优惠金额"
              name="couponMoney"
              rules={[
                {
                  required: true,
                  validator: couponMoneyValidator,
                },
              ]}
            >
              <Input placeholder="请输入优惠券金额" suffix="元" />
            </Form.Item>
            <Form.Item
              label="使用门槛"
              name="couponType"
              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="minPrice"
                rules={[
                  {
                    required: true,
                    validator: minPriceValidator,
                  },
                ]}
              >
                <Input placeholder="请输入金额" suffix="元" />
              </Form.Item>
            )}
            {couponType === 1 && (
              <>
                <Form.Item
                  label="打"
                  style={{ marginLeft: "30px" }}
                  name="couponDiscount"
                  rules={[
                    {
                      required: true,
                      validator: discountValidator,
                    },
                  ]}
                >
                  <Input placeholder="请输入折扣" suffix="折" />
                </Form.Item>
                {/* <Form.Item */}
                {/*  label="最多优惠" */}
                {/*  style={{ marginLeft: "30px" }} */}
                {/*  name="preferentialLimit" */}
                {/*  rules={[ */}
                {/*    { */}
                {/*      required: true, */}
                {/*      validator: (rule, value, callback) => */}
                {/*        moneyValidator(rule, value, callback, "最多优惠"), */}
                {/*    }, */}
                {/*  ]} */}
                {/* > */}
                {/*  <Input placeholder="请输入最多优惠" suffix="元" /> */}
                {/* </Form.Item> */}
              </>
            )}
            {couponType === 3 && (
              <Form.Item
                label="核销方式"
                name="verificationType"
                rules={[{ required: true, message: "请选择核销方式" }]}
              >
                <Radio.Group>
                  <Radio value={0}>单次核销</Radio>
                  <Radio value={1}>多次核销</Radio>
                </Radio.Group>
              </Form.Item>
            )}

            <Form.Item
              label="发行量"
              name="couponTotal"
              rules={[
                {
                  required: true,
                  validator: (rule, value, callback) =>
                    negativeNumberValidator(rule, value, callback, "发行量"),
                },
              ]}
            >
              <Input placeholder="请输入发行量" suffix="张" />
            </Form.Item>
            {/* <Form.Item */}
            {/*  label="每人限领" */}
            {/*  name="restrictedAccess" */}
            {/*  rules={[ */}
            {/*    { */}
            {/*      required: true, */}
            {/*      validator: (rule, value, callback) => */}
            {/*        negativeNumberValidator(rule, value, callback, "限领数量"), */}
            {/*    }, */}
            {/*  ]} */}
            {/* > */}
            {/*  <Input placeholder="请输入限领数量" suffix="张" /> */}
            {/* </Form.Item> */}
            <Form.Item
              label="分享人数"
              name="peopleNumber"
              rules={[
                {
                  required: true,
                  message: "请选择分享人数",
                },
              ]}
            >
              <Select placeholder="请输入分享人数">
                <Select value={2}>2人</Select>
                <Select value={3}>3人</Select>
                <Select value={5}>5人</Select>
              </Select>
            </Form.Item>
            <Form.Item label="被分享用户标签" name="userTag">
              <Select placeholder="请选择标签" allowClear>
                <Select.Option value={1}>新人</Select.Option>
                <Select.Option value={2}>实名认证</Select.Option>
                <Select.Option value={3}>企业认证</Select.Option>
              </Select>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
);

export default ShareCouponInfo;
