/**
 * AppServer API调用封装
 * @constructor
 */

// import { sj } from "./Sj.js"
import {
	md5
} from "./md5.js"


function objectToQueryParams(obj) {
	return Object.keys(obj).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])).join('&');
}
var AppServer = function() {


}

var serverConfig = {}
//dev-localhost

var baseUrl = 'https://music.shhuanmeng.com'
// var baseUrl = 'http://localhost:90'
// var basePayCenterUrl = 'https://api-pay.hissai.com'
serverConfig.apiUrl_Music_AccountLogIn = baseUrl + '/api/Account/AccountLogIn'
serverConfig.apiUrl_Music_GetMiniProgramUserInfo = baseUrl + '/api/Account/GetMiniProgramUserInfo'

serverConfig.apiUrl_Music_GetMusicGenresList = baseUrl + '/api/Music/GetMusicGenresList'
serverConfig.apiUrl_Music_GetMusicGenresInfo = baseUrl + '/api/Music/GetMusicGenresInfo'
serverConfig.apiUrl_Music_GetUserMusicGenresList = baseUrl + '/api/Music/GetUserMusicGenresList' //音乐标签
serverConfig.apiUrl_Music_CreateUserMusicGenres = baseUrl + '/api/Music/CreateUserMusicGenres' //创建音乐风格
serverConfig.apiUrl_Music_CreateMusic = baseUrl + '/api/Music/CreateMusic' //创建音乐
serverConfig.apiUrl_Music_GetMusicSchedule = baseUrl + '/api/Music/GetMusicSchedule' //获取音乐进度
serverConfig.apiUrl_Music_GetMyMusicList = baseUrl + '/api/Music/GetMyMusicList' //我的音乐列表
serverConfig.apiUrl_Music_GetUserInfo = baseUrl + '/api/Music/GetUserInfo' //用户信息
serverConfig.apiUrl_Music_MusicSongsReview = baseUrl + '/api/Music/MusicSongsReview' //歌曲审核
serverConfig.apiUrl_Music_MusicCancelSongsReview = baseUrl + '/api/Music/MusicCancelSongsReview' //取消审核
serverConfig.apiUrl_Music_GetShopInfoList = baseUrl + '/api/Music/GetShopInfoList' //取消审核


/**
 * 获取完整的application/x-www-form-urlencoded请求参数
 * 1）填充必要的请求参数
 * 2）填充签名
 * @param postData
 */
AppServer.prototype.getPostFormBody = function(postData) {
	var fullPostData = Object.assign({}, postData)

	//补全参数
	// if (!postData.appId) {
	// 	fullPostData.appId = 1002;
	// 	//#ifdef MP-TOUTIAO
	// 	fullPostData.appId = 1004;
	// 	// #endif
	// 	// #ifndef 
	// 	fullPostData.appId = 1002;
	// 	// #endif
	// 	// fullPostData.appId = 1002;

	// }
	// if(!postData.bossId){
	// 	fullPostData.bossId = 0;
	// }
	// if (!postData.userId) {
	// 	let userId = uni.getStorageSync("userId");
	// 	if (userId) {
	// 		fullPostData.userId = userId
	// 	}
	// }
	// console.log("参数", fullPostData);
	//签名
	// fullPostData.sign = this.getSign(fullPostData)
	//url编码
	// var formBody = [];
	// for (var key in fullPostData) {

	// 	var encodedKey = encodeURIComponent(key);
	// 	var encodedValue = encodeURIComponent(fullPostData[key]);
	// 	formBody.push(encodedKey + "=" + encodedValue);
	// }
	// formBody = formBody.join("&");

	// return formBody
}

/**
 * @param {Object} postData
 * 获取参数签名
 */
AppServer.prototype.getSign = function(postData) {
	let arr = [];
	for (let key in postData) {
		if (key == 'sign')
			continue;
		arr.push(key)
	}
	arr.sort();
	let str = '';
	for (let i in arr) {
		let value = postData[arr[i]]
		if (value || value == 0) {
			str += value
		}
	}

	//添加saltKey
	let saltKey = ""
	try {
		let token = uni.getStorageSync("token")
		if (token) {
			saltKey = token.split('.')[2];
		}

	} catch (e) {
		saltKey = ""
	}

	str += saltKey
	let sign = md5(str)
	// console.log("要签名的字符串:" + str + ",sign=" + sign)
	return sign
}
/**
 * 接口请求
 */
AppServer.prototype.postData = async function(url, postData) {
	// var formBody = this.getPostFormBody(postData)
	// console.log(formBody);
	let authToken = uni.getStorageSync("token");

	return uni.request({
			url: url,
			method: 'POST',
			header: {
				'Content-Type': "application/json",
				'Authorization': authToken
			},
			data: JSON.stringify(postData)
		})
		.then((res) => {
			// 此处的 res 参数，与使用默认方式调用时 success 回调中的 res 参数一致
			console.log(`post,url=${url},form=${JSON.stringify(postData)},response=${res.data}`);
			//在这里处理验签失败等问题
			return res.data;
		})
		.catch((err) => {
			// 此处的 err 参数，与使用默认方式调用时 fail 回调中的 err 参数一致
			console.error(err);
			return err;
		});
}

AppServer.prototype.getData = async function(url, postData) {

	let authToken = uni.getStorageSync("token");
	if (postData != null) {
		var parmat = objectToQueryParams(postData);
		if (url.indexOf("?") > -1) {
			url += "&" + parmat;
		} else {
			url += "?" + parmat;
		}
	}

	return uni.request({
			url: url,
			method: 'GET',
			header: {
				'Authorization': authToken
			},
			// data: JSON.stringify(postData)
		})
		.then((res) => {
			// 此处的 res 参数，与使用默认方式调用时 success 回调中的 res 参数一致
			console.log(`post,url=${url},response=${res.data}`);
			//在这里处理验签失败等问题
			return res.data;
		})
		.catch((err) => {
			// 此处的 err 参数，与使用默认方式调用时 fail 回调中的 err 参数一致
			console.error(err);
			return err;
		});
}

/**
 * 
 * @param taskId
 * @param prompt
 * @param steps
 */

AppServer.prototype.GetMusicGenresList = async function() {

	var url = serverConfig.apiUrl_Music_GetMusicGenresList

	return this.getData(url).then((data) => {
		return data;
	})
}

//音乐列表
AppServer.prototype.GetMusicGenresInfo = async function(genresId) {

	var url = serverConfig.apiUrl_Music_GetMusicGenresInfo

	return this.getData(url, {
		"genresId": genresId
	}).then((data) => {
		return data;
	})
}

//创作音乐标签列表
AppServer.prototype.GetUserMusicGenresList = async function() {

	var url = serverConfig.apiUrl_Music_GetUserMusicGenresList

	return this.getData(url).then((data) => {
		return data;
	})
}

//自定义音乐风格
AppServer.prototype.CreateUserMusicGenres = async function(genreName) {

	var url = serverConfig.apiUrl_Music_CreateUserMusicGenres

	return this.postData(url, {
		"genreName": genreName
	}).then((data) => {
		return data;
	})
}

//创建音乐
AppServer.prototype.CreateMusic = async function(genreName, prompt, name) {

	var url = serverConfig.apiUrl_Music_CreateMusic

	return this.postData(url, {
		"genreName": genreName,
		"prompt": prompt,
		"name": name,
	}).then((data) => {
		return data;
	})
}

//获取音乐进度
AppServer.prototype.GetMusicSchedule = async function(id) {

	var url = serverConfig.apiUrl_Music_GetMusicSchedule

	return this.getData(url, {
		"id": id
	}).then((data) => {
		return data;
	})
}

//我的音乐列表
AppServer.prototype.GetMyMusicList = async function() {

	var url = serverConfig.apiUrl_Music_GetMyMusicList

	return this.getData(url).then((data) => {
		return data;
	})
}

//用户信息
AppServer.prototype.GetUserInfo = async function() {

	var url = serverConfig.apiUrl_Music_GetUserInfo

	return this.getData(url).then((data) => {
		return data;
	})
}

//歌曲审核
AppServer.prototype.MusicSongsReview = async function(id) {

	var url = serverConfig.apiUrl_Music_MusicSongsReview

	return this.postData(url, {
		"id": id
	}).then((data) => {
		return data;
	})
}

//取消歌曲审核
AppServer.prototype.MusicCancelSongsReview = async function(id) {

	var url = serverConfig.apiUrl_Music_MusicCancelSongsReview

	return this.postData(url, {
		"id": id
	}).then((data) => {
		return data;
	})
}

//取消歌曲审核
AppServer.prototype.GetShopInfoList = async function() {

	var url = serverConfig.apiUrl_Music_GetShopInfoList

	return this.getData(url).then((data) => {
		return data;
	})
}


AppServer.prototype.GetServerList = async function() {
	return this.postData(serverConfig.apiUrl_AppConfig_GetServerList).then(data => {
		console.log((data));
	})
}

/**
 * 登录
 * @param {Object} code
 */
AppServer.prototype.AccountLogIn = async function(code) {
	return this.postData(serverConfig.apiUrl_Music_AccountLogIn, {
		"loginType": 2,
		"code": code
	}).then(data => {
		console.log((data));
		return data;
	})
}

// AppServer.prototype.GetMiniProgramUserInfo = async function(encryptedData, iv, userId) {
// 	return this.postData(serverConfig.apiUrl_Music_GetMiniProgramUserInfo, {
// 		"encryptedData": encryptedData,
// 		"iv": iv,
// 		"userId": userId
// 	}).then(data => {
// 		console.log((data));
// 		return data;
// 	})
// }

/**
 * 运行平台
 */
AppServer.prototype.GetPlatformIsAndroid = function() {
	let port = uni.getSystemInfoSync().platform
	switch (port) {
		case 'android':
			console.log('运行Android上', port);
			return true;
			break; //android
		case 'ios':
			console.log('运行iOS上', port);
			return false;
			break;
		default:
			console.log('运行在开发者工具上');
			return false;
			break;
			//devtools
	}
}

export {
	AppServer
}