/*
	充值测试处理模块
*/
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 get_parameter = function(appid){
	var option = huosu_subset[appid];
	if (option){
		return option;
	}
	return null;
}

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

  var money = receipt.money                       	// 玩家付款金额
  var copies = 1                      // 购买份数: 付款金额 / 单价
  var moneytype = receipt.moneytype                // 货币类型
  var cfid = receipt.cfid                        	// 产品配置表id
  var overtime = receipt.overtime                  // SDK回调处理时间
  var channel_order_id = receipt.channel_order_id  // SDK生成的订单号
  // var talkingdata = receipt.talkingdata            // TD是否发送标识
  var payment_type = receipt.payment_type          // 支付类型(具体使用的SDK)
  // var remarks = receipt.remarks                    // 附带信息
  var istest = 1                     // 充值模式	istest=1沙盒测试  2:正式

	var cp_order_id = receipt.cp_order_id						// CP订单号
	var channel = receipt.channel						// 渠道

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

	var product_id = cfid

	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("[editor] 没有找到该订单");
				try{res.send("FAILURE");}
				catch(e){}
				return;
			}
			if (vals[0].overtime>0){
				console.log("[editor] 已经处理的订单");
				try{res.send("SUCCESS");}
				catch(e){}
				return;
			}

			var amountnum = money
			var platform = 'android';
			var channel = vals[0].channel
			var cfid = receipt.cfid
			var timestamp = Date.parse(new Date()) / 1000;

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

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

			if (amountnum != option.price){
				console.log("[editor] 充值金额不同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=?, \
				copies=?,\
				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,copies,istest,cp_order_id];
			var sql_2 = mysql.format(sql_1, values_2);
			query(sql_2,function(qerr,rows,fields_)
			{
				if (qerr){
					console.log("[editor]逻辑错误，请检查数据表结构和sql语句:\n\t%s", qerr);
					try{res.send("FAILURE");}
					catch(e){}
					return;
				}
				if (rows.affectedRows > 0){//判断修改了多少个记录
					console.log("[editor]支付成功了，现在通知游戏服务器, 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("[editor] 订单 %s: 成功发货!", cp_order_id);
						} else{
							console.log("[editor] 订单 %s: 发货地址无效!", cp_order_id);//在无效时返回成功，我们自己补单中会派发flag为1支付成功但是没成功发货的单
						}
						try{res.send("SUCCESS");}
						catch(e){}
					});

					// 向 TalkingData 报告充值数据
					var appId = config.getAppID(channel);
					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重复写入[editor]已经处理的订单");
					try{res.send("SUCCESS");}
					catch(e){}
					return;
				}
			})
		}else{
			console.log("[editor] 查询订单列表错误，请检查数据表结构和sql语句:\n\t%s", qerr);
			try{res.send("FAILURE");}
			catch(e){}
			return;
		}
	})
}


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

router.post('/editor_pay_test', function(req, res) {
	var real_ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
	console.log("post wyhdpay,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{
			pay_success(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;