//检查订单间隔
var mysql = require('mysql');
var mysqlcn = require('../../terry/mysqlcn.js');    
var qs = require('querystring');   
var http = require('http');
var query = mysqlcn.query;

var USER = "yytx";
var PWD = "lee@YY-Games.520";

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

//查询游戏服务器列表
var sql_select_server = function(id){
   var sql = "SELECT * FROM services WHERE id = ?"; 
   var inserts = [id]; 
   sql = mysql.format(sql, inserts);
   return sql;
}

//查询玩家是否被封号
var sql_select_uid = function(id){
   var sql = "SELECT * FROM prohibition_info WHERE uid = ?"; 
   var inserts = [id];
   sql = mysql.format(sql, inserts);
   return sql;
}

//封号
function prohibition(uid,serverid){
    var sql = sql_select_server(serverid);
    query(sql,function(qerr,vals,fields){
        if (vals.length>0){
            queryRet = vals[0];				

            //content={"receiver":"00-6326686271099908096","times":10}
            var content = {  
                'receiver': uid,  
                'times': 99999999,
            };  
            content = JSON.stringify(content);
            var data2game = {
                'user' : USER,
                'pwd' : PWD,
                'content' : content,
            }

            data2game = JSON.stringify(data2game);  
            //console.log("data2game:%s",data2game)
            var opt = {  
                method: "POST",
                host: queryRet.ip,  
                port: queryRet.port,  
                path: "/forbidden",  
                headers: {
                    "Content-Type": 'application/json',  
                    "Content-Length": data2game.length
                }  
            };  
            
            var req = http.request(opt, function (res){  
                if (res.statusCode == 200){  
                    var datas = [];  
                    var size = 0; 
                    res.on('data', function (data){
                        datas.push(data);  
                        size += data.length;
                    });  
                    res.on('end', function (){
                        var buff = Buffer.concat(datas, size);  
                        var result = buff.toString();
                        var result = JSON.parse(result);
                        if (parseInt(result.errno)==200){
                            // 至此，一笔充值圆满的结束了
                            console.log("[IOS短间隔充值封号] 请求封号成功,result.errno:%s",result.errno);
                        } 
                        else{
                            console.log("[IOS短间隔充值封号] 请求封号失败3,result.errno:%s,result.info:%s",result.errno,result.info);
                        }
                    });  
                    res.on('error', function (err){
                        console.log(err);
                        console.log("[IOS短间隔充值封号] 请求封号失败2");
                    });  
                }  
            }).on('error', function(){
                console.log("[IOS短间隔充值封号] 请求封号失败1");
            });  
            req.write(data2game);
            req.end(); 
        }else {
            console.log("[IOS短间隔充值封号] 查询角色服务器失败");
        }
    })
}

function get_orderid(overtime,uid,orderid_a){
    var sql = mysql.format("SELECT * FROM payinfo where overtime=? AND uid=?", [overtime,uid]);//在mysql库中检查订单号
	query(sql,function(qerr,vals,fields){
		if (qerr==null){
			if (vals[0]==null){
				//console.log("[查询订单] 没有找到该订单");
				return ;
			}
			if (vals[0].overtime>0 && orderid_a != vals[0].orderid){
                console.log("[查询订单] 得到订单:%s,时间:%s,本次时间:%s",vals[0].orderid,vals[0].overtime,overtime);
                var orderid = vals[0].orderid;
                var serverid = vals[0].serverid
                
                //记录有短间隔的订单对玩家封号
                var sql = sql_insert(vals[0].orderid, vals[0].serverid,vals[0].uid,vals[0].money,vals[0].moneytype,vals[0].cfid,vals[0].platform,vals[0].channel,vals[0].overtime,0,vals[0].product_id,vals[0].user_id,vals[0].submittime,0)
                query(sql,function(qerr,vals,fields){
                    try	{
                        if (qerr) {
                            if (qerr.errno == 1062) {
                                // 视为成功，但不再封号。
                            } else {
                                console.log("[IOS短间隔充值封号] 订单 %s: 存储失败!\n\t%s",orderid, JSON.stringify(qerr));
                            }
                        } else {
                            //通知游戏服封号
                            var sql = sql_select_uid(uid);
                            query(sql,function(qerr,vals,fields){
                                if (vals.length>=4){
                                    console.log("[IOS短间隔充值封号] 角色将被封号,uid:%s",uid);
                                    prohibition(uid,serverid)
                                }else {
                                    console.log("[IOS短间隔充值封号] 角色未被封号,uid:%s,overtime:%s",uid,overtime);
                                }
                            })
                        }
                    } catch(err) {
                        console.log(err);
                    }
                })
            }
		}else{
			console.log("[IOS短间隔充值封号] 查询订单列表错误，请检查数据表结构和sql语句:\n\t%s", qerr);
			return ;
		}
    })
}

exports.orderid_interval = function(uid,overtime,orderid){
    for(var i = 0; i < 4; ++i){
        var now_overtime = overtime - i
        //console.log("[IOS短间隔充值封号] 角色未被封号,uid:%s,overtime:%s,now_overtime:%s",uid,overtime,now_overtime);
        get_orderid(now_overtime,uid,orderid)
        // query(sql,function(qerr,vals,fields){
        //     if (vals.length>0){
        //         console.log("[IOS短间隔充值封号] 角色已经封号,uid:%s,now_overtime:%s",uid,now_overtime);
        //     }else {
        //         console.log("[IOS短间隔充值封号] 角色未被封号,uid:%s,overtime:%s,now_overtime:%s",uid,overtime,now_overtime);
        //         get_orderid(now_overtime,uid)
        //     }
        // })
    }
}