import {
	getCache
} from './authority';
import config from './config';
import SM2 from './sm2';
import {
	getUrlParams
} from './tools';

export const HttpRequest = function(url, method, data) {
	return new Promise((resolve, reject) => {
		const token = getCache('token');
		let _header = {}
		if (url.includes("/auth/loginByPwd") || url.includes("/auth/logout")) {
			_header = {
				'content-type': 'application/json',
			};
		} else {
			_header = {
				'content-type': 'application/json',
				'Authorization': token
			};
		}
		let endata = null;
		if (method.toLowerCase() == "get") {
			if (url.includes("?")) {
				let nurl = url.substring(0, url.indexOf("?") + 1);
				var params = getUrlParams(url);
				for (const key in params) {
					let keyData = params[key];
					if (params.hasOwnProperty(key)) {
						if (nurl.toLowerCase().endsWith("?")) {
							nurl += key + "=" + SM2.sm2Encrypt(keyData, config.sm2PublicKey);
						} else {
							nurl += "&" + key + "=" + SM2.sm2Encrypt(keyData, config.sm2PublicKey);
						}
					}
				}
				url = nurl;
			} else {
				let nurl = url;
				if(data){
					if (Object.keys(data).length > 0) {
						nurl = url + "?";
					}
					Object.keys(data).forEach((key) => {
						let keyData = data[key];
						if (data.hasOwnProperty(key)) {
							if (nurl.toLowerCase().endsWith("?")) {
								nurl += key + "=" + SM2.sm2Encrypt(keyData, config.sm2PublicKey);
							} else {
								nurl += "&" + key + "=" + SM2.sm2Encrypt(keyData, config.sm2PublicKey);
							}
						}
					});
				}
				url = nurl;
			}
		} else {
			if (data["content-type"]) {
				if (data["content-type"] == "application/x-www-form-urlencoded") {
					_header = {
						'content-type': 'application/x-www-form-urlencoded',
						'Authorization': token
					};
					let formData = new Formdata();
					Object.keys(data).forEach((key) => {
						if (key.toLowerCase() == "content-type") return false;
						let enKeyData = SM2.sm2Encrypt(data[key], config.sm2PublicKey)
						formData.append(key, enKeyData);
					});
					endata = formData;
				}
			} else {
				endata = SM2.sm2Encrypt(JSON.stringify(data), config.sm2PublicKey);
			}
		}
		uni.request({
			url: url,
			data: endata,
			method: method,
			header: _header,
			success: (res) => { //请求成功
				if (res.statusCode == 200) { //成功 
					resolve(res.data);
				} else { //失败 
					reject(res);
				}
			},
			fail: (err) => { //请求失败 
				reject(err);
			}
		})
	})
}


export const HttpFileUpload = function(url,file) {
	return new Promise((resolve, reject) => {
		 uni.uploadFile({
		    url: url ,
		    filePath: file.path, // 选择的文件路径
		    name: 'multipartFile', // 后端接收文件时的字段名，通常是 'file'
		    formData: { 
		    },
		    success: (res) => { 
		      if (res.statusCode == 200) { //成功
		      	resolve(JSON.parse(res.data));
		      } else { //失败 
		      	reject(res);
		      }
		    },
		    fail: (err) => {
		      console.log('上传失败:', err);
		    }
		  });
	})

}