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

const { Option } = Select;
const { RangePicker } = DatePicker;

const WeekCheckBox = () =>
  WeeksList.map(item => (
    <Checkbox key={item.value} value={item.value} style={{ lineHeight: '32px' }}>
      {item.name}
    </Checkbox>
  ));

const rangeConfig = {
  rules: [{ type: 'array', required: true, message: '请选择时间!' }],
};

const FormRuleSetting = forwardRef((props, ref) => {
  const { editData, supplierIdList } = props;
  const [form] = Form.useForm();
  const customer = useContext(ServiceContext);
  const [dateType, setDateType] = useState(1);

  // 判断是否有禁用的店铺 禁用店铺不显示
  const getIsInShops = arr => {
    const list = [];
    arr.forEach(item => {
      supplierIdList.some(s => +s.id === +item) && list.push(item);
    });
    return list;
  };

  useEffect(() => {
    if (customer.isEdit || customer.isUseCache) {
      if (!editData) return;
      const goodInfo = Object.assign({}, editData);
      if (goodInfo.shopIds) {
        const shopIds = getIsInShops(editData.shopIds);
        goodInfo.shopIds = shopIds;
      }
      console.log('goodInfo :>> ', goodInfo);
      if (goodInfo.validityPeriodType) {
        console.log('+goodInfo.validityPeriodType :>> ', +goodInfo.validityPeriodType);
        setDateType(+goodInfo.validityPeriodType);
      }
      form.setFieldsValue(goodInfo);
    }
  }, [customer.isEdit, customer.isUseCache, editData]);

  const onCheck = async () => {
    try {
      const { useTime, purchaseTime, ...values } = await form.validateFields();
      const params = {
        purchaseStartTime: formatTime(purchaseTime[0]),
        purchaseEndTime: formatTime(purchaseTime[1]),
        temp: 'serviceItem',
        ...values,
      };
      if (useTime && useTime.length === 2) {
        params.useStartTime = formatTime(useTime[0]);
        params.useEndTime = formatTime(useTime[1]);
      }
      return params;
    } catch (errorInfo) {
      return null;
    }
  };

  const onChangeDateType = e => {
    const v = +e.target.value;
    setDateType(v);
  };

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

  const nowDateTime = moment(moment().format('YYYY-MM-DD 00:00:00'));
  const nowDateTimeEnd = moment(moment().format('YYYY-MM-DD 23:59:59'));

  useImperativeHandle(ref, () => ({
    onCheck,
    reset: form.resetFields,
  }));
  return (
    <>
      <Form
        {...formItemLayout}
        form={form}
        name="register"
        initialValues={{
          // useTime: [], // 使用开始时间
          validityPeriodType: 1, // 有效期类型
          // useEndTime: '', // 使用结束时间
          purchaseTime: [], // 购买开始时间
          // purchaseEndTime: '2022-07-27 06', // 购买结束时间
          shopIds: [], // 适用门店列表
          unavailableDate: [], // 不可用日期
          useTimeDescription: '', // 使用时间
          useMethod: '', // 使用方法
          ruleDescription: '', // 规则说明
          applyScope: '', // 适用范围
          tips: '', // 温馨提示
        }}
        scrollToFirstError
        onValuesChange={getFormValues}
      >
        <Form.Item name="purchaseTime" label="购买时间" {...rangeConfig}>
          <RangePicker
            format="YYYY-MM-DD HH:mm:ss"
            defaultPickerValue={[nowDateTime, nowDateTimeEnd]}
          />
        </Form.Item>
        <Form.Item
          name="validityPeriodType"
          label="有效期类型"
          rules={[{ required: true, message: '请选择有效期类型!' }]}
        >
          <Radio.Group onChange={onChangeDateType}>
            <Radio value={1}>固定日期</Radio>
            <Radio value={2} disabled>
              指定范围
            </Radio>
          </Radio.Group>
        </Form.Item>
        {dateType === 1 ? (
          <Form.Item name="useTime" label="有效期" {...rangeConfig}>
            <RangePicker
              format="YYYY-MM-DD HH:mm:ss"
              defaultPickerValue={[nowDateTime, nowDateTimeEnd]}
            />
          </Form.Item>
        ) : (
          <Form.Item
            name="validityPeriodDays"
            label="有效期天数"
            rules={[{ required: true, message: '请输入有效期天数!' }]}
          >
            <InputNumber min={1} max={36000} />
          </Form.Item>
        )}
        <Form.Item
          name="shopIds"
          label="适用门店"
          rules={[{ required: true, message: '请选择适用门店!', type: 'array' }]}
        >
          <Select
            mode="multiple"
            placeholder="请选择适用门店"
            showSearch
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {(supplierIdList || []).map(item => (
              <Option value={+item.id} key={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="unavailableDate"
          label="不可用日期"
          rules={[{ required: false, message: '请选择不可用日期!', type: 'array' }]}
        >
          <Checkbox.Group>{WeekCheckBox()}</Checkbox.Group>
        </Form.Item>
        <Form.Item
          name="useTimeDescription"
          label="使用时间"
          rules={[{ required: false, message: '请输入描述！' }]}
        >
          <Input.TextArea
            showCount
            maxLength={100}
            placeholder="例如：11:00-12:00;14:00-17:00可用，其他时间不可用"
          />
        </Form.Item>
        <Form.Item
          name="useMethod"
          label="使用方法"
          rules={[{ required: true, message: '请输使用方法，200字以内！' }]}
        >
          <Input.TextArea showCount maxLength={200} placeholder="请输使用方法，200字以内！" />
        </Form.Item>
        <Form.Item
          name="ruleDescription"
          label="规则说明"
          rules={[{ required: true, message: '请输规则说明，200字以内！' }]}
        >
          <Input.TextArea showCount maxLength={200} placeholder="请输规则说明，200字以内！" />
        </Form.Item>
        <Form.Item
          name="applyScope"
          label="适用范围"
          rules={[{ required: false, message: '请输入适用范围' }]}
        >
          <Input.TextArea
            showCount
            maxLength={50}
            placeholder="请输入适用范围，50字以内 例如：全场通用"
          />
        </Form.Item>
        <Form.Item
          name="tips"
          label="温馨提示"
          rules={[{ required: false, message: '请输入温馨提示' }]}
        >
          <Input.TextArea
            showCount
            rows={5}
            maxLength={200}
            placeholder="请输入温馨提示，200字以内&#13;&#10;例如：&#13;&#10;*不兑零，不找零&#13;&#10;*无需预约，消费高峰期可能需要等位&#13;&#10;*商家提供免费WIFI"
          />
        </Form.Item>
      </Form>
    </>
  );
});

export default FormRuleSetting;
