import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { Image } from '@tarojs/components'
import { getImgURL } from '@/utils/image'
import { fetch } from '@/utils/request'
import { API_NEWS_LIST } from '@/constants/api'
import '@/assets/css/iconfont.css'
import './index.scss'

export default function News (props) {
  const { Info = {} } = props

  const [NewsList, setNewsList] = useState([])

  const gotoList = () => {
    const buildingId = Info?.buildingId
    Taro.navigateTo({
      url: `/pages/index/newsList/index?buildingId=${buildingId}`
    })
  }

  const gotoDetail = (item) => {
    Taro.navigateTo({
      url: `/pages/index/newsDetail/index?id=${item.newsId}`
    })
  }

  useEffect(() => {
    if (Info?.buildingId) {
      // 获取资讯列表
      fetch({ url: API_NEWS_LIST, payload: { buildingId: Info.buildingId, pageSize: 2, pageNum: 1 } }).then((res) => {
        setNewsList(res.records || [])
      })
    }
  }, [Info?.buildingId])

  return NewsList.length > 0 ? (
    <view className='components News'>

      <view className='Title flex-h'>
        <view className='flex-item'>
          <text>新鲜资讯</text>
        </view>
        <text onClick={gotoList}>更多</text>
        <text className='iconfont icon-jiantouright'></text>
      </view>

      <view className='List flex-h'>
        {
          NewsList.length > 0 &&
          <view className='flex-item' onClick={() => gotoDetail(NewsList[0])}>
            <view className='Img' style={{display: NewsList[0].newsImg || NewsList[0].newsName ? 'block' : 'none'}}>
              <Image mode='aspectFill' src={getImgURL(NewsList[0].newsImg)} className='centerLabel'></Image>
            </view>
            <text className='Title'>{NewsList[0].newsName}</text>
          </view>
        }
        {
          NewsList.length > 1 &&
          <view className='flex-item' onClick={() => gotoDetail(NewsList[1])}>
            <view className='Img' style={{display: NewsList[1].newsImg || NewsList[1].newsName ? 'block' : 'none'}}>
              <Image mode='aspectFill' src={getImgURL(NewsList[1].newsImg)} className='centerLabel'></Image>
            </view>
            <text className='Title'>{NewsList[1].newsName}</text>
          </view>
        }
        {
          NewsList.length === 1 &&
          <view className='flex-item'></view>
        }
      </view>

    </view>
  ) : null;
}
