//补单
var checkorder = require('../../terry/checkorder.js');
var mysql = require('mysql');
var mysqlcn = require('../../terry/mysqlcn.js');
var config = require('../config.js');
var encryption = require('./encryption.js');
var qs = require('querystring');

var query = mysqlcn.query;

// var orderid            	//cp订单号
// var serverid        		//服务器id
// var uid     				//玩家的uid
// var platformid           //'android'或'ios'
// var channel             	//渠道
// var cfid        			//商品的sid
// var money           		//金额
// var moneytype            //货币类型
// var flag     			//等待支付
// var product_id			//计费点名称
// var channel_order_id   	//渠道订单号
// var talkingdata   		//1未向talkingdata数据0发送成功
// var payment_type			//附加的子渠道
// var submittime			//订单创建时间
// var overtime				//订单结束时间
// var userid               //平台或渠道的账号id


var SIG_KEY_A = "d06ede1fc820e59c7fb795c8d310aaa4";
var sql_insert = function(orderid, serverid,uid,money,moneytype,cfid,platform,channel,submittime,overtime,flag,product_id,talkingdata){
    var sql = "INSERT INTO payinfo SET orderid=?, serverid=?, uid=?,money=?,moneytype=?,cfid=?,platform=?,channel=?,submittime=?,overtime=?,flag=?,product_id=?,talkingdata=?";
    var values = [orderid, serverid,uid,money,moneytype,cfid,platform,channel,submittime,overtime,flag,product_id,talkingdata];
    sql = mysql.format(sql, values);
    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 istest = 2 // 充值模式	istest=1沙盒测试  2:正式
  //手动补单
var shoudong_repair_order=function(args,res){
	try {
        console.log("补单消息:%s",args)
		var obj = JSON.parse(args);
		var serverid = obj.serverid;
		var uid = obj.uid;
		var cfid = obj.cfid;
		var money = obj.money;
		var moneytype = obj.moneytype;
		var platform = obj.platform;
		var channel = obj.channel;
		var orderid = obj.orderid;
		var act_id = obj.act_id;
		var act_type = obj.act_type;
		var goods_id = obj.goods_id;
		var sign = obj.key;
        if (serverid==null ||
            uid==null ||
            cfid==null ||
            money==null ||
            moneytype==null ||
            platform==null ||
            channel==null ||
            orderid==null ||
			act_id==null ||
			act_type==null ||
			goods_id==null ||
			sign == null
			){
		  res.send(JSON.stringify({ 'error':'参数不全'}));
		  return;
		}
		var submittime = Date.parse(new Date()) / 1000;

		if (obj.desc==null){
			obj.desc = "gm";
		}

		var str_sign = "serverid="+serverid+
		"&uid="+uid+
		"&cfid="+cfid+
		"&money="+money+
		"&moneytype="+moneytype+
		"&platform="+platform+
		"&channel="+channel+
		"&orderid="+orderid+
		"&act_id="+act_id+
		"&act_type="+act_type+
		"&goods_id="+goods_id+
		"&key="+SIG_KEY_A;
		var mysign = encryption.md5(str_sign);
		if (mysign != sign){
			try{res.send( JSON.stringify( {'erron':'签名错误'}));}
			catch(e){}
			return;
		}
		query(sql_select(orderid),function(qerr,vals,fields){
			if (qerr==null){
				if (vals[0]){
					console.log("订单重复");
					try{res.send( JSON.stringify( {'erron':'订单重复'}));}
					catch(e){}
					returnorderID = 2;
					return;
				}
				var timestamp = Date.parse(new Date()) / 1000;
				var product_id = option.name

				var sql_1 = "INSERT INTO payinfo SET\
				orderid=?,\
				overtime=?,\
				flag=?,\
				money=?,\
				cfid=?,\
				platform=?,\
				channel=?,\
				moneytype=?,\
				product_id=?,\
				talkingdata=?,\
				act_id=?, \
				act_type=?, \
				goods_id=?, \
				istest=?";
				var values_2 = [orderid,timestamp,1,money,cfid,platform,channel,option.typename,product_id,1,act_id, act_type, goods_id,istest];
				var sql = mysql.format(sql_1, values_2);
				query(sql,function(qeer,vals,fields_){
					if(qeer==null){
						checkorder.pushproduct(query,orderid,uid,serverid,cfid,function(ok){
							if (ok) {
								console.log("[补单] 订单 %s: 成功发货!", orderid);
							} else{
								console.log("[补单] 订单 %s: 发货地址无效!", orderid);//在无效时返回成功，我们自己补单中会派发flag为1支付成功但是没成功发货的单
							}
							try{
							res.send(JSON.stringify({ 'error':'成功'}));
							}
							catch(e){}
						})
					}else{
						console.log(qeer);
						res.send(JSON.stringify({ 'error':'插入数据失败，请重新提交'}));
					}
				})
			}
		})
	}catch(err){
		console.log(err);
		res.send(JSON.stringify({ 'error':'请重新提交'}));
	}
}

//手动补单 成功  status:200    失败 status:400   其他错误  status:500
var url_repair_order=function(args,res){
	try {
		console.log("补单消息:%s",args)
		var obj
		try {
			obj = qs.parse(args)
			console.log("qs解析成功")
		  } catch(e) {
			console.log(e)
			res.send("FAILURE");
			return;
		  }
		var serverid = obj.serverid;
		var uid = obj.uid;
		var cfid = obj.cfid;
		var money = obj.money;
		var moneytype = obj.moneytype;
		var platform = obj.platform;
		var channel = obj.channel;
		var orderid = obj.orderid;
		var act_id = obj.act_id;
		var act_type = obj.act_type;
		var goods_id = obj.goods_id;
		var sign = obj.key;
		var check_ret = false;
		var name = ""
        if (serverid==null){
			name = "serverid"
		}else if(uid==null) {
			name = "uid"
		}else if(cfid==null) {
			name = "cfid"
		}else if(money==null) {
			name = "money"
		}else if(moneytype==null) {
			name = "moneytype"
		}else if(platform==null) {
			name = "platform"
		}else if(channel==null) {
			name = "channel"
		}else if(orderid==null) {
			name = "orderid"
		}else if(act_id==null) {
			name = "act_id"
		}else if(act_type==null) {
			name = "act_type"
		}else if(goods_id==null) {
			name = "goods_id"
		}else if(sign==null) {
			name = "sign"
		}else{
			check_ret = true
		}
		if(!check_ret){
			console.log(name);
			res.send(JSON.stringify({ 'status':'500','msg':'参数不全'}));
		}
		var submittime = Date.parse(new Date()) / 1000;


		if (obj.desc==null){
			obj.desc = "gm";
		}
		var str_sign = "serverid="+serverid+
		"&uid="+uid+
		"&cfid="+cfid+
		"&money="+money+
		"&moneytype="+moneytype+
		"&platform="+platform+
		"&channel="+channel+
		"&orderid="+orderid+
		"&act_id="+act_id+
		"&act_type="+act_type+
		"&goods_id="+goods_id+
		"&key="+SIG_KEY_A;
		console.log(str_sign);
		console.log(obj.str);
		var mysign = encryption.md5(str_sign);
		if (mysign != sign){
			console.log(mysign);
			console.log(sign);
			try{res.send( JSON.stringify( {'status':'500','msg':'缺少参数'}));}
			catch(e){}
			return;
		}
		query(sql_select(orderid),function(qerr,vals,fields){
			if (qerr==null){
				if (vals[0]){
					console.log("订单重复");
					try{res.send( JSON.stringify( {'status':'400','msg':'订单重复'}));}
					catch(e){}
					return
				}
				var platform = 'android';
				var channel = 'replenish';
				var option = config.parse(platform,channel,cfid)
				var timestamp = Date.parse(new Date()) / 1000;
				var product_id = option.name

				var sql_1 = "INSERT INTO payinfo SET\
				orderid=?,\
				serverid=?,\
				overtime=?,\
				flag=?,\
				money=?,\
				cfid=?,\
				platform=?,\
				channel=?,\
				moneytype=?,\
				product_id=?,\
				talkingdata=?,\
				act_id=?, \
				act_type=?, \
				goods_id=?, \
				uid=?, \
				istest=?";

				var values_2 = [orderid,serverid, timestamp,1,money,cfid,platform,channel,moneytype,product_id,0,act_id, act_type, goods_id,uid,istest];
				var sql = mysql.format(sql_1, values_2);
				console.log(sql)
				query(sql,function(qeer,vals,fields_){
					if(qeer==null){
						checkorder.pushproduct(query,serverid,orderid,function(ok){
							if (ok) {
								console.log("[补单] 订单 %s: 成功发货!", orderid);
							} else{
								console.log("[补单] 订单 %s: 发货地址无效!", orderid);//在无效时返回成功，我们自己补单中会派发flag为1支付成功但是没成功发货的单
							}

							try{
							res.send(JSON.stringify({ 'status':'200','msg':'成功'}));
							}
							catch(e){}
						})
					}else{
						console.log(qeer);
						res.send(JSON.stringify({ 'status':'400','msg':'插入数据失败，请重新提交'}));
					}
				})
			}
		})
	}catch(err){
		console.log(err);
		res.send(JSON.stringify({ 'status':'400','msg':'请重新提交'}));
	}
}


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

router.get('/repair_order', 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,real_ip,new Date());
		var data = "";
		req.on("data",function(chunk){
		  data += chunk;
		})
		req.on("end",function(){
			shoudong_repair_order(data,res);
		})
		req.on("error",function(err){
			 var info = JSON.stringify({ 'error':'充值系统错误'});
			 res.send(info);
		})
	 }catch(err){
		 console.log(err);
		 var info = JSON.stringify({ 'error':'充值系统错误'});
		 res.send(info);
	 }
})

router.post('/repair_order', function(req, res) {
	var real_ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
	console.log("post repair_order,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{
			url_repair_order(data,res)
		} catch(e) {
			console.log(e)
			res.send("FAILURE");
		}
	});

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


module.exports = router;