import {Swiper, SwiperItem, View} from "@tarojs/components";
import {FC, useEffect, useState} from "react";
import {AdwareType} from "@/api";
import Taro from "@tarojs/taro";
import styles from '../home.module.scss'
import Img from "@/components/image/image";

interface Props {
  data: any[]
  only_flag: string
  width: number
}

const Adware: FC<Props> = ({data, only_flag, width}) => {
  const [adverts, setAdverts] = useState<AdwareType[]>([])
  const [space, setSpace] = useState<any | null>(null)

  useEffect(() => {
    const res = data.find(d => d.only_flag === only_flag)
    setSpace(res)
    setAdverts(res?.adverts || [])
  }, [data])

  function jumpAdware(url: string) {
    if (url.substring(0, 3) === 'wx:') {
      Taro.navigateTo({
        url: url.substring(3, url.length)
      })
    }
  }

  return (
    <>
      {
        adverts.length > 0 && <View className={styles.adware}>
          {
            adverts.length === 1 && <Img
              src={adverts[0].image_url}
              mode='scaleToFill'
              lazyLoad
              fadeIn
              onClick={() => jumpAdware(adverts[0].image_path)}
              width={width}
              height={(space.height / space.width) * width}/>
          }
          {
            adverts.length > 1 && <Swiper
              indicatorDots
              autoplay
              circular
              style={{width: width + "rpx", height: (space.height / space.width) * width + "rpx", overflow: 'hidden'}}
              indicatorActiveColor='rgba(255,255,255,0.5)'>
              {adverts.map(d => <SwiperItem key={d.id}>
                <Img
                  src={d.image_url}
                  lazyLoad
                  fadeIn
                  width={width}
                  height={(space.height / space.width) * width}
                  onClick={() => jumpAdware(d.image_path)}/>
              </SwiperItem>)}
            </Swiper>
          }
        </View>
      }
    </>
  )
}

export default Adware
