import axios from "axios"
import store from "@/store/index.js"

axios.interceptors.response.use(function (response) {
  // 2xx 范围内的状态码都会触发该函数。
  if (response.data.code === 5001 || response.data.code === 5002) {
    console.log('post message.....')
    window.parent.postMessage('token invalid')
    return Promise.reject('登录态过期')
  }
  return response
}, function (error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  console.log(error)
  console.log('post message.....')
  window.parent.postMessage('token invalid')
  return Promise.reject('调用接口出错')
})

export default {
  async getAnswerRecord() {
    const lastToken = localStorage.getItem('token')
    const res = await axios({
      method: 'get',
      url: `${process.env.VUE_APP_API_PREFIX}/api/cms/question/getListByUser`,
      headers: {
        token: lastToken,
      }
    })
    return res.data.data
  },
  async submitAnswer(isCorrect, id, selectedOptions, badgeType) {
    const lastToken = localStorage.getItem('token')
    const res = await axios({
      method: 'post',
      url: `${process.env.VUE_APP_API_PREFIX}/api/cms/question/submit`,
      headers: {
        token: lastToken,
      },
      data: {
        hasRight: isCorrect,
        num: id,
        options: JSON.stringify(selectedOptions),
        type: badgeType.join(','),
      }
    })
    return res.data.data
  },
}