<?php


namespace app\index\controller;

class Home extends \think\Controller
{
	public function index() {
        $account=\think\Session::get("account");
		$datae = \think\Db::name("user")->field("Id,rmb,lock")->where("account", $account)->find();
		if ($datae["lock"] != 0) {
		    return "账号被锁定！";
		}
		$HH = pay_k("", true);
			$rate = \think\Db::name("charge_rate")->where('status',1)->find();
		if (empty($rate)) {
		    $this->assign(['rate'=>0]);
		}else{
		    $this->assign(['rate'=>$rate['rate']]);
		}
		$token = $this->request->token("__token__", "sha1");
			    $serverid=\think\Session::get("serverid");
	    $guid=\think\Session::get("guid");
		$this->assign(["token" => $token, "rmb" => $datae["rmb"], "HHHH" => $HH, "account" => $account,'server'=>$serverid,'guid'=>$guid]);

		return $this->fetch();

	}
	
	public function updatePassword(){
	     $request = \think\Request::instance()->post();
	     if($request) {
	         $account=\think\Session::get("account");
	         $password = $request["password"];
	         $password1 = $request["password1"];
	         $password2 = $request["password2"];
	         
	         if($password1 != $password2){
	             return $this->error("两次输入的新密码不一样");
	         }
	         
	         $datae = \think\Db::name("user")->field("password,lock")->where("account", $account)->find();
	         if ($datae["lock"] != 0) {
		        return "账号被锁定！";
		     }
		     
		     if($datae["password"] != md5($password)){
		         return $this->error("原密码不正确");
		     }
		     
		     if($password == $password1){
		         return $this->error("原密码和新密码相同");
		     }
		     
		     \think\Db::name("user")->where("account", $account)->update(["password" => md5($password1)]);
		     
		     return $this->fetch("success");
	     }else{
	         return $this->fetch();
	     }
	}
	
	public function buy(){
	    $request = \think\Request::instance()->post();
	    $serverid=\think\Session::get("serverid");
	    $guid=\think\Session::get("guid");
	    $account=\think\Session::get("account");
	    $datae = \think\Db::name("user")->field("Id,rmb,lock")->where("account", $account)->find();
	    if ($datae["lock"] != 0) {
		    return "账号被锁定！";
		}
	    $productId=$request["productId"];
    	$productInfo=pay_k($productId);
		$pay_amount = \intval($productInfo["nMoney"]);
		if ($datae["rmb"] < $pay_amount) {
		    $this->error("平台币不足");
		}else{
	        if(isset($productInfo["limit"])) {
	            $limit = $productInfo["limit"];
	            $limitType = $productInfo["limitType"];
	            if($limitType == 0){
	                $count = \think\Db::name("gamebuy_log")->where(["account"=> $account, 
                	        "server"=> $serverid, 
                	        "productId"=> $productId
                	        ])->count();
	            }else{
	                $count = \think\Db::name("gamebuy_log")->where(["account"=> $account, 
                	        "server"=> $serverid, 
                	        "productId"=> $productId
                	        ])->whereTime("time", "today")->count();
	            }
	            if($count >= $limit){
	                $errorMsg = "购买失败,超出购买限制！";
	                if($limitType == 0){
	                    $errorMsg = $errorMsg."该物品永久限购".$limit."次";
	                }else{
	                    $errorMsg = $errorMsg."该物品每日限购".$limit."次";
	                }
                     $this->error($errorMsg);
                     return;
	            }
	        }
	        $log_id = time().rand(1, 1000000);
	        $Testdata["log_id"] = $log_id;
	        $Testdata["account"] = $account;
			$Testdata["server"] = $serverid;
			$Testdata["guid"] = $guid;
			$Testdata["productId"] = $productId;
			$Testdata["productName"] = $productInfo["jiancheng"];
			$Testdata["price"] = $pay_amount;
			$Testdata["time"] = date("Y-m-d H:i:s", time());
			$Testdata["status"] = 0;
			\think\Db::name("gamebuy_log")->data($Testdata)->insert();
			
			$data_user = \think\Db::name("gameconfig")->where("server", $serverid)->field("ip,gmport")->find();
			
			$resultSendItem = $this->sendItems($serverid, $guid, $data_user["ip"], $data_user["gmport"], $productInfo);
			if($resultSendItem){
			    \think\Db::name("user")->where("account", $account)->setDec("rmb", $pay_amount);
	            \think\Db::name("user")->where("account", $account)->setInc("recharge", $pay_amount);
	            \think\Db::name("gamebuy_log")->where("log_id", $log_id)->update(["status" => 1]);
	            $this->assign(["jiancheng" => $productInfo["jiancheng"], "money" => $pay_amount, "msg" => "购买成功！"]);
				$goback='http://'.$_SERVER['HTTP_HOST'].'/index/Home';
    		    $this->assign('goback',$goback);
			    return $this->fetch("rmb");
			}
			return $this->error("购买失败！");
		}
	}
	
	private function sendItems($serverid, $guid, $ip, $port, $productInfo){
	    $url = "http://127.0.0.1:8877/gm";
			
		$getdata["server"] = $serverid;
		$getdata["guid"] = $guid;
		$getdata["cmd"] = "itemManage";
		$getdata["subcmd"] = "giveItem";
		$getdata["ip"] = $ip;
		$getdata["gmport"] = $port;
		$getdata["md5"] = md5("#".getSign()."#server*".$serverid."guid*".$guid."cmd*itemManage"."subcmd*giveItem"."#".getSign()."#");
	    
		$newarr = explode(";", $productInfo["goods"]);
		if (isset($newarr[0]) &&  count($newarr) <= 4) {
		    $attach_item=[];
			for ($i = 0; $i < count($newarr); $i++) {
				$newarrd = explode(",", $newarr[$i]);
				if (isset($newarrd[0]) && isset($newarrd[1])) {
					$attach_item[] = ["id" => $newarrd[0], "num" => $newarrd[1]];
				}
			}
			
			$getdata["body"] = json_encode([
    		    "player_list" => [\think\Session::get("guid")],
    		    "server_broadcast" => "0",
    		    "content" => "购买：".$productInfo["jiancheng"]."，价格：". $productInfo["nMoney"]."平台币",
    		    "items" => $attach_item
		        ]);
    		$returngm = http_curl($url, "get", $getdata);
    		
    		if ($returngm) {
    		    $returngm = json_decode($returngm, true);
    		    if($returngm["code"] == 1000){
    		        return true;
    		    }
    		}
		}else if(isset($newarr[0]) &&  count($newarr) > 4){
		    $attach_item1=[];
		    for ($i = 0; $i < 4; $i++) {
				$newarrd = explode(",", $newarr[$i]);
				if (isset($newarrd[0]) && isset($newarrd[1])) {
					$attach_item1[] = ["id" => $newarrd[0], "num" => $newarrd[1]];
				}
			}
			
			$getdata["body"] = json_encode([
    		    "player_list" => [\think\Session::get("guid")],
    		    "server_broadcast" => "0",
    		    "content" => "购买：".$productInfo["jiancheng"]."，价格：". $productInfo["nMoney"]."平台币",
    		    "items" => $attach_item1
    		    ]);
    		$returngm1 = http_curl($url, "get", $getdata);
    		
    		$attach_item2=[];
		    for ($i = 4; $i < count($newarr); $i++) {
				$newarrd = explode(",", $newarr[$i]);
				if (isset($newarrd[0]) && isset($newarrd[1])) {
					$attach_item2[] = ["id" => $newarrd[0], "num" => $newarrd[1]];
				}
			}
			
			$getdata["body"] = json_encode([
    		    "player_list" => [\think\Session::get("guid")],
    		    "server_broadcast" => "0",
    		    "content" => "购买：".$productInfo["jiancheng"]."，价格：". $productInfo["nMoney"]."平台币",
    		    "items" => $attach_item2
    		    ]);
    		$returngm2 = http_curl($url, "get", $getdata);
    		
    		if ($returngm1 && $returngm2) {
    		    $returngm1 = json_decode($returngm1, true);
    		    $returngm2 = json_decode($returngm2, true);
    		    if($returngm1["code"] == 1000 && $returngm2["code"] == 1000){
    		        return true;
    		    }
    		}
		}
		return false;
	}
	
}