import React, { useContext, useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Form, Input, Select, Checkbox, Radio, Space, InputNumber } from 'antd';
import { Title } from './CommonTemplate';
import { formItemLayout } from '../config';
import { ServiceContext } from '../context';
import { debounce } from '@/utils/utils';

const createInitValues = () => ({
  settlementMethod: 1,
  limitPurchase: null, // 是否限购1:限购/0:不限购
  limitPurchaseType: null, // 限购类型，如果限购必填1:长期限购/2:周期限购
  limitPurchaseCycle: null, // 限购周期1：每天/7：7天/30：30天
  limitPurchaseQuantity: null, // 限购数量
  packageContent: '',

  appointment: null, // 预约
  receptionVolume: null,
});

const FormSettlementOthers = forwardRef((props, ref) => {
  const { editData } = props;
  const [form] = Form.useForm();
  const [initValue, setInitValue] = useState(createInitValues());
  const customer = useContext(ServiceContext);

  const onCheck = async () => {
    try {
      const values = await form.validateFields();
      return {
        ...values,
        temp: 'settlementItem',
        limitPurchase: values.limitPurchase ? 1 : 0,
      };
    } catch (errorInfo) {
      return null;
    }
  };

  const getFormValues = debounce(() => {
    const values = form.getFieldsValue();
    props.onValuesChange({ settlementItem: values });
  }, 400);

  useEffect(() => {
    if (customer.isEdit || customer.isUseCache) {
      if (!editData) return;
      form.setFieldsValue(editData);
      setInitValue({ ...editData });
    }
  }, [customer.isEdit, customer.isUseCache, editData]);

  useImperativeHandle(ref, () => ({
    onCheck,
    reset: () => {
      setInitValue(createInitValues());
      form.resetFields();
    },
  }));

  const radioChangeEvent = key => {
    const value = form.getFieldValue(key);
    setInitValue({
      ...initValue,
      [key]: value,
    });
  };

  const AuditLimitPurchaseType = () => {
    const limitPurchaseType = form.getFieldValue('limitPurchaseType');
    if (limitPurchaseType === 1) {
      return null;
    }
    return (
      <Form.Item name="limitPurchaseCycle" rules={[{ required: true, message: '请选择限购周期' }]}>
        <Select placeholder="请选择限购周期" style={{ width: 150 }}>
          <Select.Option value={1}>每天</Select.Option>
          <Select.Option value={7}>7天</Select.Option>
          <Select.Option value={30}>30天</Select.Option>
        </Select>
      </Form.Item>
    );
  };

  const AuditLimitPurchaseTemplate = () => {
    if (!initValue.limitPurchase) {
      return null;
    }

    const PurchaseTemplate =
      initValue.limitPurchaseType !== null ? (
        <Form.Item wrapperCol={{ offset: 3, span: 16 }}>
          <Space>
            {AuditLimitPurchaseType()}
            <Form.Item
              name="limitPurchaseQuantity"
              rules={[{ required: initValue.limitPurchase, message: '请输入限购数量' }]}
            >
              <InputNumber placeholder="请输入限购数量" style={{ width: 150 }} />
            </Form.Item>
          </Space>
        </Form.Item>
      ) : null;

    return (
      <>
        <Form.Item
          name="limitPurchaseType"
          wrapperCol={{ offset: 3, span: 16 }}
          rules={[{ required: true, message: '请选择限购类型' }]}
        >
          <Radio.Group onChange={() => radioChangeEvent('limitPurchaseType')}>
            <Space direction="vertical">
              <Radio value={1}>每ID限购</Radio>
              <Radio value={2}>按周期限购</Radio>
            </Space>
          </Radio.Group>
        </Form.Item>
        {PurchaseTemplate}
      </>
    );
  };
  return (
    <Form
      {...formItemLayout}
      form={form}
      name="register"
      initialValues={initValue}
      scrollToFirstError
      onValuesChange={getFormValues}
    >
      <Form.Item
        name="appointment"
        label="预约"
        rules={[{ required: true, message: '请选择是否预约！' }]}
      >
        <Radio.Group>
          <Radio value={1}>是</Radio>
          <Radio value={0}>否</Radio>
        </Radio.Group>
      </Form.Item>
      <Form.Item
        name="receptionVolume"
        label="每日最低接待量"
        // rules={[{ required: true, message: '每日最低接待量' }]}
      >
        <InputNumber min={0} style={{ width: 200 }} placeholder="请输入每日最低接待量" />
      </Form.Item>
      <Title title="结算信息" />
      {/* <Form.Item
        name="packageContent"
        label="套餐内容"
        rules={[{ required: true, message: '请输入套餐内容, 1000字以内！！' }]}
      >
        <Input.TextArea showCount maxLength={1000} placeholder="请输入套餐内容, 1000字以内！！" />
      </Form.Item> */}
      <Form.Item
        name="settlementMethod"
        label="结算方式"
        rules={[{ required: true, message: '请输入套餐内容！' }]}
        extra="自动分账: 合同期内订单结算款实时分账到甲方指定账号。"
      >
        <span style={{ color: 'rgba(0, 0, 0, 0.45)' }}>(默认)</span>
      </Form.Item>

      <Title title="其他设置" />
      <Form.Item label="限购" name="limitPurchase" valuePropName="checked">
        <Checkbox onChange={() => radioChangeEvent('limitPurchase')}>
          <b style={{ marginLeft: 10 }}>启用限购</b>
          <span style={{ marginLeft: 10 }} className="ant-form-text">
            限制每人可购买数量
          </span>
        </Checkbox>
      </Form.Item>
      {AuditLimitPurchaseTemplate()}
    </Form>
  );
});

export default FormSettlementOthers;
