import axios from 'axios'
import qs from 'qs'
import user from '@/state/user'
import { getApp } from '@/app'
import { openLoading, closeLoading } from './loading'
import { openErrorMsg } from './errorMsg'
import { 
  fromUrls, 
  fileUrls, 
  GetUrls, 
  PostUrls, 
  notLoginUrls, 
  HdUrls, 
  getAuthConfig, 
  FileFlow,
  RedirctUrls,
  RedirctPageUrls
} from './config'
import {
  normalizePagesContent,
  normalizeResponse,
  normalizeRequest
} from './normalizeRedirct'
import devData from './simulation.dev'

const gotoLoginCodes = [2001,3004,2005]

axios.defaults.baseURL =  process.env.VUE_APP_PREFIX

axios.interceptors.request.use(async config => {
  const app = getApp()

  if (!user.value.token && !~notLoginUrls.indexOf(config.url)) {
    app.$router.replace({name: 'login'})
    throw '用户未登录'
  }

  config.headers.token = user.value.token || ''
  config.headers.userid = user.value.info.id

  
  if (~RedirctUrls.indexOf(config.url)) {
    config = await normalizeRequest(config)
  }

  if (~HdUrls.indexOf(config.url)) {
    let { data } = await axios.post(getAuthConfig, config.data)
    config.data = {
      client_code: process.env.VUE_APP_HD_CODE, 
      req_time: data.timeStamp,
      authcode: data.authcode,
      ...config.data
    }
  }

  if (~GetUrls.indexOf(config.url)) {
    config.method = 'GET'
  } else if (~PostUrls.indexOf(config.url)) {
    config.method = 'POST'
    if (!config.data && config.params) {
      config.data = config.params 
    }
  }

  // 处理需要用表单上传的请求
  if (~fromUrls.indexOf(config.url)) {

    config.data = qs.stringify(config.data)
    config.headers['Content-Type'] = "application/x-www-form-urlencoded; charset=utf-8;"

  } else if (~fileUrls.indexOf(config.url)) {
    const fromData = new FormData()

    Object.keys(config.data).forEach(key => {
      fromData.append(key, config.data[key])
    })
    config.data = fromData
    config.headers['Content-Type'] = "multipart/form-data"
  }

  openLoading(config.url)
  return config
})

const resInterceptor = res => {
  const app = getApp()
  
  closeLoading()

  if (~FileFlow.indexOf(res.config.url)) {
    return res
  }
  
  if (~RedirctUrls.indexOf(res.config.url)) {
    res = normalizeResponse(res)
  }

  if (~RedirctPageUrls.indexOf(res.config.url)) {
    res = normalizePagesContent(res)
  }
  if(res.config.responseType == "blob" &&  res.status == 200){//下载文件流
    return res.data
  }
  if (res.data.code !== 0 && res.data.code !== "000000" && res.data.code !== 200) {
    if (~gotoLoginCodes.indexOf(res.data.code)) {
      app.$router.replace({name: 'login'})
      user.value.token = ''
    } else if (process.env.NODE_ENV == 'development' && devData[res.config.url]) {
      return devData[res.config.url]()
    }
    let errMsg = res.data.msg || res.data.message || '请求失败，服务端发生了点小故障！'
    openErrorMsg(errMsg)

    throw res.data.msg
  }
  return res.data
}

axios.interceptors.response.use(resInterceptor, (error) => {
  closeLoading()
  if (error.response && error.response.data) {
    return resInterceptor(error.response || '请求失败，服务端发生了点小故障！')
  } else {
    openErrorMsg(typeof error === 'string' ? error : '请求失败，服务端发生了点小故障！')
    return Promise.reject(error);
  }
  
})

