/*
	给玩家创建订单, 订单创建消息由客户端发起创建。通过游戏服转发至充值服。
	游戏服传入的参数：
    userid = character.account,			      -- 平台或渠道的账号id
    serverid = character.sid,		          -- 游戏服务器id
    uid = character.uid,		              -- 游戏内的账号id
    platformid = platformid,	            -- 平台id（Andorid、iOS）
    channel = character.channel,			    -- 渠道标识
    product_id = product_id,	            -- 计费点名称
    remarks  = 'remarks',                     -- ,
    source = source or 0,                 -- 充值来源(0:非活动 其他值: 活动类型)
    appname = appname or 'appname',           -- 玩家使用的包
	source 			改参数主要指指定客户端在上面界面请求的订单创建, 目前主要区分 活动充值 和 非活动充值
	appname			针对指定包的玩家充值, 额外处理的需求
*/
var mysql = require('mysql');
var mysqlcn = require('../../terry/mysqlcn.js');
var query = mysqlcn.query;
var uuid = require('node-uuid');
var qs = require('querystring');
var encryption = require('./encryption.js');
var config = require('../config.js');

 //查询游戏服务器列表
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_select = function(orderid){
	 var sql = "SELECT * FROM payinfo WHERE ?? = ?";
	 var inserts = ['orderid',orderid];
	 sql = mysql.format(sql, inserts);
	 return sql;
}

var sql_select_account = function(account){
	var sql = "SELECT * FROM cardNOID WHERE account = ?";
    var inserts = [account];
    sql = mysql.format(sql, inserts);
	return sql;
}

//@TODO: 充值服生成订单
var getorderiduuid = function(args,res){
    console.log("客户端来请求充值服产生订单:%s",args);
	if (args==null){
		console.log("无效的充值请求!");
		try {res.send("2");}
		catch(e){}
		return;
	}

	var receipt = null
	try {
		receipt = qs.parse(args);//JSON.parse(args)
	} catch(e) {
			console.log("解析失败!");
			try {res.send("3");}
			catch(e){}
			return
	}

	var userid = receipt.userid;			// 平台或渠道的账号id
	var serverid = parseInt(receipt.serverid);		// 游戏服务器id
	var uid = receipt.uid;		            // 游戏内的账号id
	var platform = receipt.platform;	// 平台id（Andorid、iOS）
	var channel = receipt.channel;			// 渠道标识
	var product_id = receipt.product_id;	// 礼包id
    var cfid = receipt.cfid;                // 计费点id
	var remarks = receipt.remarks;
	var appname  = receipt.appname;			// 玩家充值使用的包
	var act_id = parseInt(receipt.act_id);			// 活动唯一id
	console.log(
			"请求:\n\tserverid=%s,uid=%s,userid=%s,platform=%s,channel=%s,remarks=%s,appname=%s,act_id=%s,cfid=%s",
			serverid,
			uid,
			userid,
			platform,
			channel,
			remarks,
			appname,
			act_id,
			cfid);

	var sql = sql_select_server(serverid);
	query(sql,function(qerr,vals,fields_){
		if (qerr==null){
			if (vals.length==0){
				console.log("客户端获取订单号，该服务器id:%s不存在",serverid);
				try{
					res.send(JSON.stringify( {'erron':4,'desc':"该服务器id不存在"}));
				}
				catch(e){}
                return
            }

			var orderid = uuid.v1();
			if (orderid == null || orderid == undefined || orderid == "") {
				try {
                    // res.send("4");
					res.send(JSON.stringify( {'erron':4,'desc':'订单号创建失败'}));
				}
				catch(e){}
				console.log("无效订单号!")
				return
			}

			var returnorderID = 1
			query(sql_select(orderid),function(qerr,vals,fields){
				if (qerr==null){
					if (vals[0]){
						console.log("生成订单重复");
						try{res.send( JSON.stringify( {'erron':4,'desc':'生成订单重复'}));}
						catch(e){}
						returnorderID = 2;
						return
					} else{
						var pushmysql = function(query,orderid,serverid,uid,platform,channel,userid,product_id,cfid,remarks,appname,callback){
							var submittime = Date.parse(new Date()) / 1000;
							var sql = "INSERT INTO payinfo SET orderid=?,serverid=?,uid=?,platform=?,channel=?,submittime=?,flag=?,user_id=?,product_id=?,cfid=?,remarks=?,appname=?";
							var values = [orderid, serverid,uid,platform,channel,submittime,2,userid,product_id,cfid,remarks,appname];
							sql = mysql.format(sql, values);
							console.log(sql)
							query(sql, function(err,vals){
								if (err	== null) {
									callback(0)
								} else {
									callback(err.errno);
								}
							})
						}

						//将客户端生成的订单号记录在数据库中
						pushmysql(query,orderid,serverid,uid,platform,channel,userid,product_id,cfid,remarks,appname,function(errno){
							if (errno == 0) {
								try{
									// res.send("0,"+orderid);
									res.send(JSON.stringify( {'erron':0,'desc': orderid}));
								}
								catch(e){}
								console.log("开始订单 %s 的支付流程!", orderid);
							} else {
								try{
									// res.send("5");
									res.send(JSON.stringify( {'erron':5,'desc': "数据库存储失败"}));
								}
								catch(e){}
								console.log("创建订单 %s 时出现 %s 错误!", orderid, errno);
							}
						});
					}
				} else {
					console.log("查找mysql库中订单列表失败");
					try{
						// res.send( "6,系统错误，请重新获取");
						res.send(JSON.stringify( {'erron':6,'desc': "系统错误，请重新获取"}));
					}
					catch(e){}
				}
			});
		}else{
			console.log("查找mysql库中服务器列表失败");
			try{
				// res.send( "6,系统错误，请重新获取");
				res.send(JSON.stringify( {'erron':6,'desc': "系统错误，请重新获取"}));
			}
			catch(e){}
		}
	})
}

var get_server_ip = function(args,res){
	console.log("GM请求服务器ip数据:%s", JSON.stringify(args));

	var key = "2D7F44957C2749D9B650B43CF6AB0320";
	var receipt = args;

	var serverid = receipt.serverid;
	var user = receipt.user;
	var sign = receipt.sign;
	var str_sign = "serverid="+serverid+"&user="+user+"&key="+key;
	var mysign = encryption.md5(str_sign);
	if (mysign != sign){
		console.log("查找mysql库中服务器失败，签名错误mysign:%s,sign:%s",mysign,sign);
		try{res.send( JSON.stringify({ 'state':'2'}));}
		catch(e){}
		return;
	}

	var sql = mysql.format("SELECT * FROM services where id=?" ,[serverid]);
	query(sql,function(qerr,vals,fields_){
		if (qerr==null){
			if (vals.length==0){
				console.log("查找mysql库中服务器失败");
				try{res.send( JSON.stringify({ 'state':'3'}));}
				catch(e){}
                return
			}

			var returndata = JSON.stringify({
				'state':'0',
				'ip':vals[0].wan,
				'port':vals[0].port,
			});

			console.log("查找mysql库中服务器列表:%s",returndata);
			res.send(returndata);

		}else{
			console.log("打开mysql库中服务器失败");
			try{res.send( JSON.stringify({ 'state':'4'}));}
			catch(e){}
		}
	});
}

var get_all_server_ip = function(args,res){
	console.log("GM请求服务器ip数据:%s", args);

	var key = "2D7F44957C2749D9B650B43CF6AB0320";
	var receipt = JSON.parse(args);

	var channel = receipt.channel;
	var user = receipt.user;
	var sign = receipt.sign;
	var str_sign = "channel="+channel+"&user="+user+"&key="+key;
	var mysign = encryption.md5(str_sign);
	if (mysign != sign){
		console.log("查找mysql库中服务器失败，签名错误mysign:%s,sign:%s",mysign,sign);
		try{
			res.send(JSON.stringify({ 'status':'400','msg':'参数不全'}));
		}
		catch(e){}
		return;
	}

	var sql = "SELECT * FROM services";
	query(sql,function(qerr,vals,fields_){
		if (qerr==null){
			if (vals.length==0){
				console.log("查找mysql库中服务器列表失败");
				try{
					res.send(JSON.stringify({ 'status':'500','msg':'无数据'}));
				}
				catch(e){}
                return
			}

			var data = new Array();
			for (var i = 0;i < vals.length; ++i){
				var aa = {
					"id" : vals[i].id,
					'ip':vals[i].wan_ip,
					'port':vals[i].port,
				};
				data[i] = aa;
			}
			var returndata = JSON.stringify({
				'state':'1',
				'data':data,
			});

			console.log("查找mysql库中服务器列表:%s",returndata);
			res.send(returndata);
		}else{
			console.log("打开mysql库中服务器列表失败");
			try{
				res.send(JSON.stringify({ 'status':'400','msg':'稍后请求'}));
			}
			catch(e){}
		}
	});
}

//@TODO: 服务器列表获取
var getserver_all = function(args,res){
	console.log("/getserver_all请求区服数据:%s", JSON.stringify(args));
	var key = "2D7F44957C2749D9B650B43CF6AB0320";
	var receipt = JSON.parse(args);

	var channel = receipt.channel;
	var user = receipt.user;
	var sign = receipt.sign;
	var str_sign = "channel="+channel+"&user="+user+"&key="+key;
	var mysign = encryption.md5(str_sign);
	if (mysign != sign){
		console.log("查找mysql库中服务器失败，签名错误mysign:%s,sign:%s",mysign,sign);
		try{
			res.send(JSON.stringify({ 'status':'400','msg':'参数不全'}));
		}
		catch(e){}
		return;
	}

	var sql = "SELECT * FROM services";
	query(sql,function(qerr,vals,fields_){
		if (qerr==null){
			if (vals.length==0){
				console.log("查找mysql库中服务器列表失败");
				try{res.send( JSON.stringify({ 'state':'0'}));}
				catch(e){}
                return
			}

			var data = new Array();
			for (var i = 0;i < vals.length; ++i){
				var aa = {
					"id" : vals[i].id,
					"serverID" : vals[i].id,
					"serverName" : vals[i].name,
				};
				data[i] = aa;
			}
			var returndata = JSON.stringify({
				'state':'1',
				'data':data,
			});

			console.log("查找mysql库中服务器列表:%s",returndata);
			res.send(returndata);
		}else{
			console.log("打开mysql库中服务器列表失败");
			try{res.send( JSON.stringify({ 'state':'0'}));}
			catch(e){}
		}
	});
}

var express = require('express');
var router = express.Router();

//@TODO: 订单生成
var getorderid = function(req, res) {
	var real_ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
	console.log("post getorderid,host:%s, ip:%s,path:%s,time:%s",req.hostname,real_ip,req.path,new Date());
	var data = "";
	req.on("data",function(chunk){
	  data += chunk;
	});
	req.on("end",function(){
		try{
			getorderiduuid(data,res);
		} catch(e) {
			console.log(e)
			// res.send("fail");
			res.send(JSON.stringify( {'erron':1,'desc': "fail"}));
		}
	});
	req.on("error",function(err){
		 console.log("error:%s",err);
		//  res.send("fail");
		res.send(JSON.stringify( {'erron':1,'desc': "fail"}));
	});
}

router.post('/getorderid', getorderid);
router.post('/IosOrderid', getorderid);
router.post('/ios_orderid', getorderid);
router.post('/orderid_ios', getorderid);
router.post('/OrderidIos', getorderid);

router.get("/get_server_ip",function(req,res){
	try{
		var real_ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
		console.log("get shoudong_repair_order,host:%s, ip:%s,time:%s",req.hostname,req.ip,new Date());
		get_server_ip(req.query,res);
	 }catch(err){
		 console.log(err);
		 var info = JSON.stringify({ 'state':'0'});
		 res.send(info);
	 }
})


router.get("/get_time",function(req,res){
	try{
			var real_ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
	//      console.log("get get_time,host:%s, ip:%s,time:%s",req.hostname,req.ip,new Date());
	//      var times = Math.floor(Date.now()/1000);

			var date = new Date();//.转换成毫秒
			var time = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':' +
			(date.getMinutes() <10 ? '0' + date.getMinutes() : date.getMinutes()) + ':' +
			(date.getSeconds() <10 ? '0' + date.getSeconds() : date.getSeconds());
			res.send(time)
	}catch(err){
			 console.log(err);
			 var info = JSON.stringify({ 'state':'0'});
			 res.send(info);
	 }
})


router.post("/get_all_server_ip",function(req,res){
	var real_ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
	console.log("post get_all_server_ip,host:%s, ip:%s,path:%s,time:%s",req.hostname,real_ip,req.path,new Date());
	var data = "";
	req.on("data",function(chunk){
	  	data += chunk;
	});

	req.on("end",function(){
		try{
			get_all_server_ip(data,res);
		} catch(e) {
			console.log(e)
			res.send("fail");
		}
	});

	req.on("error",function(err){
		console.log("error:%s",err);
		res.send("fail");
	});
})

router.post("/getserver_all",function(req,res){
	var real_ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
	console.log("post getserver_all,host:%s, ip:%s,path:%s,time:%s",req.hostname,real_ip,req.path,new Date());
	var data = "";
	req.on("data",function(chunk){
	  	data += chunk;
	});

	req.on("end",function(){
		try{
			getserver_all(data,res);
		} catch(e) {
			console.log(e)
			res.send("fail");
		}
	});

	req.on("error",function(err){
		console.log("error:%s",err);
		res.send("fail");
	});
})

module.exports = router;