import * as React from 'react';
import { useEffect } from 'react';
import { FastCascader } from 'components/ui';
import { Component } from 'components/types';
import transformer from 'utils/transformer';
import { isNumber } from 'utils/isType';
import useOptions from '../hooks/useOptions';
import { FormTypes } from '../../types';

const OPTION_ITEM_ALL = { label: '全部', value: '' };

function Select(props: FormTypes.FormItem.FormAtomicSelectProps) {
  const {
    config,
    values,
    validateTrigger,
  } = props;

  const {
    key,
    type,
    style,
    placeholder,
    notModify,
    isChangeOnSelect,
    searchable = false,
    notAll,
    data: defaultOptions,
    interact,
    resFunc,
  } = config;
  let localOptions: FormTypes.FormItem.OptionItem[] = [];

  if (!notAll) localOptions = [OPTION_ITEM_ALL];
  if (defaultOptions) localOptions = [...localOptions, ...defaultOptions];

  // states
  const {
    ajaxOptions,
    setOptions,
  } = useOptions(props);

  // handlers
  const handleSearch = (value: string) => {
    if (searchable) {
      setOptions({ [key]: value });
    }
  };

  // effects
  const deps = interact && interact.type === Component.Business.ResultType.fetch
    ? [values[interact.triggerKey as string]] : [];

  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(
    setOptions,
    [
      // setOptions,
      ...deps,
    ],
  );

  return (type === 'multcascader' ? (
    <FastCascader
      changeOnSelect={isChangeOnSelect}
      defaultValue={values[key] || []}
      style={{ ...style, minWidth: '100px' }}
      multiple
      placeholder={placeholder}
      options={[...localOptions, ...ajaxOptions]}
      onSearch={handleSearch}
      showSearch
      disabled={notModify}
      // eslint-disable-next-line react/destructuring-assignment
      onChange={(val: any[]) => {
        // eslint-disable-next-line react/destructuring-assignment
        props[validateTrigger](val.map((item: any) => {
          if (isNumber(item[item.length - 1])) return item[item.length - 1];
          return +`${item[item.length - 1]}`.substring(2);
        }));
      }}
    />
  ) : (
    <FastCascader
      changeOnSelect={isChangeOnSelect}
      style={{ ...style, minWidth: '100px' }}
      value={transformer[resFunc || 'default'](values[key])}
      placeholder={placeholder}
      options={[...localOptions, ...ajaxOptions]}
      onSearch={handleSearch}
      showSearch
      disabled={notModify}
      onChange={(val: any[]) => {
        // eslint-disable-next-line react/destructuring-assignment
        props[validateTrigger](+`${val[val.length - 1]}`);
      }}
    />
  ));
}

export default Select;
