import React from 'react'
import { Image, Text, View } from '@tarojs/components'
import {
  Button
} from "@nutui/nutui-react-taro";
import './index.scss'
import TabbarAction from '@/components/action';
import { Infiniteloading } from '@nutui/nutui-react-taro';
import { useEffect } from 'react';
import { useState } from 'react';

import Taro from '@tarojs/taro';
import { mallList } from '../../utils/api';
import { useRouter } from '@tarojs/taro';


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)
  const [chan] = useState(param.source != 'shopping_score_mall' ? 'mall' : 'shopping_score_mall')



  useEffect(() => {
    if (page < 1) {
      return
    }
    fetchList(page)
  }, [page])

  const fetchList = async (page) => {

    const offset = (page - 1) * limit
    const res = await mallList(chan, 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 index={1} />
      <View className='home-body' id="shoppingScroll">
        <Infiniteloading
          containerId="shoppingScroll"
          useWindow={false}
          loadTxt="loading"
          loadMoreTxt="没有数据啦～"
          loadIcon='loading'
          hasMore={hasMore}
          onLoadMore={(x) => {
            setPage(p => p + 1)
            x()
          }}
        >
          <View className='shopping-container '>
            {
              list.map(item => {
                return <View className='shopping-item' key={item.id} onClick={() => {
                  navDetailFn(item.id)
                }}>
                  <View className='shopping-item-image'>
                    <Image src={item.cover_image} />
                  </View>
                  <View className='shopping-item-content'>
                    <View className='shopping-item-name line-clamp-2'>
                      {item.name}
                    </View>
                    {/* <View className='shopping-item-desc line-clamp-2 '>
                      这个是商品的介绍
                    </View> */}
                    <View className='shopping-item-price text-left'>
                      <Text className='shopping-item-price-sale'>¥{item.price}</Text>
                      {/* <Text className='shopping-item-price-origin'>原价888</Text> */}
                    </View>
                  </View>

                </View>
              })
            }


          </View>
        </Infiniteloading>
      </View>
    </View>
  )
}

export default Index
