import React, { useEffect, useState, forwardRef, useImperativeHandle, Ref, useRef } from 'react';

import { Button } from 'antd';
import { useRouter } from 'next/router';

import api, { FilterOptionResp, TypesResp, InfoList } from './api';
import RegionItem from './compoents/regionItem';
// eslint-disable-next-line import/no-cycle
import ResultItem from './compoents/resultItem';
import TypeInfo from './compoents/typeInfo';
import styles from './index.module.scss';

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 categorySecondRef = useRef<any>();
  const router = useRouter();
  useImperativeHandle(ref, () => ({
    clearRouter,
  }));
  const [result, setResult] = useState<FilterResult>({});

  const onChange = (item: FilterOptionResp, type: string) => {
    clearRouter();
    const 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();
    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?.forEach((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>();
  const [currentDicIndex, setCurrentDicIndex] = useState<number>(-1);
  const [currentItemIndex, setCurrentItemIndex] = useState<number>(-1); // 当前分类移入的下标
  const [categoryObj, setCategoryObj] = useState<FilterOptionResp>();

  // 分类移入
  const categoryMouseEnter = (item: FilterOptionResp) => {
    if (item.children) {
      setCategoryObj(item);
      categorySecondRef.current.style.display = 'block';
      if (typeInfo) {
        const index: number = typeInfo.findIndex((v) =>
          v.categoriesInfoListDTO.some((i) => i.id === item.id),
        );
        setCurrentDicIndex(index);
        categorySecondRef.current.style.top = `${(index + 1) * 26}px`;
      }
    } else {
      categorySecondRef.current.style.display = 'none';
    }
  };
  // 分类移出
  const categoryMouseLeave = () => {
    categorySecondRef.current.style.display = 'none';
  };
  // 二级菜单移入
  const categorySecondMouseEnter = () => {
    if (currentItemIndex !== -1) {
      categorySecondRef.current.style.display = 'block';
    }
  };
  // 二级菜单移出
  const onMouseLeave = () => {
    setCurrentItemIndex(-1);
    categorySecondRef.current.style.display = 'none';
  };
  // 修改移入的下标
  const changeCurrentItemIndex = (index: number) => {
    setCurrentItemIndex(index);
  };
  // 二级分类选中
  const categorySecondSelect = (v: FilterOptionResp) => {
    const obj = JSON.parse(JSON.stringify(categoryObj));
    if (obj?.children) {
      obj.children = obj.children.filter((item: FilterOptionResp) => item.id === v.id);
      obj.name += `/${v.name}`;
      onChange(obj, 'categoryId');
    }
  };
  useEffect(() => {
    if (routerList.indexOf(router.pathname) > -1) {
      (async () => {
        const res = await api.infoByType({
          type: routerList.indexOf(router.pathname) + 1,
        });
        setTypeInfo(res.result);
        // 首页跳转自定筛选选中
        const 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} onMouseLeave={onMouseLeave}>
        <div
          className={styles.filterCategorySecond}
          ref={categorySecondRef}
          onMouseLeave={onMouseLeave}
          onMouseEnter={categorySecondMouseEnter}
        >
          {categoryObj?.children &&
            categoryObj?.children.map((v) => (
              <Button type='link' key={v.id} onClick={() => categorySecondSelect(v)}>
                {v.name}
              </Button>
            ))}
        </div>
        {typeInfo?.length &&
          typeInfo?.map((item, index) => (
            <TypeInfo
              key={item.directoryId}
              typeName={item.name}
              dataValue={item.categoriesInfoListDTO}
              onChange={(e: FilterOptionResp) => onChange(e, 'categoryId')}
              categoryMouseEnter={categoryMouseEnter}
              changeCurrentItemIndex={changeCurrentItemIndex}
              currentItemIndex={currentDicIndex === index ? currentItemIndex : -1}
              categoryMouseLeave={categoryMouseLeave}
            ></TypeInfo>
          ))}
        {props.showResultItem && <ResultItem data={result} onDel={onDel}></ResultItem>}
      </div>
    </>
  );
};

export default forwardRef(Filter);
