//QUICK
var mysql = require('mysql');
var config = require('../../pay/config');
var crypto = require('crypto');
var qs = require('querystring');
var checkorder = require('../checkorder');

//md5加密
var md5 = function (str){
	var md5sum = crypto.createHash('md5');
	md5sum.update(str);
	str = md5sum.digest('hex');
	return str;
};

//充值成功的时候修改库中数据
var sql_update_quick = function(order_no,timestamp,flag,ordermoney,cfida,platform,channel,payment_type,moneytype,sdcustomno){  
	//填充充值信息				
	 var sql_2 = "UPDATE payinfo SET channel_order_id=?,overtime=?,flag=?,money=?,cfid=?,platform=?,channel=?,payment_type=?,moneytype=?,talkingdata=? WHERE orderid=? AND flag=2";
	 var timestamp = Date.parse(new Date()) / 1000;
	 var cfid = ordermoney; 
	 var values_2 = [order_no,timestamp,1,ordermoney,cfida,platform,channel,payment_type,moneytype,1,sdcustomno];
	 var sql = mysql.format(sql_2, values_2);
	 return sql;
 }
 
exports.quick_pay_success = function(args,query,res,quick_proto){
	var obj = qs.parse(args);
	// var nt_data = obj.nt_data;  				//通知数据(XML格式)
	// var sign = obj.sign;        				//签名串
	// var md5Sign = obj.md5Sign;  				//string 签名计算方法为MD5
	 var outputname = quick_proto.outputname 	//使用quick的渠道
	 var callback_key = quick_proto.callback_key //quick解密编码
    // var md5_key = quick_proto.md5_key			//MD5加密编码

    var uid = obj.uid //必传购买道具的用户uid
    var username = obj.username//必有购买道具的用户username
    var cpOrderNo = obj.cpOrderNo//可为空游戏下单时传递的游戏订单号，原样返回
    var orderNo = obj.orderNo//必有SDK唯一订单号
    var payTime = obj.payTime//必有用户支付时间，如2017-02-0614:22:32
    var payAmount = obj.payAmount//必有用户支付金额
    var payCurrency = obj.payCurrency//必有用户支持的币种，如RMB，USD等
    var payType = obj.payType//表示支付方式的   30是谷歌支付 8为appstore支付  其他的为第三方金流渠道
    var usdAmount = obj.usdAmount//必有用户支付的游戏道具以美元计价的金额
    var extrasParams = obj.extrasParams//可为空游戏下单时传递的扩展参数，将原样返回。//额外参数，现在使用的配置sid
    var sign = obj.sign//必有签名值，游戏应根据签名约定，本地计算后与此值进行比对

    var payStatus = obj.payStatus
    var actRate = obj.actRate

	console.log(outputname+"quick回调来了");
    console.log(args);
    
    //验证签名
    // var strsign = 'actRate='+actRate+
    // "&cpOrderNo="+cpOrderNo+
    // "&extrasParams="+extrasParams+
    // "&orderNo="+orderNo+
    // "&payAmount="+payAmount+
    // "&payCurrency="+payCurrency+
    // "&payStatus="+payStatus+
    // "&payTime="+payTime+
    // "&payType="+payType+
    // "&uid="+uid+
    // "&usdAmount="+usdAmount+
    // "&username="+username+"&"+callback_key;
    // var url_sort = config.url_sort(obj)
    // var strsign = url_sort +"&"+callback_key;

	var sort_data = Object.keys(obj).sort();
	// 生成本地签名验证签名
	var strsign = sort_data[0] + "=" + obj[sort_data[0]];
	for(var i=1;i<sort_data.length;i++){
		if(sort_data[i] != "sign"){
			strsign = strsign + '&'+ sort_data[i] +"="+ obj[sort_data[i]]
		}
	}
    strsign = strsign + "&" + callback_key;
    

    // var strsign = 'actRate='+actRate+
    // "&cpOrderNo="+cpOrderNo+
    // "&extrasParams="+extrasParams+
    // "&orderNo="+orderNo+
    // "&payAmount="+payAmount+
    // "&payCurrency="+payCurrency+
    // "&payStatus="+payStatus+
    // "&payTime="+payTime+
    // "&payType="+payType+
    // "&uid="+uid+
    // "&usdAmount="+usdAmount+
    // "&username="+username+"&"+callback_key;
    var genSign = md5(strsign);
    if(sign != genSign){
        console.log(outputname+"quick支付签名验证失败,sign:%s,genSign:%s,strsign:%s",sign,genSign,strsign);
        try{res.send("FAILED");}
        catch(e){}
        return;
    }

    try{
        var sql_1 = mysql.format("SELECT * FROM payinfo where orderid=?", [cpOrderNo]);//在mysql库中检查订单号
        query(sql_1,function(qerr,vals,fields_)
        {
            console.log("quick_pay_success,1");
            if(qerr){
                //"逻辑错误，请检查数据表结构和sql语句"
                console.log(outputname+"quick逻辑错误，请检查数据表结构和sql语句");
                try{res.send("FAILED");}
                catch(e){}
                return;
            }

            if (vals[0]==null){
                console.log(outputname+"quick没有找到该订单");
                try{res.send("FAILED");}
                catch(e){}
                return;
            }

            if (vals[0].overtime>0){
                console.log(outputname+"quick已经处理的订单");
                try{res.send("SUCCESS");}
                catch(e){}
                return;
            }
            
            var info_s = extrasParams.split('|');
            var len = info_s.length;
            var platform;// 只存储 ios 和 android
            var product_id;
            if (len > 1) {
                platform = info_s[1];
                if (platform == 'ios'){
                    product_id = info_s[0];
                }else if(platform == 'android'){
                    product_id = parseInt(info_s[0]);
                }else{
                    console.log(outputname+"quick错误的平台platform:%s",platform);
                    try{res.send("FAILED");}
                    catch(e){}
                    return;
                }
            }else{
                console.log(outputname+"quick获取产品包失败extrasParams:%s",extrasParams);
                try{res.send("FAILED");}
                catch(e){}
                return;
            }
    
            //var des = "null";//描述订单支付成功或失败的系统备注
            var remarks = vals[0].remarks
            var channel = quick_proto.channel;			// 只存储 qianxun、zaya、limayao, zhangyu, friday, wudiyongshi, banli, zhiyu, cloud
            var payment_type = "QUICK";//pay_channel.toString();	// 具体的子渠道，比如 quick 的 微信、手Q、UC、应用宝等， 新增一个 paymentType 字段来填充
            var timestamp = Date.parse(new Date()) / 1000;
            var option = config.parse(platform,channel,product_id);
            var cfid = option.cfid;//购买商品ID--parseInt转int
            if (cfid == 0){
                console.log(outputname+"QUICK获取cfid失败为:%s,channel:%s,product_id:%s,platform:%s", cfid,channel,product_id,platform);
                try{res.send("FAILED");}
                catch(e){}
                return;
            }

           if (usdAmount != option.price){
               console.log(outputname+"QUICK金额不一致为usdAmount:%s,option.price:%s", usdAmount,option.price);
               try{res.send("FAILED");}
               catch(e){}
               return;
           }

           var price = option.price;
           var typename = option.typename;
           if (remarks){
               if(remarks == "fr" || remarks == "de"){
                   price = option.price_eur
                   typename = option.typename_eur
               }
           }

            var sql_2 = sql_update_quick(orderNo,timestamp,1,usdAmount,cfid,platform,channel,payType,option.typename,cpOrderNo)
            query(sql_2,function(qerr,rows,fields_)
            {
                if (qerr){
                    console.log(qerr);
                    try{res.send("FAILED");} //"逻辑错误，请检查数据表结构和sql语句"}
                    catch(e){}
                    return;
                }
                
                if (rows.affectedRows <= 0){//判断修改了多少个记录
                    console.log(outputname+"quick已经处理的订单");
                    try{res.send("SUCCESS");}
                    catch(e){}
                    return;
                }

                console.log(outputname+"quick支付成功了，现在通知游戏服务器, cpOrderNo:%s, username:%s, playerid:%s, serverid:%s ,cfid:%s",
                cpOrderNo,vals[0].username,vals[0].playerid,vals[0].serverid,cfid);
                //send_2_game(query,cpOrderNo,vals[0].username,vals[0].playerid,vals[0].serverid,cfid, function(ok){
                checkorder.pushproduct(query,cpOrderNo,vals[0].uid,vals[0].serverid,cfid, function(ok){
                        if (ok) {
                            console.log(outputname+"海外QUICK 订单 %s: 成功发货!", cpOrderNo);
                            try{res.send("SUCCESS");}
                            catch(e){}
                        } else{
                            console.log(outputname+"海外QUICK 订单 %s: 发货地址无效!", cpOrderNo);
                            try{res.send("FAILED");}
                            catch(e){}
                        }
                    });

                // 向 TalkingData 报告充值数据
                var appId = config.getAppID(channel);
                console.log(outputname+"海外QUICK 向 TalkingData 报告充值数据 appId:%s,channel:%s", appId,channel);
                checkorder.pushtalkingdata(query,appId,platform,vals[0].uid,cpOrderNo,price,typename,option.diamond,timestamp,payment_type,vals[0].serverid);
                
            })
        });
    }catch(err){
        console.log(outputname+"quick_err ,%s",err);
        try{res.send("FAILED");}
        catch(e){}
    }
}
