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

// 广告平台配置
const AD_PLATFORMS = {
  WECHAT: {
    reward: adUnitId => wx.createRewardedVideoAd({ adUnitId }),
    feed: adUnitId => wx.createBannerAd({ adUnitId })
  },
  DOUYIN: {
    reward: adUnitId => tt.createRewardedVideoAd({ adUnitId }),
    feed: adUnitId => tt.createBannerAd({ adUnitId })
  },
  H5: {
    reward: adUnitId => {
      console.log('H5激励广告:', adUnitId)
      return { show: () => Promise.resolve() }
    },
    feed: adUnitId => {
      return { show: () => console.log('H5信息流广告展示') }
    }
  }
}

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

  // 展示激励广告（每5章触发）
  const showRewardAd = async (chapterId) => {
    if (userStore.isVIP) return
    
    chapterCount.value++
    if (chapterCount.value % 5 !== 0) return
    
    const adapter = getPlatformAdapter()
    const ad = adapter.reward('your_ad_unit_id')
    
    try {
      await ad.show()
      logAdView(chapterId, 'reward')
    } catch (err) {
      console.error('广告展示失败:', err)
    }
  }

  // 展示底部信息流广告
  const showFeedAd = () => {
    if (userStore.isVIP) return null
    
    const adapter = getPlatformAdapter()
    return adapter.feed('your_feed_ad_id')
  }

  // 广告日志记录（对接Java接口）
  const logAdView = (chapterId, adType) => {
    uni.request({
      url: 'https://api.aiyadianzi.ltd/ad/log',
      method: 'POST',
      data: {
        userId: userStore.userId,
        chapterId,
        adType,
        platform: process.env.VUE_APP_PLATFORM
      }
    })
  }

  return { showRewardAd, showFeedAd }
}