const Fly = require("flyio/dist/npm/wx") 
import Env from './Env'
import $n from './nothing'
import store from '../store'
const request = new Fly
/**
 * 请求拦截
 */
request.interceptors.request.use((config, promise) => {
  //超时设置
  if (config._timeout) config.timeout = 60000;
  //从环境变量中取 BASE_UR
  if (process.env.NODE_ENV === 'development') config.baseURL = Env.getDevBaseURL()
  else config.baseURL = Env.getBaseURL()
  //JSON格式化，未指定时，默认true
  config.parseJson = $n._isNotNull(config.parseJson) ? config.parseJson : true
  //如指定_token == true，则在headers中跟上相关token信息
  if (config._token) config.headers['token'] = store.getters.appUser.token;
  //console.warn('####### API Request: ', config)
  return config
})

/**
 * 响应拦截
 */
request.interceptors.response.use(
  (response, promise) => {
    let data = response.data || {status: false, errorMsg: '服务器未响应结果'}
    //console.warn('####### API Response: ', data)
    if (data.code == 401 || data.code == 403) {
    	uni.showModal({
    		title: '',
    		content: '登录超时，请重新登录！',
    		showCancel: false,
    		success: (res) => {
    			uni.navigateTo({ url: '/pages/login/login' })
    		}
    	})
    } else return promise.resolve(data)
  },
  (error, promise) => {
    let msg = $n._caseValue(error.code, 0, '网络连接异常', 1, '网络连接超时', 401, '请求服务未授权', error.msg)
    //console.error('####### API Response error: ', error)
    if (error.status == 401 ) {
		uni.showModal({
			title: '',
			content: '登录超时，请重新登录！',
			showCancel: false,
			success: (res) => {
				uni.navigateTo({ url: '/pages/login/login' })
			}
		})
	}else if(error.status == 500){
		uni.showModal({
			title: '',
			content: '服务器异常,状态=500' ,
			showCancel: false,
		})
	 } else return promise.reject(msg)
  },
  
)
export default request