/**
 * API 接口配置文件
 */

// 开发环境和生产环境的 API 基础地址
// 所有请求通过网关转发
const BASE_URL = process.env.NODE_ENV === 'development' 
  ? 'http://localhost:8083/api'  // 开发环境 - 通过网关
  : 'https://your-domain.com/api'  // 生产环境

/**
 * 封装 uni.request
 */
const request = (options) => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    const headers = {
      'Content-Type': 'application/json'
    }
    if (token) {
      headers['Authorization'] = token
    }
    uni.request({
      url: (/^https?:\/\//.test(options.url) ? options.url : (BASE_URL + options.url)),
      method: options.method || 'GET',
      data: options.data || {},
      header: headers,
      dataType: 'json',
      success: (res) => {
        if (res.statusCode === 200) {
          // 根据后端约定的数据格式处理
          if (res.data.code === 200 || res.data.code === 0 || res.data.success) {
            resolve(res.data.data || res.data)
          } else {
            uni.showToast({
              title: res.data.message || '请求失败',
              icon: 'none'
            })
            reject(res.data)
          }
        } else if (res.statusCode === 401) {
          // 未授权，跳转登录
          uni.navigateTo({
            url: '/pages/page3/page3'
          })
          reject(res)
        } else {
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (err) => {
        uni.showToast({
          title: (err && err.errMsg) ? err.errMsg.replace('request:','') : '网络连接失败',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

/**
 * API 接口列表
 */
export default {
  // 地区
  area: {
    // 获取省份列表
    getProvinces: () => request({ url: '/recommend/area/provinces' }),
    // 获取城市列表（可选省份ID）
    getCities: (provinceId) => {
      const url = provinceId ? `/recommend/area/cities?provinceId=${provinceId}` : '/recommend/area/cities'
      return request({ url })
    },
    // 获取区域列表（根据城市ID）
    getAreas: (cityId) => request({ url: `/recommend/area/areas?cityId=${cityId}` })
  },
  // 用户相关
  user: {
    // 获取用户信息
    getInfo: () => request({ url: '/user/info' }),
    
    // 获取指定用户的详细信息（包含简介和照片）
    getDetailInfo: (userId) => request({ 
      url: `/user/info?userId=${userId}` 
    }),
    
    // 获取今日匹配数
    getMatchCount: () => request({ url: '/user/match-count' }),
    
    // 更新用户基本信息（昵称、头像等）
    updateInfo: (data) => request({ 
      url: '/user/basic', 
      method: 'PUT', 
      data 
    }),
    
    // 更新单个字段
    updateField: (userId, fieldName, fieldValue) => request({
      url: `/user/basic/field?userId=${userId}&fieldName=${fieldName}&fieldValue=${encodeURIComponent(fieldValue)}`,
      method: 'PUT'
    })
  },

  // 认证相关
  auth: {
    // 密码登录（手机号+密码）
    loginByPassword: (phone, password) => request({
      // 直连 login 服务（开发环境），避免网关未配置导致未路由
      url: 'http://localhost:8087/api/login/password',
      method: 'POST',
      data: { phone, password }
    }),

    // 发送登录验证码（走网关 -> 登录服务）
    sendCode: (phone) => request({
      url: '/login/send-code',
      method: 'POST',
      data: { phone }
    }),

    // 验证码登录（走网关 -> 登录服务）
    smsLogin: (phone, code) => request({
      url: '/login/sms-login',
      method: 'POST',
      data: { phone, code }
    }),

    // 微信登录（直连 login 服务以便开发环境不依赖 appid/secret 配置）
    wechatLogin: (data) => request({
      url: 'http://localhost:8087/api/login/wechat/login',
      method: 'POST',
      data: data  // ✅ 传递完整的登录数据对象（包含code, nickname, avatarUrl, phoneCode）
    }),

    // 获取微信手机号（直连 login 服务）
    wechatPhone: (code) => request({
      url: 'http://localhost:8087/api/login/wechat/phone',
      method: 'POST',
      data: { code }
    })
  },

  // 首页相关
  home: {
    // 获取轮播图
    getBanners: () => request({ url: '/home/banners' }),
    
    // 获取公告列表
    getNotices: () => request({ url: '/announcement/active' }),
    
    // 获取未读消息数
    getUnreadCount: () => request({ url: '/home/unread-count' })
  },

  // 成功案例
  successCase: {
    // 获取成功案例列表
    getList: (params) => request({ 
      url: '/success-case/list',
      method: 'GET',
      data: params 
    }),
    
    // 获取成功案例详情
    getDetail: (caseNo) => request({ 
      url: `/success-case/detail/${caseNo}`,
      method: 'GET'
    }),
    
    // 获取案例时间线
    getTimeline: (caseNo) => request({ 
      url: `/success-case/timeline/${caseNo}`,
      method: 'GET'
    })
  },

  // 活动相关
  activity: {
    // 获取活动列表
    getList: (params) => request({ 
      url: '/activity/list',
      method: 'GET',
      data: params 
    }),
    
    // 获取活动详情
    getDetail: (id) => request({ 
      url: `/activity/detail/${id}`,
      method: 'GET'
    }),
    
    // 报名活动
    register: (activityId, userId) => request({ 
      url: `/activity/register/${activityId}?userId=${userId}`, 
      method: 'POST'
    }),
    
    // 取消报名
    cancelRegister: (activityId) => request({ 
      url: `/activity/cancel/${activityId}`, 
      method: 'POST' 
    })
  },

  // 课程相关
  course: {
    // 获取课程列表
    getList: (params) => request({ 
      url: '/course/list',
      method: 'GET',
      data: params 
    }),
    
    // 获取课程详情
    getDetail: (id) => request({ 
      url: `/course/detail/${id}`,
      method: 'GET'
    }),
    
    // 购买课程
    purchase: (courseId, data) => request({ 
      url: `/course/purchase/${courseId}`, 
      method: 'POST', 
      data 
    })
  },

  // 红娘相关
  matchmaker: {
    // 获取红娘列表
    getList: (params) => request({ 
      url: '/matchmaker/list', 
      method: 'POST',
      data: params 
    }),
    
    // 获取全职红娘列表
    getFormalList: (pageNum, pageSize) => request({ 
      url: `/matchmaker/formal?pageNum=${pageNum}&pageSize=${pageSize}` 
    }),
    
    // 获取红娘详情
    getDetail: (id) => request({ 
      url: `/matchmaker/detail/${id}` 
    }),
    
    // 预约红娘
    book: (matchmakerId, data) => request({ 
      url: `/matchmaker/book/${matchmakerId}`, 
      method: 'POST', 
      data 
    })
  },

  // 推荐相关
  recommend: {
    // 获取推荐用户列表（网关转发到推荐服务）
    getUsers: ({ userId, oppoOnly = 1, limit = 20 }) => request({
      url: `/recommend/users?userId=${userId}&oppoOnly=${oppoOnly}&limit=${limit}`
    }),
    // 行为反馈：like/dislike
    feedback: ({ userId, targetUserId, type }) => request({
      url: `/recommend/feedback?userId=${userId}&targetUserId=${targetUserId}&type=${type}`
    }),
    // 曝光上报
    exposure: ({ userId, shownUserIds }) => request({
      url: `/recommend/exposure?userId=${userId}&shownUserIds=${encodeURIComponent(shownUserIds)}`
    }),
    // 规则检索
    search: (query) => request({
      url: '/recommend/search',
      method: 'POST',
      data: query
    }),
    // 获取今日推荐
    getTodayRecommend: () => request({ 
      url: '/recommend/today' 
    })
  },

  // 消息相关
  message: {
    // 获取消息列表
    getList: (params) => request({ 
      url: '/message/list', 
      data: params 
    }),
    
    // 获取会话列表
    getConversations: () => request({ 
      url: '/message/conversations' 
    }),
    
    // 发送消息
    send: (data) => request({ 
      url: '/message/send', 
      method: 'POST', 
      data 
    }),

    // ===== 系统消息 =====
    getSystemList: async (userId, pageNum = 1, pageSize = 20) => {
      const res = await request({ url: `/message/system/list?userId=${userId}&pageNum=${pageNum}&pageSize=${pageSize}` })
      // 后端Result包装：{ code, data:{ list,total,page,pageSize } }
      return res.data || res
    },
    getSystemUnreadCount: async (userId) => {
      const res = await request({ url: `/message/system/unread-count?userId=${userId}` })
      return (typeof res.data === 'number') ? res.data : (res.data?.count || 0)
    },
    markSystemRead: (id) => request({
      url: `/message/system/read/${id}`,
      method: 'POST'
    }),
    getSystemDetail: async (id) => {
      const res = await request({ url: `/message/system/detail/${id}` })
      return res.data || res
    },
    markAllSystemRead: (userId) => request({
      url: `/message/system/read-all?userId=${userId}`,
      method: 'POST'
    })
  },

  // 动态相关
  dynamic: {
    // 获取推荐动态列表（广场）
    getRecommendList: (params) => request({
      url: '/dynamic/recommend',
      data: params
    }),

    // 获取动态列表
    getList: (params) => request({
      url: '/dynamic/list',
      data: params
    }),

    // 获取动态详情
    getDetail: (dynamicId, userId) => request({
      url: `/dynamic/detail/${dynamicId}`,
      data: { userId }
    }),
    // 发表评论
    addComment: (dynamicId, content, images, parentCommentId = 0) => request({
      url: `/dynamic/comment`,
      method: 'POST',
      data: { dynamicId, content, images, parentCommentId, userId: 1 },
      header: { 'Content-Type': 'application/json' }
    }),

    // 评论列表
    getComments: (dynamicId, pageNum = 1, pageSize = 10) => request({
      url: `/dynamic/comment/list/${dynamicId}`,
      data: { pageNum, pageSize }
    }),

    // 评论点赞/取消
    likeComment: (commentId) => request({
      url: `/dynamic/comment/like?commentId=${commentId}&userId=1`,
      method: 'POST'
    }),
    unlikeComment: (commentId) => request({
      url: `/dynamic/comment/like/${commentId}?userId=1`,
      method: 'DELETE'
    }),


    // 获取用户动态列表
    getUserDynamics: (userId, params) => {
      const { pageNum = 1, pageSize = 10, currentUserId = null } = params || {}
      let url = `/dynamic/user/${userId}?pageNum=${pageNum}&pageSize=${pageSize}`
      if (currentUserId) {
        url += `&currentUserId=${currentUserId}`
      }
      return request({
        url: url,
        method: 'GET'
      })
    },

    // 点赞动态
    like: (dynamicId) => request({
      url: `/dynamic/like?dynamicId=${dynamicId}&userId=1`,
      method: 'POST'
    }),

    // 取消点赞
    unlike: (dynamicId) => request({
      url: `/dynamic/like/${dynamicId}`,
      method: 'DELETE'
    }),

    // 收藏动态
    favorite: (dynamicId) => request({
      url: `/dynamic/favorite?dynamicId=${dynamicId}&userId=1`,
      method: 'POST'
    }),

    // 取消收藏
    unfavorite: (dynamicId) => request({
      url: `/dynamic/favorite/${dynamicId}`,
      method: 'DELETE'
    }),

    // 发布动态
    // publish: (data) => request({
    //   url: '/dynamic/publish',
    //   method: 'POST',
    //   data
    // }),

    // 删除动态
    delete: (dynamicId) => request({
      url: `/dynamic/${dynamicId}`,
      method: 'DELETE'
    }),

    // 发布动态（文本或已存在的媒体URL列表）
    publish: (payload) => request({
      url: '/dynamic/publish',
      method: 'POST',
      data: payload,
      header: { 'Content-Type': 'application/json' }
    }),

    // 单个文件上传方法
    uploadSingle: (filePath) => {
      return new Promise((resolve, reject) => {
        console.log('开始上传文件:', filePath)
        console.log('上传URL:', BASE_URL + '/dynamic/publish/upload')

        uni.uploadFile({
          url: BASE_URL + '/dynamic/publish/upload',
          filePath: filePath,
          name: 'file',
          success: (res) => {
            console.log('上传响应:', res)
            try {
              const data = JSON.parse(res.data)
              console.log('解析后的响应数据:', data)

              if (data.code === 200 || data.code === 0 || data.success) {
                console.log('上传成功，返回URL:', data.data)
                resolve(data.data)
              } else {
                console.error('上传失败，服务器返回错误:', data)
                reject(new Error(data.message || '上传失败'))
              }
            } catch (e) {
              console.error('解析响应数据失败:', e, '原始响应:', res.data)
              reject(new Error('解析响应数据失败'))
            }
          },
          fail: (error) => {
            console.error('上传请求失败:', error)
            reject(new Error('上传请求失败: ' + (error.errMsg || '未知错误')))
          }
        })
      })
    },

    // 批量上传多个文件（遍历调用单个上传）
    uploadBatch: (filePaths) => {
      return new Promise(async (resolve, reject) => {
        const urls = []
        try {
          for (let filePath of filePaths) {
            const url = await new Promise((resolveUpload, rejectUpload) => {
              uni.uploadFile({
                url: BASE_URL + '/dynamic/publish/upload',
                filePath: filePath,
                name: 'file',
                success: (res) => {
                  try {
                    const data = JSON.parse(res.data)
                    if (data.code === 200 || data.code === 0 || data.success) {
                      resolveUpload(data.data)
                    } else {
                      rejectUpload(data)
                    }
                  } catch (e) {
                    rejectUpload(e)
                  }
                },
                fail: rejectUpload
              })
            })
            urls.push(url)
          }
          resolve(urls)
        } catch (e) {
          reject(new Error(`批量上传失败: ${e.message || '未知错误'}`))
        }
      })
    },

    // 提交举报
    submitReport: (data) => request({
      url: '/dynamic/report',
      method: 'POST',
      data
    }),
    
    // 获取用户收藏列表
    getFavoritesList: (userId, pageNum = 1, pageSize = 10) => request({
      url: `/dynamic/favorites?userId=${userId}&pageNum=${pageNum}&pageSize=${pageSize}`
    }),
    
    // 获取用户点赞列表
    getLikedList: (userId, pageNum = 1, pageSize = 10) => request({
      url: `/dynamic/likes?userId=${userId}&pageNum=${pageNum}&pageSize=${pageSize}`
    }),
    
    // 获取用户浏览记录列表
    getBrowseHistoryList: (userId, pageNum = 1, pageSize = 10) => request({
      url: `/dynamic/browse-history?userId=${userId}&pageNum=${pageNum}&pageSize=${pageSize}`
    }),
    
    // 清空用户浏览记录
    clearBrowseHistory: (userId) => request({
      url: `/dynamic/browse-history?userId=${userId}`,
      method: 'DELETE'
    })
  },
  vip: {
      // 获取VIP信息（状态、套餐等）
      getInfo: (userId) => request({ 
        url: `/vip/info?userId=${userId}` 
      }),
      
      // 获取VIP套餐列表
      getPackages: () => request({ 
        url: '/vip/packages' 
      }),
      
      // 购买VIP套餐（获取支付参数）
      purchase: (userId, packageId) => request({ 
        url: '/vip/purchase', 
        method: 'POST', 
        data: { userId, packageId } 
      }),
      
      // 查询订单状态
      getOrderStatus: (orderNo) => request({ 
        url: `/vip/order/status?orderNo=${orderNo}` 
      })
    }
}

// 导出 request 函数供其他模块使用
export { request }
