import Taro from '@tarojs/taro'
import {useShareAppMessage} from "@tarojs/taro"
import {useEffect, useState} from "react"
import {useRouter} from '@tarojs/taro'
import {View} from '@tarojs/components'
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 () => {
    try {
      setLoading(true)
      // 1.加载远程数据
      const id = Number(params.id || 4328)
      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}`
      })
    } catch (error) {
      console.error('文章分类加载失败:', error)
    } finally {
      setLoading(false)
    }
  };

  useEffect(() => {
    reload()
  }, []);

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

  // 骨架屏组件
  const ArticleSkeleton = () => (
    <View className="px-3">
      {[1, 2, 3, 4, 5].map(i => (
        <View key={i} className="flex items-center py-4 border-b border-gray-100">
          {/* 左侧文字骨架屏 */}
          <View className="flex-1 pr-4">
            {/* 标题骨架屏 */}
            <View className="bg-gray-200 h-5 rounded animate-pulse mb-2" style={{width: '75%'}}/>
            {/* 副标题骨架屏 */}
            <View className="bg-gray-200 h-4 rounded animate-pulse" style={{width: '50%'}}/>
          </View>
          {/* 右侧图片骨架屏 */}
          <View
            className="bg-gray-200 rounded animate-pulse flex-shrink-0"
            style={{width: '100px', height: '100px'}}
          />
        </View>
      ))}
    </View>
  )

  if (loading) {
    return <ArticleSkeleton />
  }

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

  return <ArticleList data={list}/>
}

export default Category
