import Taro from '@tarojs/taro'
import {useEffect, useState} from 'react'
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'});
    if (home && home.length > 0) {
      // 读取首页导航条
      const menus = await listCmsNavigation({parentId: home[0].navigationId, 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)
    });
  }, [])

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