import store from "@/store";
import cryptoUtils from "@/utils/cryptoUtils";
let Message = vant.Toast

function redirectToLogin() {
	if(process.env.VUE_APP_ALIAS != 'xz'){
		store.dispatch('LogOut').then(()=>{
			let protocol = window.location.protocol,
			host = window.location.host,
			pathname = window.location.pathname
			location.href = `${protocol}//${host}${pathname}#/login?openid=${store.getters.user.openid||''}`
		})
	} else {

	}
}

const service = ({url, method, headers, data, params, noMesg}) => {
    return new Promise((resolve, reject) => {
        var userAgent = "{}"
        if(store.getters.user && store.getters.user.id){
			var userAgent = {
				uname: encodeURIComponent(store.getters.user.name),
				uid: store.getters.user.id
			}
            userAgent = JSON.stringify(userAgent)
		}
		

        let _headers = Object.assign({
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
            "login-device": "mobile",
            "userAgent": userAgent,
            "token": store.getters.user.accessToken
        }, headers)

        var d = data || params || {}
        d = {
            object: cryptoUtils.Encrypt(JSON.stringify(d)),
            t: new Date().getTime()
        }
        mui.ajax(`${process.env.VUE_APP_BASE_API}${url}`,{
            data: d,
            dataType:'json',//服务器返回json格式数据
            type: method,//HTTP请求类型
            timeout:60000,//超时时间设置为10秒；
            headers: _headers,
            processData: headers && (headers.processData === "false" || headers.processData === false)? false: true,
            success:function(response){
                response = JSON.parse(cryptoUtils.Decrypt(response.data))
                if(response.status==1300){
                    Message("验证码错误")
                    reject(response);
                } else if(response.status == 1100) {
                    Message("登录已失效，请重新登录")
                    setTimeout(() => {
                        redirectToLogin()
                    }, 1000)
                    reject(response);
                } else if(response.status == 1000) { //用户不存在
                    redirectToLogin()
                } else if(response.status == 1104 || response.status == 999) { //该账号在其它地方登录
                    Message("该账号在其它地方登录，请重新登录");
                    setTimeout(() => {
                        redirectToLogin()
                    }, 1000)
                } else if (response.status != 200) {
                    if(!noMesg){  //status 非200并且不需要提示的则传noMesg
                        Message(response.message || "系统异常");
                    }
                    console.error(response)
                    reject(response)
                } else {
                    resolve(response)
                }
            },
            error:function(xhr,type,errorThrown){
                console.log("err" + type); // for debug
                Message("服务端异常")
                reject(type);
            }
        });
    })
}

export default service;


// im
const imService = ({url, method, headers, data, params}) => {
    return new Promise((resolve, reject) => {

        mui.ajax(`${process.env.VUE_APP_ENV=="production"? eval("("+ process.env.VUE_APP_IM_API +")")() : process.env.VUE_APP_IM_API}${url}`,{
            data: Object.assign({}, (method&&method.toLowerCase()==="get")?params:data, {_t: new Date().getTime()}),
            dataType:'json',//服务器返回json格式数据
            type: method,//HTTP请求类型
            timeout:20000,//超时时间设置为10秒	 
            headers: headers, 
            processData: headers && (headers.processData === "false" || headers.processData === false)? false: true,         
            success:function(response){
                resolve(response)
            },
            error:function(xhr,type,errorThrown){
                console.log("err" + type); // for debug
                reject(type);
            }
        });
    })
}

export {
	imService
};