import React, { useState, useEffect } from 'react';
import { Modal, Radio, Form, TimePicker, Checkbox } from 'antd';
import { MinusSquareOutlined, PlusSquareOutlined } from '@ant-design/icons';
import moment from 'moment';
import { deepClone } from '@/utils/utils';
import { saleWeeks } from '../../staticdata';
import styles from '../../style.less';

const WeekTime = options => {
  const [form] = Form.useForm();
  const [type, setType] = useState(0);

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };
  const formItemLayoutWithOutLabel = {
    wrapperCol: {
      xs: { span: 22, offset: 0 },
      sm: { span: 16, offset: 6 },
    },
  };

  const onChangeType = ({ target: { value } }) => {
    setType(value);
  };

  const radioOptions = [{ label: '全时段', value: 0 }, { label: '自定义售卖时间', value: 1 }];

  const handleCancel = () => {
    options.cancel(false);
  };
  const handleOk = async () => {
    const params = await form.validateFields();
    // const params = values;
    if (params.saleTimes && params.saleTimes.length) {
      params.saleTimes = params.saleTimes.map(item => ({
        startTime: moment(item[0]).format('HH:mm'),
        endTime: moment(item[1]).format('HH:mm'),
      }));
    }

    options.confirm({
      type: 4,
      ...params,
    });
  };

  const onTimeValidator = (rule, value, callback) => {
    if (value && value.length === 2) {
      if (moment(value[0]).format('HH:mm') === moment(value[1]).format('HH:mm')) {
        callback(new Error('请输入大于0的数字'));
      } else {
        callback();
      }
    } else {
      callback();
    }
  };

  const initialValues = Object.assign(
    {
      saleTimeType: 0,
      saleDates: [],
      saleTimes: [[]],
    },
    options.initialValues,
  );

  useEffect(() => {
    options.visible && setType(0);
  }, [options.visible]);

  return (
    <Modal
      visible={options.visible}
      title="售卖时间"
      onOk={handleOk}
      confirmLoading={options.loading}
      maskClosable={false}
      keyboard={false}
      destroyOnClose
      onCancel={handleCancel}
    >
      <Form
        name="basic"
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        initialValues={initialValues}
        autoComplete="off"
      >
        <Form.Item
          label="售卖时间段类型"
          name="saleTimeType"
          rules={[{ required: true, message: '请选择售卖时间段类型!' }]}
        >
          <Radio.Group
            options={radioOptions}
            onChange={onChangeType}
            value={type}
            optionType="button"
            buttonStyle="solid"
          />
        </Form.Item>
        {type === 1 ? (
          <>
            <Form.Item
              label="售卖日期"
              name="saleDates"
              rules={[{ required: true, message: '请选择售卖日期!' }]}
            >
              <Checkbox.Group options={saleWeeks} />
            </Form.Item>
            <Form.List
              label="售卖时间"
              name="saleTimes"
              rules={[
                {
                  validator: async (_, saleTimes) => {
                    if (!saleTimes || saleTimes.length < 1) {
                      return Promise.reject(new Error('请选择售卖时间!'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              {(fields, { add, remove }) => (
                <>
                  {fields.map((field, index) => (
                    <Form.Item
                      label={index === 0 ? '售卖日期' : ''}
                      {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                      required
                      key={field.key}
                    >
                      <Form.Item
                        {...field}
                        validateTrigger={['onChange', 'onBlur']}
                        rules={[
                          {
                            required: true,
                            message: '请选择售卖时间',
                          },
                          {
                            validator: onTimeValidator,
                            message: '结束时间不能和开始时间相同',
                          },
                        ]}
                        noStyle
                      >
                        <TimePicker.RangePicker format="HH:mm" minuteStep={30} />
                      </Form.Item>
                      {index > 0 ? (
                        <MinusSquareOutlined
                          className={[styles['week-time-box--icon'], styles.error]}
                          onClick={() => remove(field.name)}
                        />
                      ) : (
                        <PlusSquareOutlined
                          className={[styles['week-time-box--icon'], styles.primary]}
                          onClick={() => add()}
                        />
                      )}
                    </Form.Item>
                  ))}
                </>
              )}
            </Form.List>
          </>
        ) : (
          ''
        )}
      </Form>
    </Modal>
  );
};

export default WeekTime;
