import axios from 'axios'
import router from '@/router'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { AxiosConfigTy, AxiosReqTy, ObjTy } from '~/common'
import { useUserStore } from '@/store/user'
let reqConfig: any
let loadingE: any

const service: any = axios.create()

// 请求拦截
service.interceptors.request.use(
  (request: AxiosReqTy) => {
    // token setting
    request.headers['token'] = getToken()
    /* download file*/
    if (request.isDownLoadFile) {
      request.responseType = 'blob'
    }
    /* upload file*/
    if (request.isUploadFile) {
      request.headers['Content-Type'] = 'application/json'
    }
    reqConfig = request
    if (request.bfLoading) {
      loadingE = ElLoading.service({
        lock: true,
        text: '数据载入中',
        // spinner: 'el-icon-ElLoading',
        background: 'rgba(0, 0, 0, 0.1)',
      })
    }
    /*
     *params会拼接到url上
     * */
    if (request.isParams) {
      request.params = request.data
      request.data = {}
    }
    return request
  },
  (err: any) => {
    Promise.reject(err)
  }
)
// 响应拦截
service.interceptors.response.use(
  (response) => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code != '0') {
      ElMessage({
        message: '执行失败',
        type: 'error',
        duration: 5 * 1000,
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 500 || res.code === 50012 || res.code === 50014) {
        // to re-login
        ElMessageBox.confirm(
          'You have been logged out, you can cancel to stay on this page, or log in again',
          'Confirm logout',
          {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
        ).then(async () => {
          sessionStorage.removeItem('userName')
          // store.dispatch("app/toggleOutflag", false);
          await useUserStore().logout()
          router.push(`/login`)
        })
      }
      return Promise.reject(res.message || res.returnData?.message || 'Error')
    } else {
      return res
    }
  },
  (error) => {
    const des500 = `${error}`.split(' ').includes('500')
    if (des500) {
      ElMessage({
        message: '身份令牌过期或失效，即将重新登录',
        type: 'error',
        duration: 3 * 1000,
        onClose: async () => {
          sessionStorage.clear()
          removeToken() // must remove  token  first
          removeToken('codeToken')
          removeToken('systemSet')
          removeToken('userid')
          // store.dispatch('app/toggleOutflag', false)
          // await store.dispatch('user/resetToken')
          useUserStore().resetState()
          router.push(`/login`)
          location.reload()
        },
      })
    } else {
      ElMessage({
        message: error.message,
        type: 'error',
        duration: 5 * 1000,
      })
    }
    return Promise.reject(error)
  }
)

export function axiosReq({
  url,
  data,
  method,
  headers,
  isParams,
  bfLoading,
  afHLoading,
  isUploadFile,
  isDownLoadFile,
  baseURL,
  timeout,
  isAlertErrorMsg = true,
}: AxiosConfigTy): any {
  return service({
    url: url,
    method: method ?? 'get',
    data: data ?? {},
    headers: headers ?? {},
    isParams: isParams ?? false,
    bfLoading: bfLoading ?? false,
    afHLoading: afHLoading ?? true,
    isUploadFile: isUploadFile ?? false,
    isDownLoadFile: isDownLoadFile ?? false,
    isAlertErrorMsg: isAlertErrorMsg,
    // baseURL: baseURL ?? import.meta.env.VITE_APP_BASE_URL,
    baseURL: baseURL ?? PLATFROM_CONFIG.baseNewUrl,
    timeout: timeout ?? 15000,
  })
}

export default axiosReq
