/**
 * PK Mini 模块 API
 * 使用独立的 axios 实例，指向 pk.hanxiaokj.cn
 */
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { ENV } from '@/config'

// 创建独立的 axios 实例
const pkAxios = axios.create({
  baseURL: ENV.PK_MINI_API_URL + '/',
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - PK Mini 后端使用 vvtoken 请求头
pkAxios.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers['vvtoken'] = token
  } else {
    // 兼容：尝试从 user_data 获取
    const userData = JSON.parse(localStorage.getItem('user_data') || '{}')
    if (userData.tokenValue) {
      config.headers['vvtoken'] = userData.tokenValue
    }
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

// 响应拦截器
pkAxios.interceptors.response.use((response) => {
  return addPrefixToHeaderIcon(response.data)
}, (error) => {
  return Promise.reject(error)
})

// 处理 headerIcon 的前缀和 country 的翻译
function addPrefixToHeaderIcon(data) {
  const PREFIX = 'https://vv-1317974657.cos.ap-shanghai.myqcloud.com/headerIcon/'

  if (Array.isArray(data)) {
    data.forEach(item => addPrefixToHeaderIcon(item))
    return data
  }

  if (typeof data === 'object' && data !== null) {
    for (const key in data) {
      if ((key === 'headerIcon' || key === 'anchorIcon') && data.hasOwnProperty(key)) {
        const value = data[key]
        // 如果已经是完整 URL，不再添加前缀
        if (typeof value === 'string' && (value.startsWith('http://') || value.startsWith('https://'))) {
          // 已经是完整 URL，不处理
        } else if (value) {
          // 只有文件名，添加前缀
          data[key] = PREFIX + String(value)
        }
      } else if (typeof data[key] === 'object' && data[key] !== null) {
        addPrefixToHeaderIcon(data[key])
      }
    }
  }
  return data
}

// GET 请求
function getAxios({ url, params }) {
  return new Promise((resolve, reject) => {
    pkAxios.get(url, { params }).then(res => {
      if (res.code == 200) {
        resolve(res.data)
      } else {
        ElMessage.error(res.code + ' ' + res.msg)
        reject(res)
      }
    }).catch(err => {
      reject(err)
    })
  })
}

// POST 请求
function postAxios({ url, data }) {
  return new Promise((resolve, reject) => {
    pkAxios.post(url, data).then(res => {
      if (res.code == 200) {
        resolve(res.data)
      } else {
        ElMessage.error(res.code + ' ' + res.msg)
        reject(res)
      }
    }).catch(err => {
      reject(err)
    })
  })
}

// API 接口导出
export function getUserInfo(data) {
  return postAxios({ url: 'user/getUserInfo', data })
}

export function editUserInfo(data) {
  return postAxios({ url: 'user/updateUserInfo', data })
}

export function getPkList(data) {
  return postAxios({ url: 'pk/pkList', data })
}

export function getNoticeList(data) {
  return postAxios({ url: 'systemMessage/list', data })
}

export function getAnchorList(data) {
  return postAxios({ url: 'anchor/list', data })
}

export function addAnchor(data) {
  return postAxios({ url: 'anchor/add', data })
}

export function delAnchor(data) {
  return postAxios({ url: 'anchor/deleteMyAnchor', data })
}

export function editAnchor(data) {
  return postAxios({ url: 'anchor/updateAnchorInfo', data })
}

export function getAnchorAvatar(data) {
  const url = 'https://python.yolojt.com/api/' + data.name
  // 使用原生 fetch 避免全局 axios 拦截器干扰
  return new Promise((resolve, reject) => {
    fetch(url)
      .then(response => response.json())
      .then(result => {
        if (result.code == 200) {
          resolve(result.data)
        } else {
          reject(result)
        }
      })
      .catch(err => {
        reject(err)
      })
  })
}

export function getPkInfo(data) {
  return postAxios({ url: 'user/queryMyAllPkData', data })
}

export function releasePkInfo(data) {
  return postAxios({ url: 'pk/addPkData', data })
}

export function editPkInfo(data) {
  return postAxios({ url: 'pk/updatePkInfoById', data })
}

export function delPkInfo(data) {
  return postAxios({ url: 'pk/deletePkDataWithId', data })
}

export function topPkInfo(data) {
  return postAxios({ url: 'user/pinToTop', data })
}

export function cancelTopPkInfo(data) {
  return postAxios({ url: 'user/cancelPin', data })
}

export function getIntegralDetail(data) {
  return postAxios({ url: 'user/pointsDetail', data })
}

export function getPkRecord(data) {
  return postAxios({ url: 'user/handlePkInfo', data })
}

export function signIn(data) {
  return postAxios({ url: 'user/signIn', data })
}

export function editEmail(data) {
  return postAxios({ url: 'user/updateUserMail', data })
}

export function getOtp() {
  return getAxios({ url: 'otp/getotp' })
}

export function getAnchorListById(data) {
  return postAxios({ url: 'pk/listUninvitedPublishedAnchorsByUserId', data })
}

export function createPkRecord(data) {
  return postAxios({ url: 'pk/createPkRecord', data })
}

export function queryPkRecord(data) {
  return postAxios({ url: 'pk/singleRecord', data })
}

export function pkArticleDetail(data) {
  return postAxios({ url: 'pk/pkInfoDetail', data })
}

export function updatePkRecordStatus(data) {
  return postAxios({ url: 'pk/updatePkStatus', data })
}

export function queryPkDetail(data) {
  return postAxios({ url: 'pk/fetchDetailPkDataWithId', data })
}

export function resendEmail(data) {
  return postAxios({ url: 'user/resendMail', data })
}

export function logout(data) {
  return postAxios({ url: 'user/logout', data })
}
// 获取商品列表
export function getPkItemList(data) {
  return getAxios({ url: 'pkItem/list', params: data })
}

// 购买商品
export function buyPkItem(data) {
  return postAxios({ url: 'pkItem/buy', data })
}