import axios from "axios";
import store from "@/store";
import router from "@/router";
import Qs from "qs";
import cryptoUtils from "@/utils/cryptoUtils";

let Message = vant.Toast

function redirectToLogin() {
	store.dispatch('LogOut').then(()=>{
		router.push({
			path: "/login"
		})
	})
}
var baseURL = process.env.VUE_APP_BASE_API
const service = axios.create({
	baseURL: baseURL, // api 的 base_url
	headers: {
		"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
	},
	timeout: 60000 // request timeout
});

// request interceptor
service.interceptors.request.use(
	config => {
		config.headers["login-device"] = "mobile"
		if(store.getters.user && store.getters.user.id){
			var userAgent = {
				uname: encodeURIComponent(store.getters.user.name),
				uid: store.getters.user.id
			}
			config.headers["userAgent"] = JSON.stringify(userAgent)
		} else {
			config.headers["userAgent"] = "{}"
		}
		
		if(store.getters.user.accessToken){
			config.headers["token"] = store.getters.user.accessToken
		}
		if (config.method === 'post') {
			if (!config.headers['Content-Type'] || config.headers['Content-Type'].indexOf('application/x-www-form-urlencoded') >= 0) {
				config.data = {
					object: cryptoUtils.Encrypt(JSON.stringify(config.data||{})),
					_t: new Date().getTime()
				}
				config.data = Qs.stringify(config.data)
			}
		  } else if (config.method == 'get') {
				config.params = {
					object: cryptoUtils.Encrypt(JSON.stringify(config.params||{})),
					_t: new Date().getTime(),
				}
		  }
		return config;
	},
	error => {
		console.log(error); // for debug
		Promise.reject(error);
	}
);

// response interceptor
service.interceptors.response.use(
	response => {
		var response = {
			status: response.status,
			data: JSON.parse(cryptoUtils.Decrypt(response.data.data)),
			config: response.config
		}
		
		if (response.status == 200) {
			if(response.data.status==1300){
				Message("验证码错误")
                return Promise.reject(response.data);
			} else if(response.data.status == 1100) {
                Message("登录已失效，请重新登录")
                setTimeout(() => {
                    redirectToLogin()
                }, 1000)
                return Promise.reject(response.data);
            } else if(response.data.status == 1000) { //用户不存在
                redirectToLogin()
            } else if(response.data.status == 1104 || response.data.status == 999) { //该账号在其它地方登录
                Message("该账号在其它地方登录，请重新登录");
                setTimeout(() => {
                    redirectToLogin()
                }, 1000)
            } else if (response.data.status != 200) {
				if ((!store.getters.user || !store.getters.user.accessToken)){
					return response.data
				}
				if(!response.config.noMesg){  //status 非200并且不需要提示的则传noMesg
					Message(response.data.message || "系统异常");
				}
				
				return Promise.reject(response.data);
			} else {
				return response.data;
			}
		} else if(response.status == 999){
            Message("该账号在其它地方登录，请重新登录");
            setTimeout(() => {
                redirectToLogin()
            }, 1000)
        }else{
            Message("网络出错");
			return Promise.reject(response.data);
		}
	},
	/**
	 * 下面的注释为通过在response里，自定义code来标示请求状态
	 * 当code返回如下情况则说明权限有问题，登出并返回到登录页
	 * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
	 * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
	 */
	// response => {
	//   const res = response.data
	//   if (res.code !== 20000) {
	//     Message({
	//       message: res.message,
	//       type: 'error',
	//       duration: 5 * 1000
	//     })
	//     // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
	//     if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
	//       // 请自行在引入 MessageBox
	//       // import { Message, MessageBox } from 'element-ui'
	//       MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
	//         confirmButtonText: '重新登录',
	//         cancelButtonText: '取消',
	//         type: 'warning'
	//       }).then(() => {
	//         store.dispatch('FedLogOut').then(() => {
	//           location.reload() // 为了重新实例化vue-router对象 避免bug
	//         })
	//       })
	//     }
	//     return Promise.reject('error')
	//   } else {
	//     return response.data
	//   }
	// },
	error => {
		console.log("err" + error); // for debug
        Message("服务端异常")
		return Promise.reject(error);
	}
);

export default service;



// im
const imService = axios.create({
	baseURL: process.env.VUE_APP_ENV=="production"? eval("("+ process.env.VUE_APP_IM_API +")")() : process.env.VUE_APP_IM_API, // url = base url + request url
	withCredentials: true, // send cookies when cross-domain requests
	timeout: 20000 // request timeout
})
// request interceptor
imService.interceptors.request.use(
	config => {
		// do something before request is sent
		if (config.method === 'post') {
		config.data = {
			...config.data,
			_t: new Date().getTime()
		}
		} else if (config.method == 'get') {
		config.params = {
			_t: new Date().getTime(),
			...config.params
		}
		}
		if (store.getters.user.accessToken) {
		// let each request carry token
		// ['X-Token'] is a custom headers key
		// please modify it according to the actual situation
		// config.headers['X-Token'] = getToken()
		}
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
imService.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	*/

	/**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code
	 */
	response => {
		const res = response.data
		// if the custom code is not 20000, it is judged as an error.
		return res
	},
	error => {
		console.log('err' + error) // for debug
		console.log(error.message.indexOf("timeout") != -1? "服务繁忙" : "服务端异常") // for debug
		Message(error.message.indexOf("timeout") != -1? "服务繁忙" : "服务端异常")
		return Promise.reject(error)
	}
)
export {
	imService
};
