/**
 * GPS 定位定时上报功能
 */
import { uploadGps } from '@/api/fulfiller/fulfiller.js'

let gpsTimer = null

/**
 * 获取并上传GPS定位 (带授权检查)
 */
export function reportGps(manual = false) {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'wgs84',
      success: function (res) {
        const data = {
          longitude: res.longitude,
          latitude: res.latitude
        }
        uploadGps(data).then(() => {
          console.log('GPS定位上传成功', data)
          resolve(res)
        }).catch(err => {
          console.error('GPS定位上传失败', err)
          reject(err)
        })
      },
      fail: function (err) {
        console.error('获取GPS定位失败', err)
        // 如果是手动触发且失败，尝试引导授权
        if (manual) {
          checkAndRequestPermission(reject)
        } else {
          reject(err)
        }
      }
    })
  })
}

/**
 * 检查并请求定位权限
 */
function checkAndRequestPermission(reject) {
  uni.getSetting({
    success(res) {
      if (!res.authSetting['scope.userLocation']) {
        uni.showModal({
          title: '定位未授权',
          content: '请开启定位权限，以便为您推荐附近的订单并记录服务轨迹',
          confirmText: '去设置',
          success: (modalRes) => {
            if (modalRes.confirm) {
              uni.openSetting({
                success: (settingRes) => {
                  if (settingRes.authSetting['scope.userLocation']) {
                    reportGps(true)
                  }
                }
              })
            } else {
              if (reject) reject(new Error('User denied location permission'))
            }
          }
        })
      } else {
        // 权限其实是有的，可能是系统GPS屏蔽了或其他原因
        uni.showToast({ title: '获取定位失败，请检查手机GPS是否开启', icon: 'none' })
        if (reject) reject(new Error('Location failed even with permission'))
      }
    }
  })
}

export function startGpsTimer() {
  const isEnabled = uni.getStorageSync('GPS_REPORT_ENABLED')
  if (isEnabled === false) {
    stopGpsTimer()
    return
  }
  stopGpsTimer()
  reportGps() // 默认静默尝试
  gpsTimer = setInterval(() => {
    reportGps()
  }, 1200000)
}

/**
 * 停止GPS定时上报
 */
export function stopGpsTimer() {
  if (gpsTimer) {
    clearInterval(gpsTimer)
    gpsTimer = null
  }
}
