/**
 * 首页
 */
import { View, Image } from '@tarojs/components'
import { useLoad } from '@tarojs/taro'
import Taro from '@tarojs/taro'
import { observer } from 'mobx-react'
import { Swiper } from '@taroify/core'
import { LocationOutlined } from '@taroify/icons'
import { useEffect, useState } from 'react'
import { userStore } from '../../store'
import { getBigImage, BIG_IMAGES } from '@/utils/imageHelper'
import './index.scss'

const Index = observer(() => {
  const [currentDistance, setCurrentDistance] = useState('--')
  const [storeName, setStoreName] = useState('黑八大师联盟球厅店')

  useLoad(() => {
    console.log('首页加载')
  })

  // 请求定位权限并获取位置
  const requestLocationPermission = async () => {
    try {
      // 检查定位权限设置
      const setting = await Taro.getSetting()
      
      if (!setting.authSetting['scope.userLocation']) {
        // 未授权，请求授权
        try {
          await Taro.authorize({ scope: 'scope.userLocation' })
        } catch (err) {
          // 用户拒绝授权，引导用户手动开启
          Taro.showModal({
            title: '定位权限',
            content: '需要获取您的位置信息以显示附近门店，请在设置中开启定位权限',
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                Taro.openSetting()
              }
            }
          })
          return
        }
      }

      // 获取当前位置
      const location = await Taro.getLocation({
        type: 'gcj02',
        isHighAccuracy: true
      })
      
      console.log('当前位置:', location)
      // 这里可以根据实际位置计算距离，暂时模拟
      setCurrentDistance('1.12km')
      
    } catch (err) {
      console.error('获取位置失败:', err)
      setCurrentDistance('--')
    }
  }

  useEffect(() => {
    // 页面加载时请求定位权限
    requestLocationPermission()
  }, [])

  // 处理扫码开台点击 - 跳转到独立扫码页面（无tabbar）
  const handleScanClick = () => {
    Taro.navigateTo({
      url: '/pages/scanCode/index'
    })
  }

  // 处理附近门店点击
  const handleNearbyStoreClick = () => {
    Taro.switchTab({
      url: '/pages/store/index'
    })
  }

  // 处理团购核销点击
  const handleGroupBuyClick = () => {
    Taro.showToast({
      title: '团购核销功能开发中',
      icon: 'none'
    })
  }

  return (
    <View className="index-page">
      {/* 轮播图区域 */}
      <View className="swiper-container">
        <Swiper 
          className="swiper" 
          autoplay={3000}
          lazyRender
        >
          <Swiper.Indicator className="swiper-indicator" />
          <Swiper.Item>
            <Image 
              className="swiper-image" 
              src={getBigImage('SW_BG')} 
              mode="aspectFill" 
            />
          </Swiper.Item>
          <Swiper.Item>
            <Image 
              className="swiper-image" 
              src={getBigImage('SW_BG')} 
              mode="aspectFill" 
            />
          </Swiper.Item>
        </Swiper>
      </View>

      {/* 内容区域 - 上移覆盖轮播图 */}
      <View className="content-area">
        <View className="card-container">
          {/* 左侧扫码开台 */}
          <View className="scan-card" onClick={handleScanClick}>
            <Image 
              className="card-bg" 
              src={getBigImage('SMKT')} 
              mode="aspectFill" 
            />
            <View className="card-text-content">
              <View className="card-text-title">扫码开台</View>
              <View className="card-text-desc">扫球桌二维码开台/关台</View>
            </View>
          </View>

          {/* 右侧上下两个卡片 */}
          <View className="right-cards">
            {/* 附近门店 */}
            <View className="nearby-store-card" onClick={handleNearbyStoreClick}>
              <Image 
                className="card-bg" 
                src={getBigImage('FJMD')} 
                mode="aspectFill" 
              />
              <View className="card-content">
                <View className="card-title">附近门店</View>
                <View className="store-name">{storeName}</View>
                <View className="store-distance">
                  <LocationOutlined size={24} />
                  <View className="distance-text">{currentDistance}</View>
                </View>
              </View>
            </View>

            {/* 团购核销 */}
            <View className="group-buy-card" onClick={handleGroupBuyClick}>
              <Image 
                className="card-bg" 
                src={getBigImage('TGHX')} 
                mode="aspectFill" 
              />
              <View className="card-text-content">
                <View className="card-text-title">团购核销</View>
                <View className="card-text-desc">美团/抖音/点评/快手</View>
              </View>
            </View>
          </View>
        </View>
      </View>
    </View>
  )
})

export default Index
