//检查订单
var https = require('https');
var http = require('http');
var mysql = require('mysql');

 var sql_select = function(orderid){
	 var sql = "SELECT * FROM payinfo WHERE ?? = ?";
	 var inserts = ['orderid',orderid];
	 sql = mysql.format(sql, inserts);
	 return sql;
 }

 //更新 talkingdata 报道标记
 var sql_update_talkingdata = function(orderid,value){
	 var sql = "UPDATE payinfo SET talkingdata=? WHERE orderid=?";
	 var values = [value,orderid];
	 sql = mysql.format(sql, values);
	 return sql;
 }

 //更新数据库 talkingdata 字段
 var update_talkingdata_by_orderid=function(query,orderid,value){
	console.log("update_talkingdata_by_orderid, orderid:%s,value:%d",orderid,value);
	var sql = sql_update_talkingdata(orderid,value);
	query(sql,function(qerr,vals,fields){
		if (qerr==null){
			return 0;
		}else{
			console.log(qerr);
			return 1;
		}
	})
}

 //查询游戏服务器列表
 var sql_select_server = function(id){
	var sql = "SELECT * FROM services WHERE id = ?";
    var inserts = [id];
    sql = mysql.format(sql, inserts);
	return sql;
 }

 //更新是否完成对游戏服务器的充值
 var sql_update_flag = function(orderid,flag){
	 var sql = "UPDATE payinfo SET flag=? WHERE orderid=?";
	 var values = [flag,orderid];
	 sql = mysql.format(sql, values);
	 return sql;
 }

 //更新数据库flag
 var update_flag_by_orderid=function(query,orderid,flag){
	 console.log("update_overtime_by_orderid, orderid:%s,flag:%d",orderid,flag);
	 var sql = sql_update_flag(orderid,flag);
	 query(sql,function(qerr,vals,fields){
		 if (qerr==null){
			 return 0;
		 }else{
			 console.log(qerr);
			 return 1;
		 }
	 })
 }

 //更新完成时间戳,针对渠道的报道时间
 var sql_update_overtime = function(orderid,overtime){
	var sql = "UPDATE payinfo SET overtime=? WHERE orderid=?";
	var values = [overtime,orderid];
	sql = mysql.format(sql, values);
	return sql;
}

 //更新数据库overtime
 var update_overtime_by_orderid=function(query,orderid,overtime){
	console.log("update_overtime_by_orderid, orderid:%s,overtime:%d",orderid,overtime);
	var sql = sql_update_overtime(orderid,overtime);
	query(sql,function(qerr,vals,fields){
		if (qerr==null){
			return 0;
		}else{
			console.log(qerr);
			return 1;
		}
	})
}

// 读取订单详细数据 发送至游戏服务器
var order_detail = function(orderid){
	var sql = "SELECT * FROM payinfo WHERE orderid = ?";
	var inserts = [orderid];
	return mysql.format(sql, inserts);
	// var detail
	// query(sql,function(qerr,vals,fields){
	// 	if (vals.length > 0){
	// 		// return 0, vals[0];
	// 		console.log("########## 查询到了数据")
	// 		detail = vals[0];
	// 	}else{
	// 		console.log("########## 没有查询到数据")
	// 		console.log(qerr);
	// 		// return 1;
	// 	}
	// })
	// return detail
}

 //发送订单完成信息给游戏服务器
 //rmb 实质是配置id，并非真是的钱
 var send_2_game = function(query,serverid, orderid, callback){
	var sql = sql_select_server(serverid);
	var sql_detail = order_detail(orderid);
	query(sql_detail,function(qerr_d,vals_d,fields_d){
		if (vals_d.length > 0){
			var detail = vals_d[0];
			var data2game = JSON.stringify(detail);
			console.log("[订单数据结果 ] %s", data2game)
			query(sql,function(qerr,vals,fields){
				if (vals.length>0){
					queryRet = vals[0];
					// var data2game = {
					// 	'orderid': orderid,
					// 	'uid': uid,
					// 	'cfid' : cfid
					// };
					console.log("[queryRet] %s", JSON.stringify(queryRet))
					var opt = {
						method: "POST",
						host: queryRet.ip,
						port: queryRet.port,
						path: "/recharge",
						headers: {
							"Content-Type": 'application/json',
							"Content-Length": Buffer.byteLength(data2game, "utf8")
						}
					};

					var req = http.request(opt, function (res){
						if (res.statusCode == 200){
							var datas = [];
							var size = 0;
							res.on('data', function (data){
								datas.push(data);
								size += data.length;
							});
							res.on('end', function (){
								var buff = Buffer.concat(datas, size);
								var result = buff.toString();
								var result = JSON.parse(result);
								if (parseInt(result.code)==0){
									// 至此，一笔充值圆满的结束了
									update_flag_by_orderid(query,orderid,0);
									if (callback) {
										callback(true)
										return
									}
								}
								else if(parseInt(result.code)==2){
									update_flag_by_orderid(query,orderid,3);
									if (callback) {
										callback(true)
										return
									}
								}
								else if (callback) {
									console.log("充值失败:%s,%s",parseInt(result.code),result.code);
									callback(false)
									return
								}
							});
							res.on('error', function (err){
								console.log(err);
								if (callback) {
									callback(false)
									return
								}
							});
						}
					}).on('error', function(){
						if (callback) {
							callback(false)
							return
						}
					});
					req.write(data2game);
					req.end();
				} else {
					if (callback) {
						callback(false)
						return
					}
				}
			})
		}else{
			console.log(qerr_d);
			if (callback) { callback(false) }
			return
		}
	})
}

var share = require("../terry/share/index.js");
var send_2_talkingdata = function(
	query,					// Mysql 查询函数
    appID,                  // String, 是您在TalkingGame中创建游戏时获得的AppID，用来唯一标识您的游戏。
    OS,                     // String, 玩家此次充值时所用的设备系统平台,只支持格式要求限定的字符串。(ios, android, h5)
    accountID,              // String, 玩家的账户ID（与客户端调用SDK的setAccount需传入玩家的accountId类似。）
    orderID,                // String, 订单ID，唯一标识一次交易。
    currencyAmount,         // Double, 充值金额；
    currencyType,           // String, 充值货币类型(人民币CNY；美元USD；新台币TWD)；
    virtualCurrencyAmount,  // Double, 充值获得的虚拟币额度。
    chargeTime,             // Long,   玩家充值发生的时间。
    paymentType,            // String, 支付方式(如：支付宝、苹果iap、银联支付、爱贝支付聚合等)。
    gameServer) {						// Long, 	 玩家充值的区服。

 	if (appID == null) {
		console.log("订单 %s: 未能向 TalkingData 报道，因为没有获得正确的 AppID", orderID)
		return;
	}
	var req = new share.TalkingData()
	req.on('error', function(err){
		console.log("订单 %s: 向 TalkingData 报告失败!\n\t%s", orderID, err.message)
	});
	req.on('end', function(){
		update_talkingdata_by_orderid(query, orderID, 0)
		console.log("订单 %s: 向 TalkingData 报告成功!", orderID)
	})
	req.send(appID, OS, accountID, orderID, currencyAmount, currencyType, virtualCurrencyAmount, chargeTime, paymentType, gameServer)
}

//通知服务器发送钻石
exports.pushproduct = function(query,serverid,OrderId,functionnum){
	send_2_game(query,serverid,OrderId,functionnum);
}

//向talkingdata推送数据
exports.pushtalkingdata = function(query,appId,platform,uid,order_id,price,typename,diamond,timestamp,payment_type,serv_id){
	// send_2_talkingdata(query,appId,platform,uid,order_id,price,typename,diamond,timestamp,payment_type,serv_id);
}


