// import common = require("./common");
// const appid = 'wxefa2810018787a41'
import {Language} from '@/utils/util.js'
const appid = '487987498'
const language = Language

var common = require('./common.js');

var storage = require('./storage.js');

var config = require('./config.js'); // 检查token是否失效 如失效 清除缓存 提示重新登录

// 402: 解析token出错  403: token格式错误  404: 公共声明中缺少必要字段  405: token验证失败
import crypto from '@/node_modules/crypto-js';

function _checkTokenValid(res) {
	
	if(res.data.code === 305){
		uni.showToast({
			title:'账号已在其他设备登录！',
			icon:'none'
		})
		return false
	}
	if (
		res.data.code === 402 ||
		res.data.code === 403 ||
		res.data.code === 404 ||
		res.data.code === 405 ||
		res.data.code === 300 ||
		res.data.code === 302 ||
		res.data.code === 303 ||
		res.data.code === 304 ||
		res.data.code === 305 ||
		res.data.code === 306
	) {
		//wx.clearStorageSync();

		//TODO
		// var shareCode = storage.getShareCode();
		// storage.clearStorage();
		// storage.setShareCode(shareCode);
		storage.removeUserToken()
		uni.removeStorageSync('car_info')
		uni.removeStorageSync('USER_INFO_DATA')
		uni.reLaunch({
			url: '/pages/loginRegister/login'
		});
		return false;
	}

	return true;
}

async function getRequest(url, data) {
	// function getRequest(url1, data, successCallBack, failCallBack) {
	// if (!failCallBack) failCallBack = function() {};
	// var url=url1?url1:''
	if (url.indexOf('?') > 0) {
		url = url + '&' + common.obj2UrlQuery(data);
	} else {
		url = '?' + common.obj2UrlQuery(data);
		// return
	}
	let res = await uni.request({
		url: url,
		method: 'GET',
	});
	
	uni.hideLoading();
	 res = res[1]
	 if(!res.data.code){
	 	throw Error(res.data);
	 }
	 if(res.data.code == 200){
		 return res
	 }
	 if(res.data.code === 503){
	 	throw Error(res.data.msg);
		return
	 }
	if (_checkTokenValid(res)) {
		return res
	}
	throw Error(res.data.msg);
}

async function postRequest(url, data ) {
	const datetime = Math.floor(Date.now() / 1000)
	data.time = datetime.toString()
	let jsonStr = JSON.stringify(selfSort(data))
	var encrypted = crypto.SHA256(jsonStr)
	var sign = encrypted.toString()
	var token = storage.getUserToken()
	// 申请拖车服务接口加密签名校验
	// if (url === config.API_DAYHIRE_DRAG_CAR_SERVICE) {
	data.sign = sign
	// }

	let res = await uni.request({
		url: url,
		data: data,
		header: {
			'content-type': 'application/json',
			'X-Token': token
		},
		method: 'POST',
	});
	res = res[1]
	
	wx.hideLoading();
	if(!res.data.code){
		throw Error(res.data);
	}
	if (res.data.code == 200) {
		res.succeed = true
		res.body = res.data
		return res
	}
	if(res.data.code === 503){
		throw Error(res.data.msg);
	}
	if (_checkTokenValid(res)) {
		return res
	}

	throw Error(res.data.msg);
}

function selfSort(data) {
	// console.log(data,"签名数据")
	let sortedKeys = Object.keys(data).sort((a, b) => {
		//对key 进行翻转
		let reversedA = a.split("").reverse().join("");
		let reversedB = b.split("").reverse().join("");
		let len = reversedA.length > reversedB.length ? reversedA.length : reversedB.length

		for (let i = 0; i < len; i++) {
			if (typeof(reversedA[i]) == 'undefined') {
				return 1;
			}
			if (typeof(reversedB[i]) == 'undefined') {
				return -1;
			}
			if (reversedA[i] > reversedB[i]) {
				return -1;
			} else if (reversedB[i] > reversedA[i]) {
				return 1;
			}
		}
		return 1
	}) // 对属性数组进行排序
	let sortedJson = {}; // 重构排序后的JSON对象
	sortedKeys.forEach(key => {
		sortedJson[key] = data[key];
	})
	return sortedJson
}

async function getApi(url, data) {
	var token = storage.getUserToken(); //wx.getStorageSync(config.STORAGE_USER_TOKEN)
	data.token = token;
	data.v = config.APP_VERSION;
	data.appid = appid
	if(!data.from){
		data.from = 'app'
		//#ifdef MP-ALIPAY
		data.from = 'ali'
		//#endif
		//#ifdef MP-WEIXIN
		data.from = 'wx'
		//#endif
	}
	

	data.language = language
	return await getRequest(url, data);
}

async function postApi(url, data) {
	var token = storage.getUserToken(); // wx.getStorageSync(config.STORAGE_USER_TOKEN)
	console.log(data, 'token');
	data.token = token;
	data.v = config.APP_VERSION;
	data.appid = appid
	if(!data.from){
		data.from = 'app'
		//#ifdef MP-ALIPAY
		data.from = 'ali'
		//#endif
		//#ifdef MP-WEIXIN
		data.from = 'wx'
		//#endif
	}
	data.language = language
	return await postRequest(url, data);
}
/**
 * 上报formid
 */

async function reportFormId(formId) {
	const accountInfo = uni.getAccountInfoSync();
	var postData = {
		formId: formId,
		appid
	};
	await postApi(config.API_FORMID_REPORT, postData);
}

async function getAppConfig() {
	const pData = {
		appid,
		terminal: 'wx_app'
	};
	let resp = await getApi(config.API_INDEX_APP_CONFIG, pData);
	if (resp.data.code === 200) {
		const appConfig = resp.data.data.appConfig;
		storage.setAppConfig(appConfig);
		//#ifdef MP-ALIPAY
		uni.setNavigationBarTitle({
			title: ''
		});
		//#endif
		//#ifdef MP-WEIXIN
		wx.setNavigationBarTitle({
			title: appConfig.app_name
		});
		//#endif
		return appConfig
	} else {}
}

module.exports = {
	getRequest: getRequest,
	postRequest: postRequest,
	getApi: getApi,
	postApi: postApi,
	reportFormId: reportFormId,
	getAppConfig: getAppConfig
};