/*
	充值测试处理模块
*/
var mysql = require('mysql');
var mysqlcn = require('../../terry/mysqlcn.js');
var query = mysqlcn.query;
var qs = require('querystring');
var encryption = require('../ordinary/encryption.js');
var checkorder = require('../../terry/checkorder.js');
var config = require('../config.js');

var pay_success = function(args,res){
	console.log("yuda_abd 回调接收:%s", args);
	var receipt
	try {
	  receipt = qs.parse(args)
	  console.log("qs解析成功")
	} catch(e) {
	  console.log(e)
	  res.send("FAILURE");
	  return;
    }

  var money = receipt.amount                       	// 玩家付款金额
//var goods_id = receipt.goods_id                   // 产品配置表id



  var channel_order_id = receipt.trade_no           // SDK生成的订单号
  var payment_type = receipt.payment_type           // 支付类型(具体使用的SDK)
  var istest = 1                                    // 充值模式	istest=1沙盒测试  2:正式
  var cp_order_id = receipt.game_trade_no			// CP订单号

	// 玩家的付款金额、充值档位、购买份数 需要进行校验

	var sql = mysql.format("SELECT * FROM payinfo where orderid=?", [cp_order_id]);//在mysql库中检查订单号
	query(sql,function(qerr,vals,fields){
		if (qerr==null){
			if (vals[0]==null){
				console.log("[yuda_abd] 没有找到该订单");
				try{res.send("FAILURE");}
				catch(e){}
				return;
			}
			if (vals[0].overtime>0){
				console.log("[yuda_abd] 已经处理的订单");
				try{res.send("SUCCESS");}
				catch(e){}
				return;
			}

			var amountnum = money
			var platform = vals[0].platform;
			platform = platform ? platform.toLowerCase() : 'null'
			var str
			if (platform == 'ios') {
				str = "com.yoo.and.lybmyz.ios"
			} else if (platform == 'android') {
				str = "com.yoo.and.lymxads"
			} 
			else {
				console.log("################## 错误的平台platform: %s", platform)
				try{res.send("FAILURE");}
				catch(e){}
				return
			}
			var pos1 = receipt.goods_id.indexOf(str) + str.length
			var pos2 = receipt.goods_id.length
			var goods_id = receipt.goods_id.substring(pos1,pos2)

			var channel = vals[0].channel
			var timestamp = Date.parse(new Date()) / 1000;

			console.log("################## goods_id %s", goods_id)
			console.log("platform:%s,channel:%s,amountnum:%s",platform,channel,amountnum)

			var option = config.parse(platform,channel,goods_id)
			var cfid = option.cfid;
			var product_id = option.name
			if (cfid == 0){
				console.log("[yuda_abd] 获取cfid失败为cfid:%s,product_id:%s", cfid,product_id);
				try{res.send("FAILURE");}
				catch(e){}
				return
			}

			if (goods_id != cfid){
				console.log("[yuda_abd] 充值计费点不同goods_id:%s,cfid:%s", goods_id,cfid);
				try{res.send("FAILURE");}
				catch(e){}
				return
			}

			if (amountnum != option.price){
				console.log("[yuda_abd] 充值金额不同amountnum:%s,option.price:%s", amountnum, option.price);
				try{res.send("FAILURE");}
				catch(e){}
				return
			}

			//填充充值信息
			var sql_1 = "UPDATE payinfo SET \
				channel_order_id=?,\
				overtime=?,\
				flag=?,\
				money=?,\
				cfid=?,\
				platform=?,\
				channel=?,\
				moneytype=?,\
				product_id=?,\
				talkingdata=?,\
				payment_type=?, \
				istest=?\
				WHERE orderid=? \
				AND flag=2";//增加flag判断防止重复写入
			var values_2 = [channel_order_id,timestamp,1,amountnum,cfid,platform,channel,option.typename,product_id,1,payment_type,istest,cp_order_id];
			var sql_2 = mysql.format(sql_1, values_2);
			query(sql_2,function(qerr,rows,fields_)
			{
				if (qerr){
					console.log("[yuda_abd]逻辑错误，请检查数据表结构和sql语句:\n\t%s", qerr);
					try{res.send("FAILURE");}
					catch(e){}
					return;
				}
				if (rows.affectedRows > 0){//判断修改了多少个记录
					console.log("[yuda_abd]支付成功了，现在通知游戏服务器, orderId:%s, uid:%s, serverid:%s ,cfid:%s",
					cp_order_id,vals[0].uid,vals[0].serverid,cfid);
						checkorder.pushproduct(query,vals[0].serverid, cp_order_id, function(ok){
						if (ok) {
							console.log("[yuda_abd] 订单 %s: 成功发货!", cp_order_id);
						} else{
							console.log("[yuda_abd] 订单 %s: 发货地址无效!", cp_order_id);//在无效时返回成功，我们自己补单中会派发flag为1支付成功但是没成功发货的单
						}
						try{res.send("SUCCESS");}
						catch(e){}
					});

						// 向 TalkingData 报告充值数据
					var appId = config.getAppID(channel);
					if (istest == 2) {
						checkorder.pushtalkingdata(query,appId,platform,vals[0].uid,cp_order_id,option.price,option.typename,option.diamond,timestamp,payment_type,vals[0].serverid);
					}
					res.send("SUCCESS");
					return;
				}else{
					console.log("SQL重复写入[yuda_abd]已经处理的订单");
					try{res.send("SUCCESS");}
					catch(e){}
					return;
				}
			})
		}else{
			console.log("[yuda_abd] 查询订单列表错误，请检查数据表结构和sql语句:\n\t%s", qerr);
			try{res.send("FAILURE");}
			catch(e){}
			return;
		}
	})
}


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

router.get('/yuda_abd_pay', function(req, res) {
	var pos = req.url.indexOf('?')
	var str = req.url
	if (pos == -1) {    //请求的url是否包含？包含返回-1，==-1为不包含
		console.log("yuda_abd 回调接收未找到参数");
		res.send("FAILURE");
	} else {
		var data = str.substring(pos+1,str.length)
		pay_success(data, res)
	};
	req.on("error",function(err){
		 console.log("error:%s",err);
		 res.send("FAILURE");
	});
});

module.exports = router;