import { Select, Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import FormItem from '../FormItem/FormItem'
import { getItemProps } from "../../utils"
import http from '../../utils/request'
import schema from "./schema"
import { debounce } from 'lodash';

const { Option } = Select;
const SelectWapper = (item: any) => {
  const data: any = getItemProps(schema, item)
  const [Options, setOptions] = useState<any>([])
  const { first = false, form = undefined, FormItemProps, componentType, ControlProps, request, ControlFieldNames, options, defaultText } = data
  const [fetching, setFetching] = useState(false);
  const { placeholder } = ControlProps
  const { label } = FormItemProps
  const { labelName, valueName, } = ControlFieldNames

  const getRequest = async () => {
    // const res = await http[request.type](request.url, request?.params)
    const res1 = await http(request.url, {
      method: request.type,
      data: {
        ...request?.params
      }
    })
    const res = {
      data: res1
    }
    if (res) {
      let data: any = res
      if (request.getData) {
        for (const i of request.getData) {
          data = data?.[i]
        }
      }
      if (data) {
        if (!(data instanceof Array)) {
          data = [data]
        }
        if (!defaultText && first) {
          const json = {}
          json[FormItemProps?.name] = data?.[0]?.[valueName]
          form.setFieldsValue(json);
        }
        setOptions(data);
      } else {
        setOptions([])
      }
      // debugger
      if (defaultText) {
        let status = 0;
        for (const i of data) {
          if (i[valueName] === defaultText) {
            status = 1;
            break;
          }
        }
        (window as any)[valueName] = status
        if (status === 0) {
          const json = {}
          json[FormItemProps?.name] = defaultText
          form.setFieldsValue(json);
        }
      }

    }
    return res
  }

  useEffect(() => {
    !ControlProps?.showSearch && request?.url ? getRequest() : setOptions(options)
  }, [defaultText])

  const onSearch = () => {
    if (ControlProps?.showSearch) {
      return {
        onSearch: debounce(async (e: any) => {
          if (e) {
            setFetching(true);
            request.params.replace('null', e)
            let params = request.params.replace('null', `"${e}"`)
            params = JSON.parse(params)
            let data: any = await http[request.type](request.url, params)
            setFetching(false);
            if (request.getData) {
              for (const i of request.getData) {
                data = data?.[i]
              }
            }
            if (data) {
              if (data instanceof Array) {
                setOptions(data);
              } else {
                setOptions([data]);
              }
            }
          }
        }, 800),
        notFoundContent: fetching ? <Spin size="small" /> : null
      }
    } else {
      return {}
    }
  }

  const SelectBox = () => {
    return <Select
      className='kx_antd_select'
      {...onSearch()}
      {...ControlProps}
      placeholder={`${placeholder || '请选择' + label}`}
    >
      {Options?.map((i: any, index: any) => {
        return <Option key={index} value={valueName === "*" ? JSON.stringify(i) : i?.[valueName]}>
          {i?.[labelName]}
        </Option>
      })}
    </Select>
  }

  return componentType === 'FormItem' ? <FormItem {...FormItemProps}>
    {SelectBox()}
  </FormItem> : SelectBox()
};

export default SelectWapper;
