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: $t('select.purchase.cycle') }]}>
        <Select placeholder={$t('select.purchase.cycle')} style={{ width: 150 }}>
          <Select.Option value={1}>{$t('daily')}</Select.Option>
          <Select.Option value={7}>{$t('7.days')}</Select.Option>
          <Select.Option value={30}>{$t('30.days')}</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: $t('enter.purchase.limit') }]}
            >
              <InputNumber placeholder={$t('enter.purchase.limit')} style={{ width: 150 }} />
            </Form.Item>
          </Space>
        </Form.Item>
      ) : null;

    return (
      <>
        <Form.Item
          name="limitPurchaseType"
          wrapperCol={{ offset: 3, span: 16 }}
          rules={[{ required: true, message: $t('select.limit.type') }]}
        >
          <Radio.Group onChange={() => radioChangeEvent('limitPurchaseType')}>
            <Space direction="vertical">
              <Radio value={1}>{$t('per.id.limit')}</Radio>
              <Radio value={2}>{$t('cyclebased.limit')}</Radio>
            </Space>
          </Radio.Group>
        </Form.Item>
        {PurchaseTemplate}
      </>
    );
  };
  return (
    <Form
      {...formItemLayout}
      form={form}
      name="register"
      initialValues={initValue}
      scrollToFirstError
      onValuesChange={getFormValues}
    >
      <Form.Item
        name="appointment"
        label={$t('appointment')}
        rules={[{ required: true, message: $t('select.reservation') }]}
      >
        <Radio.Group>
          <Radio value={1}>{$t('yes')}</Radio>
          <Radio value={0}>{$t('no')}</Radio>
        </Radio.Group>
      </Form.Item>
      <Form.Item
        name="receptionVolume"
        label={$t('daily.min.reception')}
        // rules={[{ required: true, message: '每日最低接待量' }]}
      >
        <InputNumber min={0} style={{ width: 200 }} placeholder={$t('enter.daily.min.capacity')} />
      </Form.Item>
      <Title title={$t('settlement.info')} />
      {/* <Form.Item
        name="packageContent"
        label="套餐内容"
        rules={[{ required: true, message: '请输入套餐内容, 1000字以内！！' }]}
      >
        <Input.TextArea showCount maxLength={1000} placeholder="请输入套餐内容, 1000字以内！！" />
      </Form.Item> */}
      <Form.Item
        name="settlementMethod"
        label={$t('settlement.method')}
        rules={[{ required: true, message: $t('enter.package.content') }]}
        extra={$t('autosplit.realtime.fund.distribution')}
      >
        <span style={{ color: 'rgba(0, 0, 0, 0.45)' }}>{$t('default')}</span>
      </Form.Item>

      <Title title={$t('other.settings')} />
      <Form.Item label={$t('purchase.limit')} name="limitPurchase" valuePropName="checked">
        <Checkbox onChange={() => radioChangeEvent('limitPurchase')}>
          <b style={{ marginLeft: 10 }}>{$t('enable.purchase.limit')}</b>
          <span style={{ marginLeft: 10 }} className="ant-form-text">{$t('purchase.limit.per.person')}</span>
        </Checkbox>
      </Form.Item>
      {AuditLimitPurchaseTemplate()}
    </Form>
  );
});

export default FormSettlementOthers;
