<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */


namespace BL\app\controller;

use BL\app\libs\Controller;
use BL\app\controller\PayBase;

/**免签控制器
 * Class index
 * @package BL\app\controller
 */
class mq extends Controller
{
    
   public function pay(){
       
        $data = array('title' => '扫码支付');
        $this->put('pay.php', $data);
    }
   
    public function getReturn($code = 1, $msg = "成功", $data = null)
    {
        return array("code" => $code, "msg" => $msg, "data" => $data);
    }
    //创建订单
    public function createOrder()
    {
        $this->closeEndOrder();
        $payId = $this->req->get('payId');
        if (!$payId || $payId == "") {
           exit("请传入商户订单号");
        }
        $type = $this->req->get("type");
        if (!$type || $type == "") {
            exit("请传入支付方式");
        }
        if ($type != 3 && $type != 2&& $type != 1) {
            exit("支付方式错误");
        }

        $price = $this->req->get("price");
        if (!$price || $price == "") {
            exit("请传入订单金额");
        }
        if ($price <= 0) {
            exit("订单金额必须大于0");
        }

        $sign = $this->req->get("sign");
        if (!$sign || $sign == "") {
            exit("请传入签名");
        }

        $isHtml = $this->req->get("isHtml");
        if (!$isHtml || $isHtml == "") {
            $isHtml = 0;
        }
        $param = $this->req->get("param");
        if (!$param) {
            $param = "";
        }

        $res = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "keyl"'))->fetchRow();
        $key = $res['value'];
        $_sign = md5($payId . $param . $type . $price . $key);
        if ($sign != $_sign) {
            exit("签名错误");
        }

        $jkstate =$this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "jkstate"'))->fetchRow();
        $jkstate = $jkstate['value'];
        
        if ($jkstate!="1"){
            exit("监控端状态异常，请检查");

        }
        $reallyPrice = bcmul($price ,100);
        
        $payQf = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "payQf"'))->fetchRow();
        $payQf = $payQf['value'];


        $orderId = date("YmdHms") . rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9);

        $ok = false;
        for ($i = 0; $i < 300; $i++) {
            $tmpPrice = $reallyPrice . "-" . $type;
            
                $tmpdata = array('price' => $tmpPrice, 'oid' => $orderId, 'create_date' => time());
                $row = $this->model()->from('mqtmp_price')->insertData($tmpdata)->insert();
              if ($row) {
                    $ok = true;
                    break;
                }
           
            if ($payQf == 1) {
                $reallyPrice++;
            } else if ($payQf == 2) {
                $reallyPrice--;
            }
        }

        if (!$ok) {
            exit("订单超出负荷，请稍后重试");
        }
        //echo $reallyPrice;

        $reallyPrice = bcdiv($reallyPrice, 100,2);

        if ($type == 3) {
            $payUrl = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "wxpay"'))->fetchRow();
            $payUrl = $payUrl['value'];

        } else if ($type == 2) {
            $payUrl = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "jhpay"'))->fetchRow();
            $payUrl = $payUrl['value'];
        } else if ($type == 1) {
            $payUrl = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "alipay"'))->fetchRow();
            $payUrl = $payUrl['value'];
        }
        if ($payUrl == "") {
            exit("请您先进入后台配置程序");
        }
        $isAuto = 1;
        
        $_payUrl = $this->model()->select()->from('mqqrcode')->where(array('fields' => 'type = ? AND price = \''.$reallyPrice.'\'', 'values' => [$type]))->fetchRow();
            
        if ($_payUrl) {
            $payUrl = $_payUrl['pay_url'];
            $isAuto = 0;
        }
    	$res = $this->model()->from('mqorder')->where(array('fields' => '`pay_id` =\''.$payId.'\''))->delete();
        if ($res) {
            exit("商户订单号已存在");
        }




        $createDate = time();
        $data = array(
            "close_date" => 0,
            "create_date" => $createDate,
            "is_auto" => $isAuto,
            "order_id" => $orderId,
            "param" => $param,
            "pay_date" => 0,
            "pay_id" => $payId,
            "pay_url" => $payUrl,
            "price" => $price,
            "really_price" => $reallyPrice,
            "state" => 0,
            "type" => $type,
        );
        
        
       $dingdan=$this->model()->from('mqorder')->insertData($data)->insert();
       if ($dingdan) {
            return $this->res->redirect($this->dir . 'pay?orderId='.$orderId);
        }else{
            exit("订单信息错误r");
        }
        

        


    }
    //获取订单信息
    public function getOrder()
    {
        header('Content-Type:application/json');  //此声明非常重要
        $this->closeEndOrder();
        $res = $this->model()->select()->from('mqorder')->where(array('fields' => '`order_id` = \''.$this->req->post("orderId").'\''))->fetchRow();
        if ($res){
            
            $time = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "close"'))->fetchRow();
            $data = array(
                "payId" => $res['pay_id'],
                "orderId" => $res['order_id'],
                "payType" => $res['type'],
                "price" => $res['price'],
                "reallyPrice" => $res['really_price'],
                "payUrl" => $res['pay_url'],
                "isAuto" => $res['is_auto'],
                "state" => $res['state'],
                "timeOut" => $time['value'],
                "param" => $res['param'],
                "date" => $res['create_date']
            );
            exit(json_encode($this->getReturn(1, "成功", $data)));
        }else{
            exit(json_encode($this->getReturn(-1, "云端订单编号不存在")));
        }
    }
    
    
    
    
    //查询订单状态
    public function checkOrder()
    {
        header('Content-Type:application/json');  //此声明非常重要
        $this->closeEndOrder();
        $res = $this->model()->select()->from('mqorder')->where(array('fields' => '`order_id` = \''.$this->req->post("orderId").'\''))->fetchRow();
        if ($res){
            if ($res['state']==0){
                exit(json_encode($this->getReturn(-1, "订单未支付"), JSON_UNESCAPED_UNICODE));
            }
            if ($res['state']==-1){
                exit(json_encode($this->getReturn(-1, "订单已过期"), JSON_UNESCAPED_UNICODE));
            }


            $res['price'] = number_format($res['price'],2,".","");
            $res['really_price'] = number_format($res['really_price'],2,".","");
            exit(json_encode($this->getReturn(1, "成功"), JSON_UNESCAPED_UNICODE));
        }else{
            exit(json_encode($this->getReturn(-1, "云端订单编号不存在"), JSON_UNESCAPED_UNICODE));
        }

    }
    
    //获取监控端状态
    public function getState(){
      
        $this->closeEndOrder();
        $res2 = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "keyl"'))->fetchRow();
        $key = $res2['value'];
        $t = $this->req->get("t");

        $_sign = $t.$key;

        if (md5($_sign)!=$this->req->get("sign")){
            exit(json_encode($this->getReturn(-1, "签名校验不通过")));
        }


        $res2 = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "lastheart"'))->fetchRow();
        $lastheart = $res['value'];
        
        $res2 = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "lastpay"'))->fetchRow();
        $lastpay = $res['value'];
        
        $res2 = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "jkstate"'))->fetchRow();
        $jkstate = $res['value'];

        exit(json_encode($this->getReturn(1, "成功",array("lastheart"=>$lastheart,"lastpay"=>$lastpay,"jkstate"=>$jkstate))));

    }

    //App心跳接口
    public function appHeart(){
        header('Content-Type:application/json');  //此声明非常重要
        $this->closeEndOrder();
        $res2 = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "keyl"'))->fetchRow();
        $key = $res2['value'];
        $t = $this->req->get("t");

        $_sign = $t.$key;

        if (md5($_sign)!=$this->req->get("sign")){
            exit(json_encode($this->getReturn(-1, "签名校验不通过")));
        }

        $jg = time()*1000 - $t;
        if ($jg>50000 || $jg<-50000){
            exit(json_encode($this->getReturn(-1, "客户端时间错误")));
        }

        $this->model()->from('mqsetting')->updateSet(array("value"=>1))->where(array('fields' => '`key` = "jkstate"'))->update();
        $this->model()->from('mqsetting')->updateSet(array("value"=>time()))->where(array('fields' => '`key` = "lastheart"'))->update();
        
        
        exit(json_encode($this->getReturn(), JSON_UNESCAPED_UNICODE));
    }
    //App推送付款数据接口
    public function appPush(){
        header('Content-Type:application/json');  //此声明非常重要
        $payDao = new PayBase();
        $this->closeEndOrder();
        $res2 = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "keyl"'))->fetchRow();
        $key = $res2['value'];
        $t = $this->req->get("t");
        $type = $this->req->get("type");
        $price = $this->req->get("price");
        $_sign = $type.$price.$t.$key;
        if (md5($_sign)!=$this->req->get("sign")){
           exit(json_encode($this->getReturn(-1, "签名校验不通过")));
        }
        $jg = time()*1000 - $t;
        if ($jg>50000 || $jg<-50000){
            exit(json_encode($this->getReturn(-1, "客户端时间错误")));
        }

        $this->model()->from('mqsetting')->updateSet(array("value"=>time()))->where(array('fields' => '`key` = "lastpay"'))->update();
        $res = $this->model()->select()->from('mqorder')->where(array('fields' => 'type = ? AND state=0 AND really_price = \''.$price.'\'', 'values' => array($type)))->fetchRow();
        
        if ($res){
	       $this->model()->from('mqtmp_price')->where(array('fields' => '`oid` =\''.$res['order_id'].'\''))->delete();
            $this->model()->from('mqorder')->updateSet(array("state"=>1,"pay_date"=>time(),"close_date"=>time()))->where(array('fields' => 'id=?', 'values' => array($res['id'])))->update();			
			//发卡平台订单业务处理										
				//发卡平台订单业务处理
        		if($res['type']==1){
        	         $model="支付宝";
        		}	
        		if($res['type']==2){
        	         $model="聚合码";
        		}	
        		if($res['type']==3){
        	         $model="微信";
        		}
                $payDao->updateOrder($res['pay_id'],$model,$res['order_id']);
				
		  //发卡平台订单业务处理			
		  


        }else{
            $data = array(
                "close_date" => 0,
                "create_date" => time(),
                "is_auto" => 0,
                "order_id" => "无订单转账",
                "param" => "无订单转账",
                "pay_date" => 0,
                "pay_id" => "无订单转账",
                "pay_url" => "",
                "price" => $price,
                "really_price" => $price,
                "state" => 1,
                "type" => $type

            );
            $row = $this->model()->from('mqorder')->insertData($data)->insert();
            exit(json_encode($this->getReturn(), JSON_UNESCAPED_UNICODE));

        }


    }
    
    

   //关闭过期订单接口(请用定时器至少1分钟调用一次)
    public function closeEndOrder(){

        $res = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "lastheart"'))->fetchRow();
        $lastheart = $res['value'];
        if ((time()-$lastheart)>60){
            
        $this->model()->from('mqsetting')->updateSet(array("value"=>0))->where(array('fields' => '`key` = "jkstate"'))->update();
        }
        $time = $this->model()->select()->from('mqsetting')->where(array('fields' => '`key` = "close"'))->fetchRow();
        $closeTime = time()-(60*$time['value']);
        $close_date = time();
        $updata=array("state"=>-1,"close_date"=>$close_date);
        $res= $this->model()->from('mqorder')->updateSet($updata)->where(array('fields' => '`state` = 0 AND `create_date` <=  \''.$closeTime.'\'  '))->update();
    	$tmp =$this->model()->from('mqtmp_price')->where(array('fields' => '`create_date` <=\''.$closeTime.'\''))->delete();
           

    }

}