//GooglePlay
let mysql = require('mysql');
let mysqlcn = require('../../terry/mysqlcn.js');
let query = mysqlcn.query;
let qs = require('querystring');
let checkorder = require('../../terry/checkorder.js');
let config = require('../config.js');
let express = require('express');
let router = express.Router();
let crypto = require('crypto');

// let IS_TEST = 2 //1是测试2是正式
Date.prototype.Format = function (fmt) { //author: meizz
	let o = {
			"M+": this.getMonth() + 1, //月份
			"d+": this.getDate(), //日
			"h+": this.getHours(), //小时
			"m+": this.getMinutes(), //分
			"s+": this.getSeconds(), //秒
			"q+": Math.floor((this.getMonth() + 3) / 3), //季度
			"S": this.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (let k in o)
	if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

let sql_insert = function(orderid, serverid,uid,rmb,moneytype,cfid,platform,channel,overtime,flag,product_id,user_id,purchase_date_ms,talkingdata,payment_type,istest){
    let sql = "INSERT INTO payinfo SET orderid=?, serverid=?, channel=?, submittime=?, flag=?, user_id=?, channel_order_id=?, money=?, cfid=?, platform=?,overtime=?,product_id=?,uid=?,moneytype=?,talkingdata=?,payment_type=?,istest=?";
    let values = [orderid, serverid, channel,purchase_date_ms,flag,user_id,orderid,rmb,cfid,platform,overtime,product_id,uid,moneytype,talkingdata,payment_type,istest];
    sql = mysql.format(sql, values);
    return sql;
}

function insert_str(str, insert_str, sn) {
    let newstr = "";
    for (let i = 0; i < str.length; i += sn) {
        let tmp = str.substring(i, i + sn);
        newstr += tmp + insert_str;
    }
    return newstr;
}

let RsaSha1Check = function(str,sig,publicKey){
    let public_key = insert_str(publicKey, '\n', 64);
    public_key = '-----BEGIN PUBLIC KEY-----\n' + public_key + '-----END PUBLIC KEY-----';

    let verifier = crypto.createVerify('RSA-SHA1');
    console.log('验证签名public key:\n' + public_key);
    console.log('验证签名src_sign:' + str);
    verifier.update(new Buffer(str, 'utf-8'));
    return verifier.verify(public_key, sig, 'base64');
};

let pay_success = function(args, res){
    if (args==null){
        console.log("[GooglePlay] 无效的充值请求!");
        try{res.send("error,1");}
        catch(e){}
        return;
    }

    let obj = null
    try {
        obj = qs.parse(args);
    } catch(e){
        console.log("[GooglePlay] 无效的充值请求!");
        try{res.send("error,1");}
        catch(e){}
        return
    }

    let orderid = obj.orderid;  //订单号
    let channel_order_id = obj.channel_order_id //渠道订单id
    let serverid = obj.serverid;//服务器id
    let userid = obj.userid;    //玩家的渠道帐号
    let uid = obj.uid;          //玩家游戏uid
    let cfid = obj.cfid         // 计费点
    let platform = "googleplay";
    let ti = new Date().Format("yyyy-MM-dd hh:mm:ss");

    console.log("[GooglePlay] 订单 %s 请求 (%s):\n\tchannel_order_id=%s, serverid=%s,uid=%s,userid=%s,platform=%s",
                            orderid, ti, channel_order_id, serverid, uid, userid, platform);


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

            //检查订单
			let channel = vals[0].channel
            let conf = config.parse(platform, channel, cfid);
            let amountnum = conf.price
            let moneytype = conf.typename;
            if (conf.cfid == 0){
                console.log("[GooglePlay] channel:%s获取cfid失败为platform:%s,cfid:%s",channel, platform, cfid);
                try{res.send("fail");}
                catch(e){}
                return
            }

            console.log("[GooglePlay] 订单 %s 处理:\n\t商品配置:%s, 金额:%s, 类型:%s, 用户:%s, 服务器:%s",
                channel_order_id,cfid,amountnum,moneytype,uid,serverid);

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

router.post('/googleplay', function(req, res) {
	console.log("谷歌,post ,host:%s, ip:%s,date:%s",req.hostname,req.ip,new Date());
   let data = "";
   req.on("data",function(chunk){
	 data += chunk;
   })
   req.on("end",function(){
        pay_success(data,res);
   })
   req.on("error",function(err){
	   res.send('erron,1');
   })
});

module.exports = router;
