import CategoryItem from './compoents/categoryItem'
import Category from './compoents/category'
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 BrandItem from './compoents/brandItem'
import ModelItem from './compoents/modelItem'
import PartItem from './compoents/partItem'
import QualityItem from './compoents/qualityItem'
import Industry from './compoents/industry'
import AppType from './compoents/appType'
import DeviceBrand from './compoents/deviceBrand'
import DeviceModel from './compoents/deviceModel'
import TypeInfo from './compoents/typeInfo'
import api, { TypesResp, InfoList } from './api'

export type AdapterResult = {
  // brandId?: number
  // districtId?: number
  // modelId?: number
  // partsId?: number
  // productCategoryId?: number
  // qualityId?: number
  // industryId?: number
  // appTypeId?: number
  categoryId?: any[]
  provinceId?: number
}

export type FilterResult = {
  // region?: RegionResp
  // brand?: FilterOptionResp
  // category?: FilterOptionResp
  // part?: FilterOptionResp
  // model?: FilterOptionResp
  // quality?: FilterOptionResp
  // industryId?: FilterOptionResp
  // appTypeId?: FilterOptionResp
  categoryId?: InfoList[]
  provinceId?: FilterOptionResp
}

type itemType =
  | '类目'
  | '地域'
  | '品牌'
  | '部件'
  | '型号'
  | '成色'
  | '行业'
  | '应用'
  | '设备品牌'
  | '设备型号'
  | '设备类目'

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

// const idArr = [
//   'brandId',
//   'categoryId',
//   'modelId',
//   'partsId',
//   'productCategoryId',
//   'qualityId',
//   'industryId',
//   'appTypeId',
// ]
// const nameArr: any = {
//   brandId: {
//     type: 'brandId',
//     typeObj: 'brand',
//     typeName: '品牌：',
//   },
//   // districtId: {
//   //   type:"districtId",
//   //   typeObj:"region",
//   //   typeName:"地域：",
//   // },
//   modelId: {
//     type: 'modelId',
//     typeObj: 'model',
//     typeName: '型号：',
//   },
//   partsId: {
//     type: 'partsId',
//     typeObj: 'part',
//     typeName: '部件：',
//   },
//   productCategoryId: {
//     type: 'productCategoryId',
//     typeObj: 'category',
//     typeName: '类目：',
//   },
//   qualityId: {
//     type: 'qualityId',
//     typeObj: 'quality',
//     typeName: '成色：',
//   },
//   industryId: {
//     type: 'industryId',
//     typeObj: 'industryId',
//     typeName: '行业：',
//   },
//   appTypeId: {
//     type: 'appTypeId',
//     typeObj: 'appTypeId',
//     typeName: '应用：',
//   },
//   categoryId: {
//     type: 'categoryId',
//     typeObj: 'categoryId',
//     typeName: '类目：',
//   },
// }

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, {
      // brandId: result.brand?.id,
      // districtId: result.region?.id,
      // modelId: result.model?.id,
      // partsId: result.part?.id,
      // productCategoryId: result.category?.id,
      // qualityId: result.quality?.id,
      // industryId: result.industryId?.id,
      // appTypeId: result.appTypeId?.id,
      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}>
        {/* {props.types.includes('品牌') && (
          <BrandItem
            onChange={(item: FilterOptionResp) => onChange(item, 'brand')}
          ></BrandItem>
        )}
        {props.types.includes('设备品牌') && (
          <DeviceBrand
            onChange={(item: FilterOptionResp) => onChange(item, 'brand')}
          ></DeviceBrand>
        )}
        {props.types.includes('类目') && (
          <CategoryItem
            onChange={(item: FilterOptionResp) => onChange(item, 'category')}
          ></CategoryItem>
        )}
        {props.types.includes('设备类目') && (
          <Category
            onChange={(item: FilterOptionResp) => onChange(item, 'categoryId')}
          ></Category>
        )}
        {props.types.includes('部件') && (
          <PartItem
            onChange={(item: FilterOptionResp) => onChange(item, 'part')}
          ></PartItem>
        )}
        {props.types.includes('型号') && (
          <ModelItem
            onChange={(item: FilterOptionResp) => onChange(item, 'model')}
          ></ModelItem>
        )}
        {props.types.includes('设备型号') && (
          <DeviceModel
            onChange={(item: FilterOptionResp) => onChange(item, 'model')}
          ></DeviceModel>
        )}
        {props.types.includes('成色') && (
          <QualityItem
            onChange={(item: FilterOptionResp) => onChange(item, 'quality')}
          ></QualityItem>
        )}
        {props.types.includes('行业') && (
          <Industry
            onChange={(item: FilterOptionResp) => onChange(item, 'industryId')}
          ></Industry>
        )}
        {props.types.includes('应用') && (
          <AppType
            onChange={(item: FilterOptionResp) => onChange(item, 'appTypeId')}
          ></AppType>
        )} */}

        {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)
