import { request } from '@/utils/request'

export const readingService = {
  // 保存阅读进度
  async saveProgress(progress) {
    // 本地保存
    const key = `progress_${progress.novelId}_${progress.chapterId}`
    uni.setStorageSync(key, JSON.stringify(progress))
    
    // 用户登录时同步到服务器
    if (uni.getStorageSync('token')) {
      try {
        await request({
          url: '/reading/progress',
          method: 'POST',
          data: progress,
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${uni.getStorageSync('token')}`
          }
        })
      } catch (e) {
        console.error('进度同步失败', e)
      }
    }
  },
  
  // 获取阅读进度
  async getProgress(novelId, chapterId) {
    // 优先从本地获取
    const key = `progress_${novelId}_${chapterId}`
    const localData = uni.getStorageSync(key)
    if (localData) {
      return JSON.parse(localData)
    }
    
    // 用户登录时从服务器获取
    if (uni.getStorageSync('token')) {
      try {
        const res = await request({
          url: `/reading/progress?novelId=${novelId}&chapterId=${chapterId}`,
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${uni.getStorageSync('token')}`
          }
        })
        
        if (res.data.success) {
          return res.data.data
        }
      } catch (e) {
        console.error('进度获取失败', e)
      }
    }
    
    return null
  },
  
  // 同步所有本地进度
  async syncAllLocalProgress() {
    if (!uni.getStorageSync('token')) return
    
    const allKeys = uni.getStorageInfoSync().keys
    const progressKeys = allKeys.filter(key => key.startsWith('progress_'))
    
    for (const key of progressKeys) {
      const progress = JSON.parse(uni.getStorageSync(key))
      try {
        await request({
          url: '/reading/progress',
          method: 'POST',
          data: progress,
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${uni.getStorageSync('token')}`
          }
        })
        
        // 同步成功后移除本地记录
        uni.removeStorageSync(key)
      } catch (e) {
        console.error(`进度同步失败: ${key}`, e)
      }
    }
  }
}