/*
 * @Author: your name
 * @Date: 2021-06-19 16:20:37
 * @LastEditTime: 2021-12-27 15:02:33
 * @LastEditors: 许宏杰
 * @Description: In User Settings Edit
 * @FilePath: \MuduAPP\src\api\request.js
 */

// import Vue from 'vue';
import router from '../router'

import axios from 'axios'
import { Toast } from 'vant'

import { refreshToken, isRefreshRequest } from '@/util/refresh2.js'

// 实例化axios
const request = axios.create({
  baseURL: process.env.VUE_APP_RUOYI,
  timeout: 50000,
})

// request--请求 拦截器
request.interceptors.request.use(
  (config) => {
    if (config.url !== 'secret/token') {
      let token = localStorage.getItem('mudu2_token')
      let authToken = 'Bearer ' + token
      config.headers['Authorization'] = authToken
    }
    //POST和PUT的请求参数转为formData
    // if (config.method === 'post' || config.method === 'put') {
    //   if (config.url !== 'attachment/uploadimagefile') {
    //     config.headers['Content-Type'] = 'multipart/form-data'
    //     let params = config.data
    //     // debugger
    //     const formData = new FormData()
    //     Object.keys(params).forEach((key) => {
    //       //参数为null或者'null'时候不传入后台
    //       if (params[key] && params[key] !== 'null')
    //         formData.append(key, params[key])
    //     })
    //     config.data = formData
    //   }
    // }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// response--响应 拦截器
request.interceptors.response.use(
  async (response) => {
    let errorData = response

    if (errorData.data.code === 401 && !isRefreshRequest(errorData.config)) {
      const isSucceed = await refreshToken()
      if (isSucceed) {
        //重新请求
        // console.log('重新刷新')
        errorData.config.headers.Authorization =
          'Bearer ' + localStorage.getItem('mudu2_token') //替换token
        let result = await request.request(errorData.config) //重新请求
        return result
      } else {
        Toast({
          message: '刷新令牌失败',
          position: 'bottom',
        })
      }
    }
    // 系统返回状态判断
    if (response.data.code === 500) {
      Toast({
        message: response.data.message,
        position: 'bottom',
      })
      // router.replace('/')
      return Promise.reject(response.data)
    } else if (response.data.code !== 200) {
      // 没有查询到附件的不显示消息
      if (response.data.message !== '没有查询到附件') {
        let message = response.data.message
        // 如果消息为空，显示为暂无数据
        if (message.length === 0) message = '暂无数据'
        Toast({
          message: message,
          position: 'bottom',
        })
      }
      return Promise.reject(response.data)
    } else {
      // 以下是正确的数据判断
      return response.data
    }
  },
  (error) => {
    // console.log(error.response)
    if (error.response && error.response.status === 401) {
      Toast({
        message: '登录过期，请重新登录',
        position: 'bottom',
      })
      localStorage.removeItem('HISTORY_ACTIVE')
      localStorage.removeItem('mudu_token')
      localStorage.removeItem('mudu_username')
      localStorage.removeItem('mudu_userInfo')
      localStorage.removeItem('mudu_userId')
      localStorage.removeItem('mudu_type')
      router.replace('/')
    } else {
      Toast({
        message: '网络异常，请检查网络情况',
        position: 'bottom',
      })
      router.replace('/')
    }
    return Promise.reject(error)
  }
)
export { request }
