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";

export type AdapterResult = {
  brandId?: number;
  districtId?: number;
  modelId?: number;
  partsId?: number;
  productCategoryId?: number;
  qualityId?: number;
  industryId?: number;
  appTypeId?: number;
  categoryId?: number;
};

export type FilterResult = {
  region?: RegionResp;
  brand?: FilterOptionResp;
  category?: FilterOptionResp;
  part?: FilterOptionResp;
  model?: FilterOptionResp;
  quality?: FilterOptionResp;
  industryId?: FilterOptionResp;
  appTypeId?: FilterOptionResp;
  categoryId?: 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, () => ({
    idArr: idArr,
    clearRouter: clearRouter,
  }));
  const [result, setResult] = useState<FilterResult>({});

  const onChange = (item: FilterOptionResp, type: string) => {
    clearRouter();
    let data: { [key: string]: FilterOptionResp } = {};
    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?.id,
    });
  }, [result]);

  useEffect(() => {
    let queryVal = JSON.parse(JSON.stringify(router.query));
    if (Object.keys(router.query).length) {
      for (const key in queryVal) {
        if (idArr.includes(key)) {
          onChange(
            { id: queryVal[key], name: nameArr[key].typeName + queryVal.name },
            nameArr[key].typeObj
          );
        }
      }
    }
  }, [router]);

  const clearRouter = () => {
    if (Object.keys(router.query).length) {
      router.query = {};
      router.replace(router.pathname);
    }
  };
  const onDel = (key: string) => {
    clearRouter();
    //@ts-ignore
    delete result[key];
    setResult({
      ...result,
    });
  };
  return (
    <>
      {props.types.includes("地域") && (
        <div
          className={styles.filterWrap}
          style={{
            marginBottom: 10,
          }}
        >
          <RegionItem
            onChange={(item: FilterOptionResp) => onChange(item, "region")}
          ></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>
        )}

        {props.showResultItem && (
          <ResultItem data={result} onDel={onDel}></ResultItem>
        )}
      </div>
    </>
  );
};

export default forwardRef(Filter);
