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

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-right: 0.5rem;
    }
    .item-active {
      color: #fff;
      background: #ff552d;
      border-radius: 4px;
    }
  }
`;

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

const CategorySelectView: React.FC<{
  list: CategoryType;
  onMain?: (arr: number) => void;
  onSecond?: (arr: number[]) => void;
}> = ({ list, onMain, onSecond }) => {
  // 图标样式
  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];
    setSecondIndex(arr);
    onSecond?.(
      arr?.length !== 0
        ? arr?.map((i) => list[currentIndex]?.children?.[i]?.value || 0)
        : list[currentIndex]?.children?.map((i) => i?.value) || [],
    );
  };
  // 主索引选择
  const handleMain = (index: number) => {
    setCurrentIndex(index);
    setSecondIndex([]);
    // 切换分类
    onMain?.(list[index]?.value);
    // 清空二级分类，并返回全部二级分类
    onSecond?.(list[index]?.children?.map((i) => i?.value) || []);
  };
  // 选择全部商品
  const handleAll = () => {
    setSecondIndex([]);
    onSecond?.(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);
      setCurrentIndex(index);
      onMain?.(list[index]?.value);
      if (!secondID) onSecond?.([]);
    }
    // 如果路由里面有二级分类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] : []);
    }
    if (!router?.query?.main && !router?.query?.second) {
      // 初始化返回一级分类
      onMain?.(list[currentIndex]?.value);
      // 初始化全部二级分类
      onSecond?.(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 ${secondIndex?.length === 0 && 'item-active'}`}
          onClick={handleAll}
        >
          全部商品
        </div>
        {list[currentIndex]?.children?.map((i, j) => (
          <div
            className={`list-item ${secondIndex?.includes(j) && 'item-active'}`}
            key={j}
            onClick={() => handleSecondary(j)}
          >
            {i.label}
          </div>
        ))}
      </div>
    </CategorySelectWrap>
  );
};

export default CategorySelectView;
