import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { useVipStore } from '@/stores/vip'

// 广告平台配置
const AD_PLATFORMS = {
  WECHAT: {
    reward: (adUnitId) => {
      const ad = wx.createRewardedVideoAd({
        adUnitId,
        multiton: true
      })
      ad.onError(err => console.error('微信激励广告错误:', err))
      return ad
    },
    feed: (adUnitId) => {
      return wx.createBannerAd({
        adUnitId,
        adIntervals: 30,
        style: {
          left: 0,
          top: 0,
          width: 320
        }
      })
    },
    interstitial: (adUnitId) => {
      return wx.createInterstitialAd({ adUnitId })
    }
  },
  DOUYIN: {
    reward: (adUnitId) => {
      const ad = tt.createRewardedVideoAd({ adUnitId })
      ad.onError(err => console.error('抖音激励广告错误:', err))
      return ad
    },
    feed: (adUnitId) => {
      return tt.createBannerAd({
        adUnitId,
        style: {
          left: 0,
          top: 0,
          width: 300
        }
      })
    },
    interstitial: (adUnitId) => {
      return tt.createInterstitialAd({ adUnitId })
    }
  },
  H5: {
    reward: (adUnitId) => {
      console.log('H5激励广告:', adUnitId)
      return { 
        show: () => {
          console.log('展示激励广告')
          return Promise.resolve()
        },
        onClose: (callback) => {
          // 模拟关闭事件
          setTimeout(() => callback({ isEnded: true }), 3000)
        }
      }
    },
    feed: (adUnitId) => {
      console.log('H5信息流广告:', adUnitId)
      return {
        show: () => console.log('展示信息流广告'),
        destroy: () => {}
      }
    },
    interstitial: (adUnitId) => {
      console.log('H5插屏广告:', adUnitId)
      return {
        show: () => console.log('展示插屏广告')
      }
    }
  }
}

// 广告触发控制器
export function useAdManager() {
  const userStore = useUserStore()
  const chapterCount = ref(0)
  const lastAdShownTime = ref(0)
  
  // 获取当前平台适配器
  const getPlatformAdapter = () => {
    // #ifdef MP-WEIXIN
    return AD_PLATFORMS.WECHAT
    // #endif
    // #ifdef MP-TOUTIAO
    return AD_PLATFORMS.DOUYIN
    // #endif
    return AD_PLATFORMS.H5
  }

  // 展示激励广告（每5章触发）
  const showRewardAd = async (chapterId) => {
    if (userStore.isVIP) return
    
    // 广告冷却时间（至少30秒）
    const now = Date.now()
    if (now - lastAdShownTime.value < 30000) return
    
    chapterCount.value++
    if (chapterCount.value % 5 !== 0) return
    
    const platform = getCurrentPlatform()
    const adapter = getPlatformAdapter()
    const adUnitId = getAdUnitId(platform, 'reward')
    
    if (!adUnitId) {
      console.error('未配置广告单元ID')
      return
    }
    
    const ad = adapter.reward(adUnitId)
    
    try {
      // 监听广告关闭事件
      return new Promise((resolve) => {
        ad.onClose(res => {
          if (res && res.isEnded) {
            // 完整观看，记录广告
            logAdView(chapterId, 'reward', platform)
            resolve(true)
          } else {
            resolve(false)
          }
        })
        
        // 展示广告
        ad.show().catch(err => {
          console.error('广告展示失败:', err)
          resolve(false)
        })
        
        lastAdShownTime.value = Date.now()
      })
    } catch (err) {
      console.error('广告展示失败:', err)
      return false
    }
  }

  // 展示底部信息流广告
  const showFeedAd = (adUnitId) => {
    if (userStore.isVIP) return null
    
    const platform = getCurrentPlatform()
    const adapter = getPlatformAdapter()
    
    if (!adUnitId) {
      adUnitId = getAdUnitId(platform, 'feed')
    }
    
    if (!adUnitId) {
      console.error('未配置信息流广告单元ID')
      return null
    }
    
    const ad = adapter.feed(adUnitId)
    try {
      ad.show()
      return ad
    } catch (err) {
      console.error('信息流广告展示失败:', err)
      return null
    }
  }

  // 展示插屏广告
  const showInterstitialAd = () => {
    if (userStore.isVIP) return
    
    // 广告冷却时间（至少60秒）
    const now = Date.now()
    if (now - lastAdShownTime.value < 60000) return
    
    const platform = getCurrentPlatform()
    const adapter = getPlatformAdapter()
    const adUnitId = getAdUnitId(platform, 'interstitial')
    
    if (!adUnitId) {
      console.error('未配置插屏广告单元ID')
      return
    }
    
    const ad = adapter.interstitial(adUnitId)
    try {
      ad.show()
      lastAdShownTime.value = Date.now()
      return true
    } catch (err) {
      console.error('插屏广告展示失败:', err)
      return false
    }
  }

  // 广告日志记录
  const logAdView = (chapterId, adType, platform) => {
    uni.request({
      url: 'https://api.aiyadianzi.ltd/ad/log',
      method: 'POST',
      data: {
        userId: userStore.userId,
        chapterId,
        adType,
        platform
      },
      header: {
        'Authorization': `Bearer ${uni.getStorageSync('token')}`
      }
    })
  }
  
  // 获取当前平台
  const getCurrentPlatform = () => {
    // #ifdef MP-WEIXIN
    return 'wechat'
    // #endif
    // #ifdef MP-TOUTIAO
    return 'douyin'
    // #endif
    return 'h5'
  }
  
  // 获取广告单元ID
  const getAdUnitId = (platform, adType) => {
    const config = {
      wechat: {
        reward: 'wechat_reward_ad_123456',
        feed: 'wechat_feed_ad_654321',
        interstitial: 'wechat_interstitial_ad_789012'
      },
      douyin: {
        reward: 'douyin_reward_ad_abcdef',
        feed: 'douyin_feed_ad_fedcba',
        interstitial: 'douyin_interstitial_ad_123abc'
      },
      h5: {
        reward: 'h5_reward_ad_123',
        feed: 'h5_feed_ad_456',
        interstitial: 'h5_interstitial_ad_789'
      }
    }
    
    return config[platform]?.[adType]
  }

  return { 
    showRewardAd, 
    showFeedAd,
    showInterstitialAd
  }
}