// import common = require("./common");
const appid = 'wxefa2810018787a41'

const language = 'zh'

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 === 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);
		uni.reLaunch({
			url: '/pages/index/index'
		});
		return false;
	}

	return true;
}

function getRequest(url, data, successCallBack, failCallBack) {
// 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
	}
	uni.request({
		url: url,
		method: 'GET',
		success: function(res) {
			uni.hideLoading();

			if (_checkTokenValid(res)) {
				successCallBack(res);
			}
		},
		fail: function(res) {
			uni.hideLoading();

			if (!(res.errMsg.indexOf('interrupted') != -1)) {
				uni.showModal({
					title: '错误',
					content: '网络错误' + res.errMsg,
					showCancel: false
				});
			}

			if (failCallBack) failCallBack(res);
		}
	});
}

function postRequest(url, data, successCallBack, failCallBack) {
	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()
	if (!failCallBack) failCallBack = function() {}
	var token = storage.getUserToken()
	
	// 申请拖车服务接口加密签名校验
	// if (url === config.API_DAYHIRE_DRAG_CAR_SERVICE) {
		data.sign = sign
	// }
	
	uni.request({
		url: url,
		data: data,
		header: {
			'content-type': 'application/json',
			'X-Token': token
		},
		method: 'POST',
		success: function(res) {
			//wx.hideLoading();
			if (res.data.code == 200) {
				res.succeed = true
				res.body = res.data
			} else {
				uni.showToast({ title: res.data.msg, icon: 'none' })
			}
			if (_checkTokenValid(res)) {
				successCallBack(res);
			}
		},
		fail: function(res) {
			uni.hideLoading();

			if (!(res.errMsg.indexOf('interrupted') != -1)) {
				uni.showModal({
					title: '错误',
					content: '网络错误' + res.errMsg,
					showCancel: false
				});
			}

			failCallBack(res);
		}
	});
}

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
}

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

function postApi(url, data, successCallBack, failCallBack) {
	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
	//#ifdef MP-ALIPAY
	data.from = 'ali'
	//#endif
	//#ifdef MP-WEIXIN
	data.from = 'wx'
	//#endif
	data.language = language
	postRequest(url, data, successCallBack, failCallBack);
}
/**
 * 上报formid
 */

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

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


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