
import { FilterOptionResp, RegionResp } from './api'
import ResultItem from './compoents/resultItem'
import RegionItem from './compoents/regionItem'
import styles from './index.module.scss'
import React, {
  useEffect,
  useState,
  forwardRef,
  useImperativeHandle,
  Ref,
} from 'react'
import { useRouter } from 'next/router'
import TypeInfo from './compoents/typeInfo'
import api, { TypesResp, InfoList } from './api'

export type AdapterResult = {
  categoryId?: any[]
  provinceId?: number
}

export type FilterResult = {
  categoryId?: InfoList[]
  provinceId?: FilterOptionResp
}


type Props = {
  types: string[] //需要包含的筛选条件项
  showResultItem: Boolean //显示结果栏
  onChange: (
    filterResult: FilterResult,
    adapterFilterResult: AdapterResult //适配器,直接用于接口请求
  ) => void //筛选条件更改事件
}

const Filter = (props: Props, ref: Ref<any>) => {
  const router = useRouter()
  useImperativeHandle(ref, () => ({
    clearRouter: clearRouter,
  }))
  const [result, setResult] = useState<FilterResult>({})

  const onChange = (item: FilterOptionResp, type: string) => {
    clearRouter()
    let data: { [key: string]: FilterOptionResp[] | FilterOptionResp } = {}
    if (type === 'categoryId') {
      if (result.categoryId) {
        data[type] = [...result.categoryId, item]
        const map = new Map()
        //去重
        data[type] = (data[type] as InfoList[]).filter(
          (v) => !map.has(v.id) && map.set(v.id, 1)
        )
      } else {
        data[type] = [item]
      }
    } else {
      data[type] = item
    }
    setResult({ ...result, ...data })
  }

  useEffect(() => {
    props.onChange(result, {
      categoryId: result.categoryId,
      provinceId: result.provinceId?.id,
    })
  }, [result])

  const clearRouter = () => {
    if (Object.keys(router.query).length) {
      router.query = {}
      router.replace(router.pathname)
    }
  }
  const onDel = (key: string | number) => {
    clearRouter()
    console.log(key)

    if (Object.prototype.toString.call(key) === '[object String]') {
      //@ts-ignore
      delete result[key]
    } else {
      if (result.categoryId?.length! === 1) {
        result.categoryId = undefined
      } else if (result.categoryId?.length! >= 2) {
        result.categoryId?.map((item, index) => {
          if (item.id === key) {
            result.categoryId?.splice(index, 1)
          }
        })
      }
    }
    setResult({
      ...result,
    })
  }
  const routerList = [
    '/jobServices',
    '/equipmentLeasing',
    '/flyingHandService',
    '/mall',
  ]
  const [typeInfo, setTypeInfo] = useState<Array<TypesResp> | null>()
  useEffect(() => {
    if (routerList.indexOf(router.pathname) > -1) {
      ;(async () => {
        const res = await api.infoByType({
          type: routerList.indexOf(router.pathname) + 1,
        })
        setTypeInfo(res.result)
        //首页跳转自定筛选选中
        let queryVal = JSON.parse(JSON.stringify(router.query))
        if (Object.keys(router.query).length) {
          //获取类型的id
          const idOfType = res.result
            ?.map((item) => item.categoriesInfoListDTO)
            .flat()
            .filter(
              (item) => item && item.id === Number(queryVal['categoryId'])
            )[0]?.directoryId
          //获取类型的名称然后拼接
          const TypeName = res.result?.filter(
            (item) => item.directoryId === idOfType
          )[0]?.name

          onChange(
            {
              id: Number(queryVal['categoryId']),
              name: `${
                TypeName ? TypeName + '：' + queryVal.name : queryVal.name
              }`,
            },
            'categoryId'
          )
        }
      })()
    }
  }, [router])

  return (
    <>
      {props.types.includes('地域') && (
        <div
          className={styles.filterWrap}
          style={{
            marginBottom: 10,
          }}
        >
          <RegionItem
            onChange={(item: FilterOptionResp) => onChange(item, 'provinceId')}
          ></RegionItem>
        </div>
      )}
      <div className={styles.filterWrap}>
        {typeInfo?.length &&
          typeInfo?.map((item) => (
            <TypeInfo
              key={item.directoryId}
              typeName={item.name}
              dataValue={item.categoriesInfoListDTO}
              onChange={(item: FilterOptionResp) =>
                onChange(item, 'categoryId')
              }
            ></TypeInfo>
          ))}
        {props.showResultItem && (
          <ResultItem data={result} onDel={onDel}></ResultItem>
        )}
      </div>
    </>
  )
}

export default forwardRef(Filter)
