import axios from 'axios'

// 创建大乐透专用的axios实例
const dltApi = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 300000, // 5分钟超时时间
  withCredentials: true, // 关键：支持跨域携带cookie和session
  headers: {
    'Content-Type': 'application/json'
  }
})

// 响应拦截器
dltApi.interceptors.response.use(
  response => {
    const data = response.data
    
    // 检查是否是session过期的响应
    if (data && data.success === false) {
      const message = data.message || ''
      
      // 专门处理账号在其他设备登录的情况
      if (message.includes('其他设备登录') || message.includes('当前会话已失效')) {
        console.log('检测到账号在其他设备登录，正在踢出当前会话...')
        
        import('element-plus').then(({ ElMessage }) => {
          ElMessage.warning({
            message: '您的账号已在其他设备登录，请重新登录',
            duration: 3000,
            showClose: true
          })
        })
        
        import('../../store/user.js').then(({ userStore }) => {
          userStore.logout(true)
        })
        return data
      }
      
      if (message.includes('未登录') || message.includes('登录过期') || message.includes('无权限') || message.includes('Invalid session')) {
        console.log('检测到session过期，清除本地登录状态')
        
        import('../../store/user.js').then(({ userStore }) => {
          userStore.logout()
        })
      }
    }
    
    return data
  },
  error => {
    console.error('大乐透API请求错误:', error)
    
    // 检查HTTP状态码，401/403通常表示未授权/session过期
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      console.log('检测到401/403错误，可能是session过期或无权限')
      
      // 动态导入userStore避免循环依赖
      import('../../store/user.js').then(({ userStore }) => {
        userStore.logout()
      })
    }
    
    return Promise.reject(error)
  }
)

// 大乐透API接口方法
export const dltLotteryApi = {
  // 获取近10期大乐透开奖期号
  getRecent10DrawIds() {
    return dltApi.get('/dlt-draw/recent-10-draw-ids')
  },

  // 根据期号获取大乐透开奖号码
  getDrawNumbersById(drawId) {
    return dltApi.get(`/dlt-draw/draw/${drawId}/numbers`)
  },

  // 大乐透前区首球分析
  analyzeFrontBalls(level, frontBalls, backBalls) {
    return dltApi.post('/dlt/ball-analysis/predict-first-ball', {
      level,
      redBalls: frontBalls, // 前区球
      blueBalls: backBalls  // 后区球
    })
  },

  // 大乐透前区随球分析
  analyzeFollowFrontBalls(level, wellRegardedBalls, previousFrontBalls, previousBackBalls) {
    return dltApi.post('/dlt/ball-analysis/predict-follower-ball', {
      level,
      wellRegardedBalls,
      previousFrontBalls,
      previousBackBalls
    })
  },

  // 大乐透后区球分析
  analyzeBackBalls(level, nextFrontBalls, previousFrontBalls, previousBackBalls, nextBackBalls) {
    return dltApi.post('/dlt/ball-analysis/predict-back-ball', {
      level,
      nextFrontBalls,
      previousFrontBalls,
      previousBackBalls,
      nextBackBalls
    })
  },

  // 大乐透后区随球分析
  analyzeFollowBackBalls(level, backFirstBall, nextFrontBalls, previousFrontBalls, previousBackBalls) {
    return dltApi.post('/dlt/ball-analysis/predict-follow-back-ball', {
      level,
      backFirstBall,
      nextFrontBalls,
      previousFrontBalls,
      previousBackBalls
    })
  },

  // 创建大乐透推测记录
  createPredictRecord(userId, drawId, drawDate, frontBalls, backBalls) {
    return dltApi.post('/dlt/ball-analysis/create-predict', {
      userId,
      drawId,
      drawDate,
      frontBalls: frontBalls.join(','),
      backBalls: backBalls.join(',')
    })
  },

  // 获取大乐透推测记录
  getPredictRecordsByUserId(userId, page = 1) {
    return dltApi.get(`/dlt/ball-analysis/predict-records/${userId}?page=${page}`)
  },

  // 获取近期大乐透开奖记录
  getRecentDraws(limit = 10) {
    return dltApi.get(`/dlt-draw/recent-draws?limit=${limit}`)
  },

  // 根据期号获取大乐透开奖记录
  getDrawById(drawId) {
    return dltApi.get(`/dlt-draw/draw/${drawId}`)
  },

  // 根据日期范围查询大乐透开奖记录
  queryDraws(startDate, endDate) {
    return dltApi.get(`/dlt-draw/query-draws?startDate=${startDate}&endDate=${endDate}`)
  },

  // 获取近100期大乐透开奖记录（用于表相查询）
  getRecent100Draws() {
    return dltApi.get('/dlt-draw/recent-100-draws')
  },

  // 创建大乐透预测记录（新接口）
  createDltPredictRecord(userId, drawId, frontBalls, backBalls, drawDate = null) {
    const params = new URLSearchParams({
      userId: userId,
      drawId: drawId,
      frontBalls: frontBalls,
      backBalls: backBalls
    })
    
    if (drawDate) {
      params.append('drawDate', drawDate)
    }
    
    return dltApi.post(`/dlt/ball-analysis/create-dlt-predict?${params.toString()}`)
  },

  // 前区与前区的组合性分析
  frontFrontCombinationAnalysis(masterBall, slaveBall) {
    return dltApi.get(`/dlt/ball-analysis/front-front-combination-analysis?masterBall=${masterBall}&slaveBall=${slaveBall}`)
  },

  // 前区与后区的组合性分析
  frontBackCombinationAnalysis(masterBall, slaveBall) {
    return dltApi.get(`/dlt/ball-analysis/front-back-combination-analysis?masterBall=${masterBall}&slaveBall=${slaveBall}`)
  },

  // 后区与后区的组合性分析
  backBackCombinationAnalysis(masterBall, slaveBall) {
    return dltApi.get(`/dlt/ball-analysis/back-back-combination-analysis?masterBall=${masterBall}&slaveBall=${slaveBall}`)
  },

  // 后区与前区的组合性分析
  backFrontCombinationAnalysis(masterBall, slaveBall) {
    return dltApi.get(`/dlt/ball-analysis/back-front-combination-analysis?masterBall=${masterBall}&slaveBall=${slaveBall}`)
  },

  // 前区与前区的持续性分析
  frontFrontPersistenceAnalysis(masterBall, slaveBall) {
    return dltApi.get(`/dlt/ball-analysis/front-front-persistence-analysis?masterBall=${masterBall}&slaveBall=${slaveBall}`)
  },

  // 后区与后区的持续性分析
  backBackPersistenceAnalysis(masterBall, slaveBall) {
    return dltApi.get(`/dlt/ball-analysis/back-back-persistence-analysis?masterBall=${masterBall}&slaveBall=${slaveBall}`)
  },

  // 前区与后区的持续性分析
  frontBackPersistenceAnalysis(masterBall, slaveBall) {
    return dltApi.get(`/dlt/ball-analysis/front-back-persistence-analysis?masterBall=${masterBall}&slaveBall=${slaveBall}`)
  },

  // 后区与前区的持续性分析
  backFrontPersistenceAnalysis(masterBall, slaveBall) {
    return dltApi.get(`/dlt/ball-analysis/back-front-persistence-analysis?masterBall=${masterBall}&slaveBall=${slaveBall}`)
  },

  // 根据用户ID获取大乐透预测记录（新接口）
  getDltPredictRecordsByUserId(userId, page = 1, pageSize = 10) {
    return dltApi.get(`/dlt-predict/predict-records/${userId}?page=${page}&pageSize=${pageSize}`)
  },

  // 条件查询大乐透预测记录
  queryDltPredictRecords(userId, predictStatus, page = 1, pageSize = 10) {
    return dltApi.post('/dlt-predict/query-predict-records', {
      userId: userId,
      predictStatus: predictStatus,
      current: page,
      pageSize: pageSize
    })
  },

  // 前区历史数据查询
  getFrontendHistoryAll() {
    return dltApi.get('/dlt/ball-active-analysis/frontend-history-all')
  },

  getFrontendHistory100() {
    return dltApi.get('/dlt/ball-active-analysis/frontend-history-100')
  },

  getFrontendHistoryTop() {
    return dltApi.get('/dlt/ball-active-analysis/frontend-history-top')
  },

  getFrontendHistoryTop100() {
    return dltApi.get('/dlt/ball-active-analysis/frontend-history-top-100')
  },

  // 后区历史数据查询
  getBackendHistoryAll() {
    return dltApi.get('/dlt/ball-active-analysis/backend-history-all')
  },

  getBackendHistory100() {
    return dltApi.get('/dlt/ball-active-analysis/backend-history-100')
  },

  getBackendHistoryTop() {
    return dltApi.get('/dlt/ball-active-analysis/backend-history-top')
  },

  getBackendHistoryTop100() {
    return dltApi.get('/dlt/ball-active-analysis/backend-history-top-100')
  },

  // Excel数据导入相关API
  // 上传Excel文件完整导入大乐透数据（D3-D12工作表）
  uploadDltExcelFile(file) {
    const formData = new FormData()
    formData.append('file', file)
    return dltApi.post('/dlt/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 上传Excel文件导入大乐透开奖数据（覆盖）（D1工作表）
  uploadDltDrawsFile(file) {
    const formData = new FormData()
    formData.append('file', file)
    return dltApi.post('/dlt/upload-draw-data', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 追加导入大乐透开奖数据（D1工作表）
  appendDltDrawsFile(file) {
    const formData = new FormData()
    formData.append('file', file)
    return dltApi.post('/dlt/append-draw-data', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 手动处理待开奖记录（双色球+大乐透）
  processPendingPredictions() {
    return dltApi.post('/dlt-predict/process-pending')
  },

  // 获取用户大乐透预测统计
  getUserPredictStats(userId) {
    return dltApi.get(`/dlt-predict/user-predict-stat/${userId}`)
  },

  // 获取用户大乐透奖金统计
  getPrizeStatistics(userId) {
    return dltApi.get('/dlt-predict/prize-statistics', {
      params: {
        userId: userId
      }
    })
  },

  // 大乐透命中率分析接口
  // 前区首球命中率分析
  getFrontFirstBallHitRate() {
    return dltApi.get('/dlt-predict/front-first-ball-hit-rate')
  },

  // 前区球号命中率分析
  getFrontBallHitRate() {
    return dltApi.get('/dlt-predict/front-ball-hit-rate')
  },

  // 后区首球命中率分析
  getBackFirstBallHitRate() {
    return dltApi.get('/dlt-predict/back-first-ball-hit-rate')
  },

  // 后区球号命中率分析
  getBackBallHitRate() {
    return dltApi.get('/dlt-predict/back-ball-hit-rate')
  },

  // 精推版大乐透第一步分析
  jtdltFirstStepAnalysis(level, frontBalls, backBalls) {
    const params = new URLSearchParams()
    params.append('level', level)
    params.append('frontBalls', frontBalls)
    params.append('backBalls', backBalls)
    
    return dltApi.post('/jtdlt/analysis/first-step', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },

  // 精推版大乐透第二步分析
  jtdltSecondStepAnalysis(level, previousFrontBalls, previousBackBalls, currentFirstBall) {
    const params = new URLSearchParams()
    params.append('level', level)
    params.append('previousFrontBalls', previousFrontBalls)
    params.append('previousBackBalls', previousBackBalls)
    params.append('currentFirstBall', currentFirstBall)
    
    return dltApi.post('/jtdlt/analysis/second-step', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },

  // 精推版大乐透第三步分析
  jtdltThirdStepAnalysis(level, previousFrontBalls, previousBackBalls, currentFrontBalls) {
    const params = new URLSearchParams()
    params.append('level', level)
    params.append('previousFrontBalls', previousFrontBalls)
    params.append('previousBackBalls', previousBackBalls)
    params.append('currentFrontBalls', currentFrontBalls)
    
    return dltApi.post('/jtdlt/analysis/third-step', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },

  // 精推版大乐透第四步分析
  jtdltFourthStepAnalysis(level, previousFrontBalls, previousBackBalls, currentFrontBalls, currentBackFirstBall) {
    const params = new URLSearchParams()
    params.append('level', level)
    params.append('previousFrontBalls', previousFrontBalls)
    params.append('previousBackBalls', previousBackBalls)
    params.append('currentFrontBalls', currentFrontBalls)
    params.append('currentBackFirstBall', currentBackFirstBall)
    
    return dltApi.post('/jtdlt/analysis/fourth-step', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  }
}

export default dltLotteryApi
