import axios from 'axios'
import { getChromeStorage } from '@/uilts/chromeExtension.js'
import { baseAPIUrl, appVersionCode } from '@/http/configAPI.js'

let userInfo = '';
let storage_mid = ''

// 创建axios实例
export const service = axios.create({
  baseURL: baseAPIUrl, // api的base_url
  timeout: 240000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json', //指定消息格式
    'Accept': 'application/json',
  },
})

function checkParams(config) {
  const { accessToken: token = '', uid = '' } = userInfo || {};
  const { mid } = storage_mid || {};

  if (config.method === 'get') {
    let { baseInfo = null } = config.params || {};
    let params = {
      ...config.params
    }

    let { pageSource } = params.params || {};
    if (pageSource) {
      delete params.params.pageSource;
    }

    if (!baseInfo || !baseInfo.token) {
      params['baseInfo'] = {
        token: token,
        mid,
        appVersionCode,
        loginUid: uid,
        uid,
        appType: 1,
        machineCode: mid,
        pageSource: pageSource || ''
      }
    }
    config['params'] = params;
  }

  if (config.method === 'post') {
    let { baseInfo = null } = config.data || {};
    let data = {
      ...config.data
    }
    let { pageSource } = data.params || {};
    if (pageSource) {
      delete data.params.pageSource;
    }

    if (!baseInfo || !baseInfo.token) {
      data['baseInfo'] = {
        token: token,
        mid,
        appVersionCode,
        loginUid: uid,
        uid,
        appType: 1,
        machineCode: mid,
        pageSource: pageSource || ''
      }
    }
    config['data'] = data;
  }
  return config
}

// request拦截器
service.interceptors.request.use(async (config) => {
  userInfo = await getChromeStorage('userInfo') || ''
  if (!storage_mid) {
    storage_mid = await getChromeStorage('mid') || ''
  }
  return checkParams(config)
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    switch (res.code.toString()) {
      // twitter授权失效
      case '1003':
        chrome.storage.local.remove("userInfo");
        chrome.runtime.sendMessage(
          { actionType: "POPUP_LOGIN", data: "" },
          (response) => {
            console.log("res", response);
          }
        )
        break;
      // 登陆token失效
      case '-107':
        chrome.storage.local.remove("userInfo");
        chrome.runtime.sendMessage(
          { actionType: "POPUP_LOGIN", data: "" },
          (response) => {
            console.log("res", response);
          }
        )
        break;
    }
    return res
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)
