import {useEffect, useState} from 'react'
import {View} from '@tarojs/components'
import {Swiper} from '@nutui/nutui-react-taro'
import {CmsAd} from "@/api/cms/cmsAd/model";
import {Image} from '@nutui/nutui-react-taro'
import {getCmsAdByCode} from "@/api/cms/cmsAd";
import navTo from "@/utils/common";
import {pageCmsArticle} from "@/api/cms/cmsArticle";
import {CmsArticle} from "@/api/cms/cmsArticle/model";


const MyPage = () => {
  const [carouselData, setCarouselData] = useState<CmsAd>()
  const [hotToday, setHotToday] = useState<CmsAd>()
  const [item, setItem] = useState<CmsArticle>()
  const [loading, setLoading] = useState(true)
  // const [disableSwiper, setDisableSwiper] = useState(false)

  // 用于记录触摸开始位置
  // const touchStartRef = useRef({x: 0, y: 0})

  // 加载数据
  const loadData = async () => {
    try {
      setLoading(true)
      // 轮播图
      const flash = await getCmsAdByCode('flash')
      // 今日热卖
      const hotToday = await getCmsAdByCode('hot_today')
      // 时里动态
      const news = await pageCmsArticle({limit:1,recommend:1})
      // 赋值
      if(flash){
        setCarouselData(flash)
      }
      if(hotToday){
        setHotToday(hotToday)
      }
      if(news && news.list.length > 0){
        setItem(news.list[0])
      }
    } catch (error) {
      console.error('Banner数据加载失败:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadData()
  }, [])

  // 轮播图高度，默认300px
  const carouselHeight = carouselData?.height || 300;

  // 骨架屏组件
  const BannerSkeleton = () => (
    <View className="flex p-2 justify-between" style={{height: `${carouselHeight}px`}}>
      {/* 左侧轮播图骨架屏 */}
      <View style={{width: '50%', height: '100%'}}>
        <View
          className="bg-gray-200 rounded animate-pulse"
          style={{height: `${carouselHeight}px`}}
        />
      </View>

      {/* 右侧骨架屏 */}
      <View className="flex flex-col" style={{width: '50%', height: '100%'}}>
        {/* 上层骨架屏 */}
        <View className="ml-2 bg-white rounded-lg">
          <View className="px-3 my-2">
            <View className="bg-gray-200 h-4 w-16 rounded animate-pulse"/>
          </View>
          <View className="px-3 flex" style={{height: '110px'}}>
            {[1, 2].map(i => (
              <View key={i} className="item flex flex-col mr-4">
                <View className="bg-gray-200 rounded animate-pulse" style={{width: 70, height: 70}}/>
                <View className="bg-gray-200 h-3 w-16 rounded mt-2 animate-pulse"/>
              </View>
            ))}
          </View>
        </View>

        {/* 下层骨架屏 */}
        <View className="ml-2 bg-white rounded-lg mt-3">
          <View className="px-3 my-2">
            <View className="bg-gray-200 h-4 w-20 rounded animate-pulse"/>
          </View>
          <View className="rounded-lg px-3 pb-3">
            <View className="bg-gray-200 rounded animate-pulse" style={{width: '100%', height: 106}}/>
          </View>
        </View>
      </View>
    </View>
  )

  // 如果正在加载，显示骨架屏
  if (loading) {
    return <BannerSkeleton />
  }

  return (
    <View className="flex p-2 justify-between bg-white" style={{height: `${carouselHeight}px`}}>
      {/* 左侧轮播图区域 */}
      <View
        style={{width: '50%', height: '100%'}}
        className="banner-swiper-container"
      >
        <Swiper
          defaultValue={0}
          height={carouselHeight}
          indicator
          autoPlay
          duration={3000}
          style={{
            height: `${carouselHeight}px`,
            touchAction: 'pan-y' // 关键修改：允许垂直滑动
          }}
          disableTouch={false}
          direction="horizontal"
          className="custom-swiper"
        >
          {carouselData && carouselData?.imageList?.map((img, index) => (
            <Swiper.Item key={index} style={{ touchAction: 'pan-x pan-y' }}>
              <Image
                width="100%"
                height="100%"
                src={img.url}
                mode={'scaleToFill'}
                onClick={() => navTo(`${img.path}`)}
                lazyLoad={false}
                style={{
                  height: `${carouselHeight}px`,
                  borderRadius: '4px',
                  touchAction: 'manipulation' // 关键修改：优化触摸操作
                }}
              />
            </Swiper.Item>
          ))}
        </Swiper>
      </View>

      {/* 右侧上下图片区域 - 从API获取数据 */}
      <View className="flex flex-col" style={{width: '50%', height: '100%'}}>
        {/* 上层图片 - 使用今日热卖素材 */}
        <View className={'ml-2 bg-white'}>
          <View className={'px-3 my-2 font-bold text-sm'}>今日热卖</View>
          <View className={'px-3 flex justify-between'} style={{
            height: '94px'
          }}>
            {
              hotToday?.imageList?.map(item => (
                <View className={'item flex flex-col mr-1'} key={item.url}>
                  <Image
                    width={60}
                    height={60}
                    src={item.url}
                    mode={'scaleToFill'}
                    lazyLoad={false}
                    style={{
                      borderRadius: '4px'
                    }}
                    onClick={() => navTo(item.path)}
                  />
                  <View className={'text-xs my-2 text-orange-600 whitespace-nowrap text-center'}>{item.title || '到手价¥9.9'}</View>
                </View>
              ))
            }
          </View>
        </View>

        {/* 下层图片 - 使用社区拼团素材  rounded-lg  shadow-sm */}
        <View className={'ml-2 bg-white mt-2'}>
          <View className={'px-3 my-2 font-bold text-sm'}>{item?.overview || item?.categoryName || '推荐文章'}</View>
          <View className={'rounded-lg px-3 pb-3'}>
            <Image
              width={'100%'}
              height={94}
              src={item?.image}
              mode={'scaleToFill'}
              lazyLoad={false}
              style={{
                borderRadius: '4px'
              }}
              onClick={() => navTo('cms/detail/index?id=' + item?.articleId)}
            />
          </View>
        </View>
      </View>
    </View>
  )
}

export default MyPage
