import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { InterDataType } from '@/api/interface';
import {
  GetAppCategoryInfo,
  QueryGoodsInfoByCategorySub,
} from '@/api/interface/mall';
import { MallAPI } from '@/api/modules/mall';
import BreadcrumbView from '@/components/breadcrumb';
import CategorySelectView, { CategoryType } from '@/components/categorySelect';
import LayoutView from '@/components/layout';
import ProductItemView from '@/components/productItem';
import { MallWrap } from '@/pages/mall/styled';

// 分类列表类型
type CategoryListType = InterDataType<GetAppCategoryInfo>;
// 商品列表类型
type GoodsInfoListType = InterDataType<QueryGoodsInfoByCategorySub>;

// 每次加载页面都会执行
export async function getServerSideProps() {
  // 分类数据
  let categoryList: CategoryListType = [];
  // 获取各个目录及分类信息
  const getAppCategoryInfo = async () => {
    const res = await MallAPI.getAppCategoryInfo({
      type: 4,
    });
    if (res && res.code === '200') {
      categoryList = res?.result || [];
    }
  };
  // 依次获取接口数据
  await (async () => {
    await getAppCategoryInfo();
  })();
  return { props: { categoryList } };
}
const MallView: React.FC<{
  categoryList: CategoryListType;
}> = (props) => {
  // 路由钩子
  const router = useRouter();
  // 分类列表
  const [categoryList, setCategoryList] = useState<CategoryType>([]);
  // 商品列表
  const [goodsInfoList, setGoodsInfoList] = useState<GoodsInfoListType>([]);
  // 转换分类列表
  const getCategoryList = () => {
    setCategoryList(
      props?.categoryList?.map((i) => ({
        value: i.id,
        label: i.name,
        children: i.subDTOList?.map((n) => ({ value: n.id, label: n.name })),
      })),
    );
  };
  // 获取商品列表
  const getGoodsInfoByCategorySub = async (list: number[]) => {
    const res = await MallAPI.queryGoodsInfoByCategorySub(list);
    if (res && res.code === '200') {
      setGoodsInfoList(res.result || []);
      console.log('商品列表 --->', res.result);
    }
  };
  // 组件挂载
  useEffect(() => {
    if (!props) return;
    getCategoryList();
    // console.log('执行到此处12312 --->', props);
  }, [props]);
  // 路由变化
  useEffect(() => {
    console.log('路由变化 --->', router);
  }, [router]);
  return (
    <>
      <LayoutView placeholder={true}>
        <MallWrap>
          <BreadcrumbView />
          <CategorySelectView
            list={categoryList}
            onSecond={getGoodsInfoByCategorySub}
          />
          <div className="mall-list flex-start">
            {goodsInfoList?.map((i, j) => (
              <ProductItemView key={j} detail={i} />
            ))}
          </div>
        </MallWrap>
      </LayoutView>
    </>
  );
};

export default MallView;
