import Taro from '@tarojs/taro'
import {useShareAppMessage} from "@tarojs/taro"
import {Loading} from '@nutui/nutui-react-taro'
import {useEffect, useState} from "react"
import {useRouter} from '@tarojs/taro'
import {getCmsNavigation, listCmsNavigation} from "@/api/cms/cmsNavigation";
import {CmsNavigation} from "@/api/cms/cmsNavigation/model";
import {pageCmsArticle} from "@/api/cms/cmsArticle";
import {CmsArticle} from "@/api/cms/cmsArticle/model";
import ArticleList from './components/ArticleList'
import ArticleTabs from "./components/ArticleTabs";
import './index.scss'

function Category() {
  const {params} = useRouter();
  const [categoryId, setCategoryId] = useState<number>(0)
  const [category, setCategory] = useState<CmsNavigation[]>([])
  const [loading, setLoading] = useState<boolean>(true)
  const [nav, setNav] = useState<CmsNavigation>()
  const [list, setList] = useState<CmsArticle[]>([])

  const reload = async () => {
    // 1.加载远程数据
    const id = Number(params.id)
    const nav = await getCmsNavigation(id)
    const categoryList = await listCmsNavigation({parentId: id})
    const shopGoods = await pageCmsArticle({categoryId: id})

    // 2.赋值
    setCategoryId(id)
    setNav(nav)
    setList(shopGoods?.list || [])
    setCategory(categoryList)
    Taro.setNavigationBarTitle({
      title: `${nav?.categoryName}`
    })
  };

  useEffect(() => {
    reload().then(() => {
      setLoading(false)
    })
  }, []);

  useShareAppMessage(() => {
    return {
      title: `${nav?.categoryName}_桂乐淘`,
      path: `/shop/category/index?id=${categoryId}`,
      success: function () {
        console.log('分享成功');
      },
      fail: function () {
        console.log('分享失败');
      }
    };
  });

  if (loading) {
    return (
      <Loading className={'px-2'}>加载中</Loading>
    )
  }

  if(category.length > 0){
    return <ArticleTabs data={category}/>
  }

  return <ArticleList data={list}/>
}

export default Category
