import React, { useEffect, useState, useRef } from 'react';
import { Modal, Form, Select, InputNumber, Input } from 'antd';
const { Option } = Select;

function SearchModal(props) {
  const { onCancel, onOk, config = [], visible, form } = props;

  const handleOk = () => {
    form.validateFields((error, values) => {
      if (error) return;
      let data = Object.keys(values)
        .map(k => {
          let item = {
            k,
            v: values[k].v,
            op: values[k].op,
          };
          if (!item.op) delete item.op;
          return item;
        })
        .filter(item => item.v);
      onOk(data);
    });
  };

  const handleCancel = () => {
    onCancel && onCancel();
  };

  const renderFormItem = item => {
    let dom,
      option = [],
      rules = [];

    switch (item.query_type) {
      case 'select':
        option = item.query_option.split(',');
        dom = (
          <Select allowClear>
            {option.map(item => (
              <Option key={item}>{item}</Option>
            ))}
          </Select>
        );
        break;
      case 'multi-select':
        option = item.query_option.split(',');
        dom = (
          <Select allowClear mode="multiple">
            {option.map(item => (
              <Option key={item}>{item}</Option>
            ))}
          </Select>
        );
      case 'input':
        if (item.type == 'string') dom = <Input />;
        else {
          let addonBefore = form.getFieldDecorator(`${item.en_name}.op`, {
            initialValue: '=',
          })(
            <Select style={{ width: 200 }}>
              <Option value="=">等于</Option>
              <Option value=">">大于</Option>
              <Option value=">=">大于等于</Option>
              <Option value="<">小于</Option>
              <Option value="<=">小于等于</Option>
            </Select>
          );
          rules = [
            {
              validator: (rule, value, callback) => {
                if (value && isNaN(value)) callback('请输入数字!');
                callback();
              },
            },
          ];
          dom = <Input addonBefore={addonBefore} />;
        }
        break;
    }

    return form.getFieldDecorator(`${item.en_name}.v`, {
      rules,
    })(dom);
  };

  return (
    <Modal
      title={'高级搜索'}
      width={'95%'}
      visible={visible}
      onCancel={handleCancel}
      onOk={handleOk}
    >
      <Form labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} layout="horizontal">
        {config
          .filter(item => item.is_query)
          .map(item => (
            <Form.Item key={item.en_name} label={item.cn_name}>
              {renderFormItem(item)}
            </Form.Item>
          ))}
      </Form>
    </Modal>
  );
}

export default Form.create()(SearchModal);
