import React from 'react'
import { Image, Text, View } from '@tarojs/components'
import './index.scss'
import TabbarAction from '@/components/action';
import { Infiniteloading } from '@nutui/nutui-react-taro';
import { useEffect } from 'react';
import { useState } from 'react';
import { mallList } from '../../utils/api';
import Taro from '@tarojs/taro';
import { useRouter } from '@tarojs/taro';
import { SetData } from '../../utils/storage';


function Index() {
  const param = useRouter().params
  const limit = 20
  const [list, setList] = useState([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)

  useEffect(() => {
    if (page < 1) {
      return
    }
    fetchList(page)
    if (param.code) {
      SetData("inviteCode", param.code)
    }

  }, [page])

  const fetchList = async (page) => {
    const offset = (page - 1) * limit
    const res = await mallList('mall', offset, limit)

    if (!res) return
    if (res.items?.length + list.length >= res.total) {
      setHasMore(false)
    }
    setList(it => [...it, ...res.items])
    setTotal(res.total)
  }


  // 跳转
  const navDetailFn = (id) => {
    Taro.navigateTo({
      url: `/pages/goods-detail/index?id=${id}`
    })
  }

  return (
    <View className='home-container'>
      <View className='home-title'>首页</View>
      <TabbarAction />
      <View className='home-body' id="customScroll">
        <Infiniteloading
          containerId="customScroll"
          useWindow={false}
          loadTxt="loading"
          loadMoreTxt={<View></View>}
          loadIcon='loading'
          hasMore={hasMore}
          onLoadMore={(x) => {
            setPage(p => p + 1)
            x()
          }}
        >
          <View className='goods-container '>
            {
              list.map(item => {
                return <View className='goods-item' key={item.id} onClick={() => {
                  navDetailFn(item.id)
                }}>
                  <View className='goods-item-image'>
                    <Image src={item.cover_image} />
                  </View>
                  <View className='goods-item-name line-clamp-2'>
                    {item.name}
                  </View>
                  {/* <View className='goods-item-desc line-clamp-2 '>
                    这个是商品的介绍
                  </View> */}
                  <View className='goods-item-price'>
                    <Text className='goods-item-price-sale'>¥{item.price}</Text>
                    {/* <Text className='goods-item-price-origin'>原价888</Text> */}
                  </View>
                </View>
              })
            }
          </View>
        </Infiniteloading>
      </View>
    </View>
  )
}

export default Index
