import Taro, { useRouter } from '@tarojs/taro'
import Axios from 'axios'
import { OPEN_ID_STORAGE_KEY } from '../constant'
import { getUserInfo } from '../utils/auth'
import sign from './sign'

const whitePageList = [
  'pages/dashboard/index',
  'pages/contact/index',
  'pages/index/index',
  'pages/knowledge/index',
]

const axiosIns = Axios.create({
  siren: false,
})


export const getSimpleHeader = () => {
  const headers = {}
  const userInfo = getUserInfo()
  headers['X-Enniu-End'] = 'mp'
  if (userInfo.userId && userInfo.token) {
    headers.userId = `${userInfo.userId}`
    headers.Authorization = `encrypt ${userInfo.token}`
  }
  return headers
};

export const getHeaders = async (config) => {
  const userInfo = await getUserInfo()
  // console.log('userInfo', userInfo)
  config.params = config.params || {}
  config.headers = config.headers || {}
  config.headers['X-Enniu-End'] = 'mp'
  if (userInfo.userId && userInfo.token) {
    config.headers.userId = `${userInfo.userId}`
    config.headers.Authorization = `encrypt ${userInfo.token}`
  }
  const openId = Taro.getStorageInfoSync(OPEN_ID_STORAGE_KEY)
  config.headers.openId = `${openId}`
  await sign(config)
  return config
};

axiosIns.interceptors.request.use(async (config) => {

  try {
    return getHeaders(config)
  } catch (e) {
    console.log(e)
  }
})

axiosIns.interceptors.response.use(
  (response) => {
    if (response.headers && response.headers.token && response.headers.userId) {
      Taro.setStorageSync('hasLogin', '1') // 已经登录过，可以认为微信号跟手机号绑定了，后面可以只授权微信信息登录
      Taro.setStorageSync('u51UserId', response.headers.userId)
      Taro.setStorageSync('u51UserToken', response.headers.token)
    }
    return response
  },
  async (err) => {
    console.log(err)
    const config = err.config
    let error = {}
    //   if (ignoreError((err.config || {}).url)) {
    //     return Promise.reject(err)
    //   }
    if (err.response && err.response.data) {
      error = err.response.data.errors
        ? err.response.data.errors[0]
        : err.response.data
    }
    if (error.code === 401) {
      Taro.setStorageSync('hasLogin', '0')
      // 如果在非白名单页，则需要跳转 '我的' 页登录
      // 白名单页，不跳转，自行处理登录逻辑
      const pages = Taro.getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentRoute = currentPage.route;
      console.log(currentRoute)
      if (!whitePageList.includes(currentRoute)) {
        Taro.switchTab({
          url: '/pages/personal/index',
        });
      }
      return Promise.reject(error)
    } else if (error.code === 1020 || error.code === 1021) {
      return error
    } else if (
      error &&
      error.message &&
      error.message.indexOf('timeout') === 0
    ) {
      if (!config.omitError) {
        Taro.showToast({
          title: '网络异常',
          icon: 'none',
        })
      }
    } else if (error.message) {
      if (!config.omitError) {
        Taro.showToast({
          title: error.message,
          icon: 'none',
        })
      }
    } else {
      if (!config.omitError) {
        Taro.showToast({
          title: '出了点问题，暂时加载不出来，请稍后再来吧',
          icon: 'none',
        })
      }
    }
    return Promise.reject(err)
  },
)

export default axiosIns
