import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/router'
import { useShopStore } from '@/store/Shop'
import { showToast, showLoadingToast } from 'vant'

import NProgress from "nprogress";
import "nprogress/nprogress.css";

const ajax = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL,
  withCredentials: true,
  timeout: 30000
})

export const request = (url, method = 'GET', params = {}, config = {}) => {

  method = method.toUpperCase()
  switch (method) {
    case 'GET':
      return ajax.get(url, { params, ...config })
    case 'POST':
      return ajax.post(url, params, config)
    default:
      return ajax.get(url, { params, ...config })
  }
}

ajax.interceptors.request.use(
  (config) => {
    if (config.requestBase == 'sso') {
      console.log('sso', import.meta.env.VITE_APP_SSO_URL)
      config.baseURL = import.meta.env.VITE_APP_SSO_URL
    }

    if (Cookies.get('token')) {
      config.headers.Authorization = Cookies.get('token')
    }
    if (Cookies.get('SessionId')) {
      config.headers.SessionId = Cookies.get('SessionId')
    }
    NProgress.start()
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

ajax.interceptors.response.use(
  (response) => {
    NProgress.done()
    refreshToken(response)
    return response.data
  },
  (error) => {
    NProgress.done()
    if (error.response) {
      switch (error.response.status) {
        case 401:
          let shopStore = useShopStore()
          Cookies.remove('token', { expires: 365, domain: shopStore.sso_domain })
          Cookies.remove('uid', { expires: 365, domain: shopStore.sso_domain })

          return router.replace({
            path: '/login',
            query: { redirect: router.currentRoute.fullPath }
          })
      }
    }
    if (error.code === 'ERR_NETWORK') {
      return showToast('網路錯誤，請檢查是否上網')
    }
    if (error.code === 'ECONNABORTED') {
      showToast('網路逾時，請重試')
    }
    return Promise.reject(error);
  }
)

function refreshToken(response) {
  let token = response.headers.authorization
  if (token) {
    Cookies.set('token', res.data.token, { expires: 30, domain: useShopStore.sso_domain })
  }
}
