import {FC, ReactNode, useCallback, useEffect, useState} from "react";
import {Text, Video, View} from "@tarojs/components";
import {brandApi, BrandRecord} from "@/api";
import Taro, {useReachBottom} from "@tarojs/taro";
import Empty from "@/components/empty/empty";
import Spinner from "@/components/spinner";
import Img from "@/components/image/image";
import {beforeTime} from "@/utils/time";
import styles from './list.module.scss'
// import articleLine from "@/static/img/articleLine.png"
// import Collect from "@/components/collect/collect";
import PageScript from "@/components/pageScript/pageScript";

const BrandItem: FC<{ data: BrandRecord; onClick: VoidFunction }> = ({data, onClick}) => {
  let media: ReactNode
  let hasMedia = true
  if (data.introductory_video_resource) {
    media = <Video
      style={{width: '100%'}}
      src={data.introductory_video_resource.url}
    />
  } else if (data.brand_album) {
    media = <Img
      height={320}
      errorType='profession'
      src={data.brand_album.split(",")[0]}
      mode="aspectFill"
      style={{background: '#ededed'}}
    />
  } else {
    hasMedia = false
  }

  return (
    <View className="bg-white flex flex-column justify-stretch mb-2 clip">
      <View className="p-3">
        <View onClick={onClick}>
          <View className='mb-2 font-32 flex'>
            <Img
              width={76}
              height={76}
              src={data.logo}
              mode='aspectFill'
              errorType='brand'
              className="rounded clip"
              style={{background: '#ededed'}}
            />
            <View className="ml-2 flex-1">
              <View className="text-row1 font-28">{data.name}</View>
              <View className='font-24 mt-2 text-muted'>
                <Text>{beforeTime(data.created_at)}</Text>
                <Text className='ml-2'>文章 {data.article_count || 0}</Text>
              </View>
            </View>
          </View>
          {hasMedia && <View className={styles.previewImag + ' mb-2'}>{media}</View>}
          <View className="font-24 text-muted text-row3" style={{lineHeight: 1.4}}>
            {data.graphic_introduction}
          </View>
        </View>
        {/*<View className="flex gap20rpx font-24 text-muted justify-around">
          <View className={styles.feature}>
            <Image src={articleLine}/>
            {data.article_count || 0}
          </View>
          <Collect owner_id={data.id} owner_type={4} select={data.collect}/>
        </View>*/}
      </View>
    </View>
  )
}

const BrandList: FC = () => {
  const [page, setPage] = useState(1)
  const [brands, setBrands] = useState<BrandRecord[]>([])
  const [total, setTotal] = useState(0)
  const [text, setText] = useState('')
  const [loading, setLoading] = useState(true)

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

  Taro.useDidShow(() => {
    brands.length && getData(true)
  })

  const getData = useCallback(async (replace = false) => {
    try {
      const res = await brandApi.list(replace ? 1 : page, replace ? 10 * page : 10)
      if (page === 1) {
        if (res.list.length < 10) {
          setText('暂无更多')
        } else {
          setText('上拉加载更多')
        }
      }
      setTotal(res.total)
      const data = res.list.reduce((pre, cur) => {
        const index = pre.findIndex(d => d.id === cur.id)
        if (index > -1) {
          pre.splice(index, 1, cur)
        } else {
          pre.push(cur)
        }
        return pre
      }, JSON.parse(JSON.stringify(brands)))
      setBrands(data)
    } catch (e) {
    }
    setLoading(false)
  }, [page])


  function jumpInfo(id: number) {
    Taro.navigateTo({url: `/pages/preview/brand/info/info?id=${id}`})
  }

  useReachBottom(useCallback(() => {
    if (brands?.length < total) {
      setPage(page + 1)
    } else {
      setText('没有更多了~')
    }
  }, [total, brands]))


  return (
    <View className='py-2'>
      <Spinner enable={loading} overlay/>
      {
        brands.length ?
          <>
            {brands.map(d => <BrandItem data={d} key={d.id} onClick={() => jumpInfo(d.id)}/>)}
            <PageScript text={text}/>
          </>
          : <Empty name='暂无品牌入驻'/>
      }
    </View>
  )
}

export default BrandList
