import {FC, useEffect, useState} from "react";
import {Image, Text, View} from "@tarojs/components";
import {HomeApi} from "@/api";
import Taro, {useReachBottom} from "@tarojs/taro";
import styles from './health.module.scss'
import play from '@/static/img/play-back.png'
import Empty from "@/components/empty/empty";
import Spin from "@/components/spinner";
import Img from "@/components/image/image";
import {formatDate} from "@/utils/time";

const Health: FC = () => {
  const [page, setPage] = useState(1)
  const [data, setData] = useState<Health[]>([])
  const [total, setTotal] = useState(0)
  const [enable, setEnable] = useState(true)

  async function getData(page: number) {
    try {
      const res = await HomeApi.health(page, 10)
      setData(res.data)
      setTotal(res.total)
    } catch (e) {
    }
    setEnable(false)
  }

  useReachBottom(() => {
    data.length < total && setPage(page + 1)
  })

  useEffect(() => {
    getData(page)
  }, [page])

  function jump(health: Health) {
    HomeApi.healthSetPlay(health.id)
    Taro.navigateTo({url: `/pages/preview/videoFull/videoFull?url=${health.resource.url}&poster=${health.url_path}&title=${health.title}`})
  }

  return (
    <>
      <Spin enable={enable} overlay/>
      <View>
        {
          data.length > 0 ? <>
              <View className={styles.container}>
                {data.map(d => <View key={d.id} className={styles.health} onClick={() => jump(d)}>
                  <Img width={370} height={345} src={d.url_path} mode='widthFix'/>
                  <Image src={play} className={styles.play} mode='aspectFit'/>
                  <View className='text-ellipsis-2 m-2 text-dark'>{d.title}</View>
                  <View className='font-26 text-muted mx-2 mb-2 flex justify-between'>
                    <Text>{formatDate(new Date(d.publish_time), "YY-MM-dd")}</Text>
                    <Text>{d.video_view}观看</Text>
                  </View>
                </View>)}
              </View>
              <View className='text-center font-24 text-dark mt-2'>暂无更多</View>
            </>
            : <Empty name='暂无数据'/>
        }
      </View>
    </>
  )
}

export default Health
