import Taro from '@tarojs/taro'
import {useEffect, useState} from 'react'
import {View, Text} from '@tarojs/components'
import {Image} from '@nutui/nutui-react-taro'
import {Loading} from '@nutui/nutui-react-taro'
import {listCmsNavigation} from "@/api/cms/cmsNavigation"
import {CmsNavigation} from "@/api/cms/cmsNavigation/model"

const Page = () => {

  const [loading, setLoading] = useState<boolean>(true)
  const [navItems, setNavItems] = useState<CmsNavigation[]>([])

  const reload = async () => {
    // 读取首页菜单
    const home = await listCmsNavigation({model: 'index'});
    const homeId = home[0].navigationId;
    if (homeId) {
      // 读取首页导航条
      const menus = await listCmsNavigation({parentId: homeId, hide: 0});
      setNavItems(menus || [])
    }
  };

  const onNav = (row: CmsNavigation) => {
    console.log('nav = ', row)
    console.log('path = ', `/${row.model}${row.path}`)
    if (row.model == 'goods') {
      return Taro.navigateTo({url: `/shop/category/index?id=${row.navigationId}`})
    }
    if (row.model == 'article') {
      return Taro.navigateTo({url: `/cms/category/index?id=${row.navigationId}`})
    }
    return Taro.navigateTo({url: `${row.path}`})
  }


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

  if (loading) {
    return (
      <Loading>加载中</Loading>
    )
  }

  if (navItems.length === 0) {
    return <View className={'hidden'}></View>;
  }

  return (
    <View className={'p-2 z-50 mt-1 hidden'}>
      <View className={'flex justify-between pb-2 p-2 bg-white rounded-xl shadow-sm'}>
        {
          navItems.map((item, index) => (
            <View key={index} className={'text-center'} onClick={() => onNav(item)}>
              <View className={'flex flex-col justify-center items-center p-1'}>
                <Image src={item.icon} height={36} width={36} lazyLoad={false}/>
                <View className={'mt-1'}>
                  <Text className={'text-gray-600'} style={{fontSize: '14px'}}>{item?.title}</Text>
                </View>
              </View>
            </View>
          ))
        }
      </View>
    </View>
  )
}
export default Page
