import * as React from 'react';
import { FastForm, FastDivider } from 'components/ui';
import FormItem from 'components/business/Form/FormItem';
import Input from 'components/business/Form/FormItem/Input';
import Select from 'components/business/Form/FormItem/Select';
import DatePicker from 'components/business/Form/FormItem/DatePicker';
import TreeSelect from 'components/business/Form/FormItem/TreeSelect';
import Cascader from 'components/business/Form/FormItem/Cascader';
import DateRangePicker from 'components/business/Form/FormItem/DateRangePicker';
import useSearch from './useSearch';
import { SearchProps } from './types';

const COMP_MAP = {
  input: Input,
  multinput: Input,
  select: Select,
  multselect: Select,
  datepicker: DatePicker,
  treeselect: TreeSelect,
  multtreeselect: TreeSelect,
  cascader: Cascader,
  multcascader: Cascader,
  daterangepicker: DateRangePicker,
};

function Search(props: SearchProps) {
  const {
    formInstance,
    initialValues,
    formList,
    actionList,
    values,
    dict,
    setValues,
    createActionBtns,
  } = useSearch(props);

  const createSonField = () => {
    const result = [];
    for (let i = 0; i < formList.length; i += 1) {
      const item = {
        ...formList[i],
      };
      const COMP = COMP_MAP[item.type];
      if (item.type === 'span') {
        result.push(
          <FormItem layout="inline" key={item.key} config={item} values={values}>
            <span>{values[item.key] || ''}</span>
          </FormItem>,
        );
      } else if (!COMP) {
        result.push(
          <FormItem layout="inline" key={item.key} config={item} values={values}>
            <div>这里是错误类型</div>
          </FormItem>,
        );
      } else {
        result.push(<FormItem layout="inline" key={item.key} config={item} values={values} dict={dict}><COMP /></FormItem>);
      }
    }

    return result;
  };

  return (
    <div className="flex">
      <FastForm
        className="flex-grow"
        layout="inline"
        form={formInstance}
        onValuesChange={(_value: any, _values: any) => {
          setValues(_values);
        }}
        initialValues={initialValues}
      >
        {createSonField()}
      </FastForm>
      {actionList.length ? (
        <div className="flex align-items-center">
          <FastDivider type="vertical" style={{ height: '100%', marginRight: '20px' }} />
          {createActionBtns(actionList)}
        </div>
      ) : null}
    </div>
  );
}

export default Search;
