import React, { useState } from 'react';
import { Form, Input, Select, DatePicker, Button, Space } from 'antd';
import moment from 'moment';
import style from './index.less';

const { Option } = Select;
const { RangePicker } = DatePicker;
const SEARCH_TYPE = {
  SELECT: 'select',
  RANGE_PICKER: 'range_picker',
  INPUT: 'input',
  DATE_PICKER: 'date_picker',
};
const FormSearch = props => {
  const {
    width = '100%',
    form,
    initialValues = {},
    onFinish = () => {},
    formConfig,
    formOptions,
    btnConfig,
  } = props;

  const FormItemBox = ({ bindKey, label, column, children, afterRender }) => {
    const columnValue = column;
    // if (afterRender) {
    //   columnValue = '';
    // }
    return (
      <Form.Item
        className={style['custom-form-item']}
        column={columnValue}
        name={bindKey}
        label={label}
      >
        {children}
      </Form.Item>
    );
  };

  // 下拉框类型
  const FormItemSelect = config => {
    const {
      bindKey,
      options: configOptions = [],
      originOptions = {},
      afterRender = null,
      afterOptions = {},
      column,
    } = config;

    const attrs = { placeholder: $t('select'), ...originOptions };
    // 提取公共部分
    const BaseSelectElement = () => (
      <FormItemBox {...config}>
        <Select name={bindKey} className={style['form-item-tag']} {...attrs}>
          {configOptions.map(option => (
            <Option key={option.value} value={option.value}>
              {option.name}
            </Option>
          ))}
        </Select>
      </FormItemBox>
    );

    if (afterRender) {
      return (
        <>
          {/* // <div className={style['custom-form-item-group']}> */}
          <BaseSelectElement />
          <FormItemBox column={column} {...afterOptions}>
            {afterRender()}
          </FormItemBox>
          {/* // </div> */}
        </>
      );
    }

    return <BaseSelectElement />;
  };

  // 选择日期范围类型
  const FormItemRangePicker = config => {
    const { originOptions = {}, bindKey, limit } = config;
    const attrs = { placeholder: [$t('start.date'), $t('end.date')], ...originOptions };

    // 自动截取日期限制的范围
    const onOpenChange = open => {
      if (!open) {
        if (limit) {
          const { rangeNum, rangeUnit } = limit;
          const [date1, date2] = form.getFieldValue(bindKey);
          const diffNum = date2.diff(date1, rangeUnit);
          const unitMapping = {
            months: 'month',
          };
          if (diffNum >= rangeNum) {
            setTimeout(() => {
              form.setFieldsValue({
                [bindKey]: [moment(date1), moment(date1).add(rangeNum, unitMapping[rangeUnit])],
              });
            });
          }
        }
      }
    };

    return (
      <FormItemBox {...config}>
        <RangePicker className={style['form-item-tag']} onOpenChange={onOpenChange} {...attrs} />
      </FormItemBox>
    );
  };

  // 选择日期
  const FormItemDatePicker = config => {
    const { originOptions = {} } = config;
    const attrs = { placeholder: $t('select.date'), ...originOptions };
    return (
      <FormItemBox {...config}>
        <DatePicker className={style['form-item-tag']} {...attrs} />
      </FormItemBox>
    );
  };

  // 多级联动

  // 输入框类型
  const FormItemInput = config => {
    const { originOptions = {} } = config;
    const attrs = { placeholder: $t('input.required'), allowClear: true, ...originOptions };
    return (
      <FormItemBox {...config}>
        <Input className={style['form-item-tag']} {...attrs} />
      </FormItemBox>
    );
  };

  // 表单内容元素
  const FormItemElement = () =>
    formConfig.map(config => {
      const { type } = config;
      switch (type) {
        case SEARCH_TYPE.SELECT:
          return <FormItemSelect key={config.bindKey} {...config} />;
        case SEARCH_TYPE.RANGE_PICKER:
          return <FormItemRangePicker key={config.bindKey} {...config} />;
        case SEARCH_TYPE.INPUT:
          return <FormItemInput key={config.bindKey} {...config} />;
        case SEARCH_TYPE.DATE_PICKER:
          return <FormItemDatePicker key={config.bindKey} {...config} />;
        default:
          return <></>;
      }
    });

  /**
   * @module 按钮操作
   */
  const FormItemButton = () => (
    <Space size={10}>
      {btnConfig.map(config => {
        const { label, onClick = () => {}, type = 'primary', clickType = 'search' } = config;
        const htmlType = clickType === 'reset' ? 'reset' : 'submit';
        const callback = () => {
          setTimeout(() => {
            onClick({ type: clickType, params: form.getFieldValue() });
          });
        };
        return (
          <Button key={clickType} type={type} htmlType={htmlType} onClick={callback}>
            {label}
          </Button>
        );
      })}
    </Space>
  );

  return (
    <div className={style['form-search']}>
      <Form
        style={{ width }}
        layout="inline"
        form={form}
        initialValues={initialValues}
        onFinish={onFinish}
        {...formOptions}
      >
        <FormItemElement></FormItemElement>
        <Form.Item>
          <FormItemButton></FormItemButton>
        </Form.Item>
      </Form>
    </div>
  );
};

export { FormSearch, SEARCH_TYPE };
