<?php
namespace app\pay\controller;

use think\Db;
use think\Cache;
use think\Controller;
class Pay extends Commone {
	public function pay() {
		$config_set_status = Db::name('set')->where('key','pay_no_status')->find();
		$config_set_msg = Db::name('set')->where('key','pay_no_msg')->find();
		if ($config_set_status['value'] == '2') {
			msgJson('', 1000, $config_set_msg['value']);
		}
		
		$orderid = $this->request->param('orderid');
		if(!$orderid) {
			$info = trim(xss($this->request->param('record')));
			if (empty($info)) {
				msgJson('', 1001, 'record（附加信息：如商户网站的订单号或用户名）参数错误');
			}
			//充值金额
			$money_index = floatval($this->request->param('money'));
			if ($money_index <= 0) {
				msgJson('', 1002, 'money（金额）参数错误');
			}
			//api_id
			$api_id = xss($this->request->param('api_id'));
			if (empty($api_id)) {
				msgJson('', 1003, '商户ID参数不可为空');
			}
			//refer来源
			$refer = urlencode($this->request->param('refer'));
			if (empty($refer)) {
				msgJson('', 1004, '订单错误,来源不明');
			}
			//notify_url 异步通知地址
			$notify_url = xss($this->request->param('notify_url'));
			if (empty($notify_url)) {
				msgJson('', 1005, '回调通知地址不可为空');
			}
			$user = Db::name('user')->where('api_id', $api_id)->find();
			if (!$user) {
				msgJson('', 1006, '商户ID不存在');
			}
			$mid = $this->request->param('mid');
			$sign = $this->request->param('sign');
			//验证签名
			$sign_data = ['api_id' => $api_id, 'record' => $info, 'money' => sprintf("%.2f", $money_index)];
			$sign_index = md5_sign($sign_data, $user['api_key']);
			$lx_land = '';
			if ($sign != $sign_index){
			    msgJson('', 1007, '签名错误');
			}
			
			if ($user['balance'] < $money_index * ($user['pay_sxf']/100)) {
				msgJson('', 1008, '商户余额不足');
			}
			$land = $this->land_1($user['id'],$money_index,$mid);
			if ($land == '-1') {
				msgJson('', 1016, '暂无账户可用,请稍后再试');
			}
			//取游戏通道编码
			$game_data = Db::name('game_list')->where('id','in',config('game_id'))->where('id', $land['typec'])->find();
			if (!$game_data) {
				msgJson('', 1014, '通道不存在');
			}
			if ($game_data['game_status'] == 0) {
				msgJson('', 1015, '通道已关闭');
			}
			$order_num = date("YmdHis") . time() . mt_rand(10000, 99999);
			//订单号 29 位
			$game_dm = $game_data['game_dm'] . '_pay';
			if($game_dm=='alipay_dmf_pay') {
				$json = json_decode($land['json'], true);
				$json['order_num'] = $order_num;
				$land['json'] = json_encode($json);
			}
			
			
		    $cls = model("\\app\common\\game\\".ucfirst($game_data['game_dm']));		    
			$sy_order = $cls->pay(json_decode($land['json'], true), $money_index, $land['id']);
			if ($sy_order['order_message'] == '抱歉，您的订单无效，请重新购买！' && $game_dm == 'hy_zb_pay') {
				//再次发起虎牙订单
				$sy_order = $this->$game_dm(json_decode($land['json'], true), $money_index, $land['id']);
			}
			if ($sy_order['order_message'] == 'ok') {
				//开始创建订单
				$hy_json = json_encode(array('hy_sign' => $sy_order['hy_sign'], 'hy_time' => $sy_order['hy_time']));
				//订单创建时间
				$order_time = time();
				//创建订单到数据库
				$sy_order['game_dm'] = $game_dm;
				$sy_order['refer'] = urldecode($refer);
				$insert_order = Db::name('orders')->insert(
				   array('land_id' => $land['id'], 
				         'userid' => $user['id'],
				         'num' => $order_num,
				         'money' => $money_index,
				         'remark' => $info,
				         'payc' => $game_data['id'],
				         'pay_time' => 0,
				         'state' => 1,
				         'order_time' => $order_time,
				         'notify_url' => $notify_url,
				         'syorder' => $sy_order['order_id'],
				         'hy_json' => $hy_json,
				         'order_url'=>json_encode($sy_order)
				    ));
				if($insert_order){
				    
				    dm_html($game_dm,$order_num,$sy_order['order_id'],$refer,0);
				    header('location:http://' . $_SERVER['HTTP_HOST'] . '/?orderid=' . $order_num);
				    exit;
			     	
				}else{
			     	msgJson('', 1017, '平台订单创建失败');
			    }
			    
			
			} else {
			    //开始判断异常监控是否为0
			    $this->bug_set($user['id'],$land['id']);
				msgJson('', 1018, '上游订单创建失败（错误信息：'.$sy_order['order_message'].')');
			}
		} else {
			$where_order['num'] = $orderid;
			$where_order['state'] = 1;
			$order_find = Db::name('orders')->where($where_order)->find();
			if(!$order_find) {
				msgJson('', 1019, '订单异常,请联系客服');
			} else {
				$sy_order = json_decode($order_find['order_url'],true);
				$game_dm = $sy_order['game_dm'];
				$order_num = $order_find['num'];
				$sy = $order_find['syorder'];
				$refer = $sy_order['refer'];
				$order_time = $order_find['order_time'];
				$money_index = $order_find['money'];
				dm_html($game_dm,$order_num,$sy,$refer,1);
			}
		
				$muban = $sy_order['order_mb'];
				$data = array('money' => $money_index, 'order_num' => $order_num, 'order_time' => date('Y-m-d H:i:s',$order_time), 'refer' => urldecode($refer), 'order_sy' => $sy_order['order_id'], 'order_url' => $sy_order['order_url'], 'alipay_url' => $sy_order['alipay_url'], 'order_mb' => $sy_order['order_mb']);
				$pay_msg_set = config_set('pay_msg_set');
				$order_time_set = config_set('order_time_set');
                $this->assign('pay_smg_set',$pay_msg_set['value']);
                $this->assign('order_time_set',$order_time_set['value']);
				$this->assign('data', $data);
				
				return view($muban);
			
		}
	}
	public function orders() {
		$num = $this->request->param('num');
		//订单号
		$syorder = $this->request->param('syorder');
		//上游订单号
		if (empty($num)){
		    json_msg(-1, '平台订单号错误');
		}
		if (empty($syorder)){ 
		     json_msg(-1, '上游订单号错误');
		}
		
		$order_where['num'] = $num;
		$order_where['syorder'] = $syorder;
		$order = Db::name('orders')->where($order_where)->find();
		$land_id = $order['land_id'];
		$land = Db::name('land')->where('id',$land_id)->find();
		$game_data = Db::name('game_list')->where('id','in',config('game_id'))->where('id',$land['typec'])->find();
		
		//结果为未支付才进行支付检查处理
		if($game_data['game_dm']!='alipay_dmf'){
		if ($order['state'] == 1) {
			if($land['typec']!='') {
			    
			    $cls = model("\\app\common\\game\\".ucfirst($game_data['game_dm']));
		    	$syorder = $cls->status(json_decode($land['json'], true),$order['syorder'],intval($order['money']));
		    	
				//开始置订单
				if($syorder!='' && $syorder!=$num && $syorder!='-2') {
					//上游订单不可为空和上游订单不可和本平台订单相同，和本平台相同订单是支付宝当面付
					$paytime = time();
					$update = Db::name('orders')->where('id', $order['id'])->update(array('pay_time'=>$paytime,'state'=>2,'http'=>'还未请求'));
					$user = Db::name('user')->where('id',$land['userid'])->find();
				    api_request($order['id'],$user);
					json_msg(200, '支付成功');
				}else if($syorder=='-2'){
				    Db::name('orders')->where('id', $order['id'])->update(array("state"=>3));
				    json_msg(1002, '订单已经超时');
				}
			}
		}
		}
		if (!is_array($order)){
		    json_msg(1001, '订单已被销毁');
		}
		if ($order['state'] == 3){
		    json_msg(1002, '订单已经超时');
		}
		if ($order['state'] == 2){
		    json_msg(200, '支付成功');
	    }
		if ($order['state'] == 1){
		    json_msg(1003, '订单未支付');
		}
		
	}
	//取账号模式
	private function land_1($userid, $money ,$mid = '') {
		$land_where['ban'] = 1;
		$land_where['userid'] = $userid;
		$land_where['land_lx'] = 1;
		$land_where['ds_status'] = 0;
		if($mid!= ''){
		$land_where['mid'] = $mid;
	    }
		$land = Db::name('land')->where($land_where)->select();
		$arr_id[] = '';
		foreach ($land as $value) {
			$order_where['userid'] = $userid;
			$order_where['land_id'] = $value['id'];
			$order_where['state'] = 2;
			$order_r = Db::name('orders')->where($order_where)->whereTime('pay_time', 'today')->sum('money');
			$order_z = Db::name('orders')->where($order_where)->sum('money');
			//先计算总限额是否已限额
			if ($value['z_money'] != 0) {
				if ($order_z >= $value['z_money']) {
					$up['land_lx'] = 0;
					$up_where['id'] = $value['id'];
					$up_where['userid'] = $userid;
					Db::name('land')->where($up_where)->update($up);
				}
			}
			if ($value['r_money'] != 0) {
				if ($order_r >= $value['r_money']) {
					$arr_id[] = $value['id'];
				}
			}
			
			
			if($value['ds_time']!=0 || $value['ds_num']!=0 || $value['ds_status_time']!=0){
		    	//判断是否在限定时间达到限量
		       if($value['ds_type'] == '0'){
		       $order_ds_where['pay_time'] = ['lt',$value['ds_status_time']+($value['ds_time']*60)];//小于
		       $order_ds_where['pay_time'] = ['gt',$value['ds_status_time']];//大于
		       $order_ds_where['state'] = 2;
		       }else if($value['ds_type'] == '1'){
		       $order_ds_where['order_time'] = ['lt',$value['ds_status_time']+($value['ds_time']*60)];//小于
		       $order_ds_where['order_time'] = ['gt',$value['ds_status_time']];//大于   
		       //$order_ds_where['state'] = 1;
		       }
		       
			   $order_ds_where['land_id'] = $value['id'];
			   
			   $order_ds = Db::name('orders')->where($order_ds_where)->count();
			   if($order_ds>=$value['ds_num']){
			       $arr_id[] = $value['id'];
			       //变更设定限量，写入限量参数和限量最新时间
			       Db::name('land')->where('id',$value['id'])->update(['ds_status'=>1,'ds_status_time'=>time()]);
			   }
			}
			
			//判断是否存在需要的金额参数,不存在过滤掉(支付宝等无需过滤)
	    	$game = Db::name('user')->where('id',$value['typec'])->find();
			if ($game['game_type']=='1') {
				$ckmoney = 'ck' . $money;
				$ck_json = json_decode($value['json'], true);
				if (!isset($ck_json[$ckmoney])) {
					$arr_id[] = $value['id'];
				}
			}
		}
		
		$land_where['id'] = ['not in', $arr_id];
		$land = Db::name('land')->where($land_where)->limit(1)->orderRaw('rand()')->select();
		if ($land) {
			return $land[0];
		} else {
			return -1;
		}
	}
	
	private function bug_set($user_id,$land_id){
	    $user = Db::name('user')->where('id',$user_id)->find();
	    $land = Db::name('land')->where('id',$land_id)->find();
	    if($user['bug_set']!='0'){
			   if($land['bug'] + 1 != $user['bug_set']){
			      $where['id'] = $land['id'];
			      $land_save = Db::name('land')->where($where)->setInc('bug');
			   }else{
			      $where['id'] = $land['id'];
			      if($user['bug_type']=='1'){
			          $land_save = Db::name('land')->where($where)->update(['land_lx' => '0']);
			          $add_data['user_id'] = $user_id;
			          $add_data['land_id'] = $land_id;
			          $add_data['land_type'] = $land['typec'];
			          $add_data['bug_num'] = $land['bug'];
			          $add_data['bug_type'] = 1;
			          $add_data['time'] = time();
			          Db::name('bug_log')->insert($add_data);
			      }else if($user['bug_type']=='2'){
			    
			           $update['land_name'] = $land['username'];
			           $where_orders['land_id'] = $land['id'];
                       $where_orders['userid'] = $user['id'];
                       $where_log['land'] = $land['id'];
                       $where_log['userid'] = $user['id'];
			           Db::name("land")->where($where)->delete();
                       DB::name("orders")->where($where_orders)->update($update);
                       DB::name("log")->where($where_log)->update($update);

			      }
			}
		}
	}
}