import unirequest from '../plugins/uni_request.js'
import store from "../store";
// import { autoAuth } from '@/utils/common.js';
import md5 from 'js-md5';
import {
	uniShowToast,
	successToast,
	loadingToast,
	uniHideToast,
	uniHideLoading,
	uniShowModal
} from './uni_api'
import {
	VUE_APP_URL
} from '../config.js'
// 初始化自定义参数 login 是否需要登录权限  cancel 是否取消上次请求
const defaultOptions = {
	login: true,
	auth: false,
	cancel: false,
	loading: true, //是否显示 请求加载中
	warn: true //是否异常弹窗提示
};
// 初始化请求
let instance = unirequest.create({
	baseURL: VUE_APP_URL,
	timeout: 100000,
	debug: true
});
let setCancel;
// 请求拦截器
instance.interceptors.request.use(
	config => {
		var token = store.state.token;//'7221b77a-899b-492b-8263-9507f5c470e9';// store.state.token
		//console.log("frontlixiangsid:"+token);
		config.header['frontlixiangsid']= token;//登录token 标志id
		config.header['platType']= 'slb';
		config.header['mpType'] = 'engineer';
		config.header['appType'] = 'ma';
		config.cancelToken = new unirequest.CancelToken(function executor(c) {
			setCancel = c; //记录当前请求
		});
		config.timeStamp= new Date().getTime();
		var jsToken ="";//防重复提交
		jsToken = md5(JSON.stringify(config))
		console.log('jsToken' + jsToken);
		console.log(config);
		config.data['tokenId'] = jsToken;
		return config
	})
// 响应拦截器
instance.interceptors.response.use(
	response => {
		// console.log('响应成功', response)
		return response
	})
	
	
	// 读取cookie   
	function getCookie(cookie,c_name) {
	    if (cookie && cookie.length > 0){
	       let c_start = cookie.indexOf(c_name + "=")           
	        if (c_start != -1){ 
	            c_start = c_start + c_name.length + 1 
	           let c_end = cookie.indexOf(";", c_start) 
	            if (c_end == -1)   
	                c_end = cookie.length   
	                return unescape(cookie.substring(c_start, c_end))   
	            } 
	        } 
	    return "" 
	}
	
// 请求主体
function baseRequest(config, options) {
	const {
		login,
		auth,
		cancel,
		loading = true,
		warn
	} = options;
	if (options.cancel) {
		cancelRequest()
	}
	loadingStatus(loading, true)
	if (login && !store.state.token) {
		loadingStatus(loading, false);
		// autoAuth();
	}

	
	return instance.request(config).then(res => {
		if(config.url==='/slbMpAutoLogin'||config.url==='/slbSmLogin'){
			try{
			  
			  var cookie = res.header["set-cookie"]||res.header["Set-Cookie"];
			  let frontId = res.data.resultMap?(res.data.resultMap.frontlixiangsid||''):'';
			  let frontlixiangsid = getCookie(cookie,"frontlixiangsid")||frontId;
			  
			   if(frontlixiangsid=='deleteMe'&&frontId){
				   frontlixiangsid = frontId;
			   }
			 if(frontlixiangsid&&frontlixiangsid!='deleteMe'){
				 // uni.setStorageSync('frontlixiangsid',frontlixiangsid)
						  store.state.token = frontlixiangsid;
						  
			 }	
			}catch(err){
				console.log(err);
			}
		}
		
		
		//console.log(config);
		loadingStatus(loading, false)
		//console.log(res);
		 
		if (res.statusCode) {
			let data = res.data;
			console.log('instance.request',res);
				console.log('instance.request data',data);
			if (res.statusCode === 200) {
				console.log('instance.request data 1',data);
				if (data.state == 1) {
					return Promise.resolve(data);
				}
				else if(data.msg&&(data.msg=='请勿频繁操作'||data.msg.indexOf('不能再次使用')>-1)){
					uniShowToast(data.msg);
					return;
				}
				else if(data._redirect||data.msg=='未登录'){
					uni.removeStorageSync('userNo');
					// if(uni.getStorageSync('userNo')){
					// 	uniShowModal('', '账号过期,重新登录?', {
					// 		showCancel: true,
					// 		success: (res) => {
					// 			if(res.confirm){
					// 				//添加跳转 微信绑定公众号页面
					// 				uni.redirectTo({
					// 					url: '/pages/login/login'
					// 				});
					// 			}else{
					// 				return Promise.resolve(data);
					// 			}
					// 		}
					// 	})
					// }
					 
					// store.commit("LOGOUT");
					// uni.reLaunch({
					// 	url: '/pages/index/auth'
					// });
					return Promise.resolve(data);
				}else if (data.state == -1) {
					return Promise.resolve(data);
				}
				else if(data=='' || data=='success'|| data._redirect){
					console.log('instance.request data 2',data);
					// store.commit("LOGOUT");
					//未登录
					
					if (!store.state.isGOAuth) {
						store.commit("SET_GO_AUTH", true);
						//判断是否是第一次加载第一次加载未登录不用弹框提醒
						if(store.state.isFirstLoad){
							store.state.isFirstLoad=false;
							uni.redirectTo({
								url: '/pages/Login/Login'
							});
							return;
						}else{
							store.state.isFirstLoad=false;
							uniShowModal('', '账号过期重新登录认证', {
								showCancel: false,
								success: (res) => {
									//添加跳转 微信绑定公众号页面
									uni.redirectTo({
										url: '/pages/auth/auth'
									});
								}
							})
							return;
						}
						
					} else {
								console.log('路由已存在，不再重复跳转')
								return;
							}
					
					data.msg='未登录';
					return Promise.reject(data);
						
				} else {
						console.log('instance.request data 3',data);
						//data.state == -301||
					if(data.msg == undefined){
						if(uni.getStorageSync("loginFlag")){
							uni.redirectTo({
							  url: "/pages/Login/Login"
							});
						}
						return;
					}
					
					if (warn) {
					uni.redirectTo({
						url: '/pages/error/error?code='+data.state+'&msg='+data.msg
					});
					return;
					}
					
					return Promise.resolve(data);
				}
				return Promise.resolve(res.data);
			} else {
				if (warn) {
					responseError({
						code: res.statusCode
					})
				}
				return Promise.reject(res.data);
			}
		} else {
			
			return Promise.reject(res.data);
		}
		loadingStatus(loading, false);
	}).catch(err => {
		
		loadingStatus(loading, false)
		// if (warn) {
		uniShowToast(err)
		// }
		return Promise.reject(err);
		
	})
}

function cancelRequest() {
	if (typeof setCancel === 'function') {
		setCancel('取消请求')
	}
	loadingStatus(loading, false);
}
// 定义请求提示
const loadingStatus = (loading, type) => {
	if (loading) {
		if (type) {
			// loadingToast('正在请求中');
			// setTimeout(function () {
			//    uniHideLoading();
			// }, 5000);//防水异常加载不关闭影响操作
		} else {
			// uniHideLoading();
		}
	} else {
		return
	}
}
// 请求返回statusCode
const responseError = ({
	code
}) => {
	let content = '';
	switch (code) {
		case 400:
			content = '请求参数错误';
			break
		case 401:
			content = '未授权,请重新登录-401';
			break
		case 403:
			content = '没有访问权限-403';
			break
		case 404:
			content = '请求错误,未找到该资源-404';
			break
		case 405:
			content = '请求方式错误-405';
			break
		case 408:
			content = '请求超时';
			break
		case 500:
			content = '服务器异常-500';
			break
		case 501:
			content = '服务未实现';
			break
		case 502:
			content = '网关错误';
			break
		case 503:
			content = '服务不可用';
			break
		case 504:
			content = '网关超时';
			break
		case 505:
			content = 'HTTP版本不受支持';
			break
		default:
			content = '请求异常-' + code;
			break
	}
	uniShowModal('', content, {
		showCancel: false,
		success: (res) => {
			console.log(res)
		}
	})
}
const request = ['get', 'post', 'put', 'delete', 'connect', 'head', 'options', 'trace'].reduce((request, method) => {
	request[method] = (url, data, options = {}) => baseRequest({
		url,
		method,
		data
	}, { ...defaultOptions,
		...options
	});

	return request;
}, {});

export default request;
