import Taro from '@tarojs/taro'
import GoodsList from './components/GoodsList'
import {useShareAppMessage} from "@tarojs/taro"
import {Loading,Empty} from '@nutui/nutui-react-taro'
import {useEffect, useState} from "react"
import {useRouter} from '@tarojs/taro'
import './index.scss'
import {pageShopGoods} from "@/api/shop/shopGoods"
import {ShopGoods} from "@/api/shop/shopGoods/model"
import {getCmsNavigation} from "@/api/cms/cmsNavigation";
import {CmsNavigation} from "@/api/cms/cmsNavigation/model";

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

  const reload = async () => {
    // 1.加载远程数据
    const id = Number(params.id)
    const nav = await getCmsNavigation(id)
    const shopGoods = await pageShopGoods({categoryId: id, status: 0})

    // 2.处理业务逻辑
    setCategoryId(id)
    setNav(nav)
    setList(shopGoods?.list || [])

    // 3.设置标题
    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 text-center'}>加载中</Loading>
    )
  }

  if(list.length == 0){
    return (
      <Empty description="暂无数据"/>
    )
  }

  return (
    <>
      <div className={'flex flex-col'}>
        <GoodsList data={list} nav={nav}/>
      </div>
    </>
  )
}

export default Category
