import {FC, useEffect, useState} from "react";
import {Text, View} from "@tarojs/components";
import Taro from "@tarojs/taro";
import styles from './articlesBox.module.scss'
import Img from "@/components/image/image";
import {beforeTime} from "@/utils/time";
import articlesEvent from "@/hooks/articlesEvent";

interface Props {
  data: Articles
}

const ArticlesBox: FC<Props> = (props) => {
  const [data, setData] = useState(props.data)

  useEffect(() => {
    setData(props.data)
  }, [props.data])

  useEffect(() => {
    articlesEvent.recordsOn(data.id, ({view}) => {
      setData({
        ...data,
        page_view: view
      })
    })
  }, [])

  Taro.useUnload(() => {
    articlesEvent.off(data.id)
  })

  const toArticlePage = () => {
    Taro.navigateTo({
      url: `/pages/preview/brand/article/article?id=${data.id}`
    })
  }

  return (
    <View className={styles.artcles} onClick={toArticlePage}>
      <View className={styles.outside}>
        <View className='flex-1 mr-2'>
          <View className={`${styles.title} text-ellipsis-1`}>{data.title}</View>
          <View className={`${styles.intro} text-ellipsis-2`}>{data.intro}</View>
          <View className={styles.pageView}>
            <Text>{beforeTime(data.created_at)}</Text>·
            <Text>{data.page_view || 0}阅读</Text>
          </View>
        </View>
        <Img src={data.cover || ''}
             errorType={data.owner_type === 1 ? 'brand' : 'health'}
             width={148}
             height={116}
             className={styles.img}/>
      </View>
    </View>
  )
}
export default ArticlesBox
