import React, { useEffect, useState } from 'react';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { useRouter } from 'next/router';
import styled from 'styled-components';

// 分类列表类型
export type CategoryType = {
  value: number;
  label: string;
  children?: CategoryType;
}[];

const CategorySelectView: React.FC<{
  list: CategoryType;
  onMain?: (arr: number) => void;
  onSecond?: (arr: number[]) => void;
  onSelect?: ({ main, second }: { main?: number; second?: number[] }) => void;
  isMultiple?: boolean;
  allText?: string;
}> = ({ list, onMain, onSecond, onSelect, allText, isMultiple }) => {
  CategorySelectView.defaultProps = { allText: '全部商品', isMultiple: true };
  // 图标样式
  const IconStyle = {
    fontSize: '8px',
    color: 'rgba(153,153,153,0.5)',
    transform: 'scaleX(1.2)',
  };
  // 路由钩子
  const router = useRouter();
  // 当前选择索引
  const [currentIndex, setCurrentIndex] = useState<number>(0);
  // 二级索引列表
  const [secondIndex, setSecondIndex] = useState<number[]>([]);
  // 二级索引选择
  const handleSecondary = (index: number) => {
    const has = secondIndex?.some((i) => i === index);
    const arr = has
      ? secondIndex?.filter((i) => i !== index)
      : [...secondIndex, index];
    const brr = isMultiple ? arr : [index];
    setSecondIndex(brr);
    // 二级筛选列表
    const second =
      brr?.length !== 0
        ? brr?.map((i) => list[currentIndex]?.children?.[i]?.value || 0)
        : list[currentIndex]?.children?.map((i) => i?.value) || [];
    // 二级筛选回调
    onSecond?.(second);
    // 统一返回筛选
    onSelect?.({
      main: list[currentIndex]?.value,
      second,
    });
  };
  // 主索引选择
  const handleMain = (index: number) => {
    setCurrentIndex(index);
    setSecondIndex([]);
    // 切换分类
    onMain?.(list[index]?.value);
    // 清空二级分类，并返回全部二级分类
    onSecond?.(list[index]?.children?.map((i) => i?.value) || []);
    // 统一返回筛选
    onSelect?.({
      main: list[index]?.value,
      second: list[index]?.children?.map((i) => i?.value) || [],
    });
  };
  // 选择全部商品
  const handleAll = () => {
    setSecondIndex([]);
    onSecond?.(list[currentIndex]?.children?.map((i) => i?.value) || []);
    // 统一返回筛选
    onSelect?.({
      main: list[currentIndex]?.value,
      second: list[currentIndex]?.children?.map((i) => i?.value) || [],
    });
  };
  // 组件挂载
  useEffect(() => {
    if (!list?.length) return;
    // 一级分类id
    const mainID = Number(router?.query?.main);
    // 二级分类id
    const secondID = Number(router?.query?.second);
    // 如果路由里面有一级分类id,则初始化一级分类
    if (mainID) {
      const index = list?.findIndex((i) => i?.value === mainID) || 0;
      setCurrentIndex(index);
      onMain?.(list[index]?.value);
      if (!secondID)
        onSecond?.(list[index]?.children?.map((i) => i?.value) || []);
    }
    // 如果路由里面有二级分类id,则初始化二级分类
    if (secondID) {
      const children = list?.find((i) => i?.value === mainID)?.children;
      const index = children?.findIndex((i) => i?.value === secondID) || 0;
      setSecondIndex([index]);
      onSecond?.(children?.[index]?.value ? [children?.[index]?.value] : []);
    }
    // 如果任何id都没有
    if (!router?.query?.main && !router?.query?.second) {
      // 初始化返回一级分类
      onMain?.(list[currentIndex]?.value);
      // 初始化全部二级分类
      onSecond?.(list[currentIndex]?.children?.map((i) => i?.value) || []);
    }
    // 统一返回筛选
    onSelect?.({
      main: mainID || list[currentIndex]?.value,
      second: secondID
        ? [secondID]
        : list[currentIndex]?.children?.map((i) => i?.value) || [],
    });
  }, [list, router]);
  return (
    <CategorySelectWrap>
      <div className="category-select flex-start">
        <div className="select-item">类别:</div>
        {list?.map((i, j) => (
          <div
            className={`select-item ${currentIndex === j && 'item-active'}`}
            key={j}
            onClick={() => handleMain(j)}
          >
            <div className="text">{i.label}</div>
            {currentIndex === j ? (
              <UpOutlined style={IconStyle} />
            ) : (
              <DownOutlined style={IconStyle} />
            )}
          </div>
        ))}
      </div>
      <div className="category-list flex-start">
        <div
          className={`list-item list-none ${
            secondIndex?.length === 0 && 'item-active'
          }`}
          onClick={handleAll}
        >
          {allText || '全部商品'}
        </div>
        {list[currentIndex]?.children?.map((i, j) => (
          <div
            className={`list-item list-none ${
              secondIndex?.includes(j) && 'item-active'
            }`}
            key={j}
            onClick={() => handleSecondary(j)}
          >
            {i.label}
          </div>
        ))}
      </div>
    </CategorySelectWrap>
  );
};

export default CategorySelectView;

const CategorySelectWrap = styled.div`
  position: relative;
  width: 100%;
  min-height: 2rem;
  border: 1px solid #ebebeb;
  margin-bottom: 1rem;
  .category-select {
    position: relative;
    width: 100%;
    min-height: 2rem;
    flex-wrap: wrap;
    border-bottom: 1px solid #ebebeb;
    .select-item {
      position: relative;
      box-sizing: border-box;
      color: #333333;
      padding: 0 1.25rem;
      min-height: 2rem;
      line-height: 2rem;
      display: flex;
      align-items: center;
      justify-content: center;
      &:first-child {
        color: #999999;
      }
      &:not(:first-child):active,
      &:not(:first-child):hover {
        background: #ececec;
      }
      &:not(:first-child) {
        cursor: pointer;
      }
      .text {
        margin-right: 0.25rem;
      }
    }
    .item-active {
      background: #ececec;
    }
  }
  .category-list {
    position: relative;
    width: 100%;
    min-height: 3rem;
    flex-wrap: wrap;
    box-sizing: border-box;
    padding: 0 0.5rem;
    .list-item {
      position: relative;
      min-height: 1.68rem;
      line-height: 1.68rem;
      padding: 0 0.5rem;
      cursor: pointer;
      margin: 0.25rem 0.5rem 0.25rem 0;
    }
    .item-active {
      color: #fff;
      background: #ff552d;
      border-radius: 4px;
    }
  }
  @media (prefers-color-scheme: dark) {
    .category-select {
      .select-item {
        color: #fff;
      }
      .item-active {
        color: #000;
      }
    }
  }
`;
