import { Image, Swiper, SwiperItem, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { formatImgUrl } from '@/common/fotmat'

interface item { title: string; img: string; url: string; id: number }
interface params {
  list?: item[]
}
const SwiperComp = ({ list = [] }: params) => {
  const [pageIndex, setPageIndex] = useState(1)
  const pageRef = useRef<any>(null)

  const pageCount = useMemo(() => {
    return list.length
  }, [list])

  const formatImages = useMemo(() => {
    return list?.map(item => formatImgUrl(item, '!w800'))
  }, [list])

  const swiperChange = (e) => {
    setPageIndex(e.detail.current + 1)
  }

  const onShowImage = () => {
    Taro.previewImage({
      current: formatImages[0],
      urls: formatImages,
    })
  }

  return (
    <View className={styles.swiper}>
      {list.length > 0 && (
        <Swiper className={styles.swiper_item} circular onAnimationFinish={e => swiperChange(e)}>
          {list?.map((item, key) => {
            return (
              <SwiperItem key={key}>
                <View className={styles.image_item} onClick={onShowImage}>
                  <Image mode="aspectFill" src={formatImgUrl(item, '!w400')}></Image>
                </View>
              </SwiperItem>
            )
          })}
        </Swiper>
      )}
      {list.length > 0 && (
        <View className={styles.page} ref={pageRef}>
          {`${pageIndex}/${pageCount}`}
        </View>
      )}
    </View>
  )
}

export default SwiperComp
