<?php
/* +----------------------------------------------------------------------+
   | Copyright (c) 2018-2019 YmPay                                        |
   |              <530759076@qq.com>                                      |
   +----------------------------------------------------------------------+*/
namespace App\Http\Controllers\Api;
use Illuminate\Support\Facades\Redis;
use App\Http\Models\PaymentModel;
use App\Http\Models\OrderModel;
use App\Http\Models\DiepollingpaymentModel;
use App\Http\Models\LivepollingpaymentModel;
use Vinkla\Hashids\Facades\Hashids;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Common\Order_Redis;
use GatewayClient\Gateway;
use QrCode;

class ApiController extends Controller {
    public function __construct(){
    	 
    }
    /****添加支付订单****/
    public function pay(Request $arr) {
        if ($arr->filled('user_id')) {
            if ($arr->filled('order_id')) {
                if ($arr->filled('return_url') && preg_match("@[a-zA-z]+://[^\s]*@", $arr['return_url'])) {
                    if ($arr->filled('notice_url') && preg_match("@[a-zA-z]+://[^\s]*@", $arr['notice_url'])) {
                        if ($arr->filled('amount')) {
                            $adminsite = DB::table('admin_site')->first();

                            if ($arr->input('amount') >= $adminsite->order_min && $arr->input('amount') <= $adminsite->order_max) {
                                if ($arr->filled('paytype')) {
                                    if ($arr->input('paytype') == 'alipay' || $arr->input('paytype') == 'unionpay' || $arr->input('paytype') == 'aliwap' || $arr->input('paytype') == 'wechat') {
                                      $userinfo = DB::table('user')->where('Id', $arr->input('user_id'))->first();
                                      //print_r($arr->filled('sign'));
                                      //print_r($arr->all());
                                      //echo getsign($arr->all(), $userinfo->token);exit;
                                        if ($arr->filled('sign')) {
                                            //获取当前用户信息

                                            //获取当前所有提交信息
                                            $paydata = $arr->all();
                                            //获取码商最低接订单金额
                                            $merchant_site['merchant_amount_mini'] = (float)$paydata['amount'];
                                            if ($userinfo) {
                                                if ($userinfo->status == 1) {
                                                    //判断用户token判断签名是否一致
                                                    if ($arr->input('sign') == getsign($paydata, $userinfo->token)) {
                                                        /****获取当前商户等级判断今日是否限额****/
                                                        if($userinfo->type  == 1){
                                                            $order_everyday_money = DB::table('admin_user_site')->first()->order_everyday_money;
                                                        }else if($userinfo->type == 2){
                                                            $order_everyday_money = DB::table('admin_user_senior_site')->first()->order_everyday_money;
                                                        }else{
                                                            $order_everyday_money = DB::table('admin_user_senior_site')->first()->order_everyday_money;
                                                        }
                                                        //获取当前商户当日订单额
                                                        $user_map['user_id'] = $userinfo->Id;
                                                        $user_map['status'] = 2;
                                                        $user_map[]=['sub_time','<',strtotime(date('Y-m-d 00:00:00'))+86400];
                                                        $user_map[]=['sub_time','>=',strtotime(date('Y-m-d 00:00:00'))];
                                                        $user_order_total_money = DB::table('order')->where($user_map)->sum('order_money');
                                                        if($order_everyday_money == 0 || $user_order_total_money < $order_everyday_money){
                                                            //判断用户提交订单号是否唯一
                                                            $map['user_id'] = $arr->input('user_id');
                                                            $map['order_id'] = $arr->input('order_id');
                                                            $orid = DB::table('order')->where($map)->first();
                                                            if (!$orid) {
                                                                //判断是否提交码商key
                                                                if ($arr->filled('merchant_key') && preg_match("@[a-zA-Z0-9]{32}@", $arr->input('merchant_key'))) {
                                                                    //查询码商状态
                                                                    $merchantinfo = DB::table('member')->where('apikey', $arr->input('merchant_key'))->first();
                                                                    if ($merchantinfo) {
                                                                        if ($merchantinfo->status == 1) {
                                                                            //判断当前码商余额是否充足
                                                                            if ($merchantinfo->price >= $merchant_site['merchant_amount_mini']) {
                                                                                $orders['member_id'] = $merchantinfo->Id;
                                                                                //是否指定了固码或活码
                                                                                if ($arr->filled('code_type')) {
                                                                                    //判断是否提交正确值
                                                                                    $code_type = $arr->input('code_type');
                                                                                    if ($code_type == 1) {
                                                                                        $plpayment = new DiepollingpaymentModel;
                                                                                        //判断用户是否支持固码通道
                                                                                        $mapuserpay['user_id'] = $userinfo->Id;
                                                                                        $mapuserpay['passageway_type'] = 1;
                                                                                        $mapuserpay['status'] = 1;
                                                                                        $dielist = PaymentModel::where($mapuserpay)->whereHas('diepay', function ($query) use ($paydata) {
                                                                                            $query->where('paytype', 'like', '%'.$paydata['paytype'].'%');
                                                                                        })->with('diepay')->get();
                                                                                        if(!$dielist->isEmpty()){
                                                                                            $paylist = $dielist;
                                                                                        }else{
                                                                                            $json['state'] = 0;
                                                                                            $json['msg'] = "当前商户不支持该通道,请联系客服";
                                                                                        }
                                                                                    } else if ($code_type == 2) {
                                                                                        //判断用户是否支持活码通道
                                                                                        $mapuserpay['user_id'] = $userinfo->Id;
                                                                                        $mapuserpay['passageway_type'] = 2;
                                                                                        $mapuserpay['status'] = 1;
                                                                                        $livelist = PaymentModel::where($mapuserpay)->whereHas('livepay', function ($query) use ($paydata) {
                                                                                            $query->where('paytype', 'like', '%'.$paydata['paytype'].'%');
                                                                                        })->with('livepay')->get();
                                                                                        $plpayment = new LivepollingpaymentModel;
                                                                                        //判断用户是否支持活码通道
                                                                                        if(!$livelist->isEmpty()){
                                                                                            $paylist = $livelist;
                                                                                        }else{
                                                                                            $json['state'] = 0;
                                                                                            $json['msg'] = "当前商户不支持该通道,请联系客服";
                                                                                        }
                                                                                    } else {
                                                                                        $json['state'] = 0;
                                                                                        $json['msg'] = "请提交正确的收款通道类型";
                                                                                    }
                                                                                    if (!isset($json)) {
                                                                                        //判断是否提交了收款账号
                                                                                        if ($arr->filled('merchant_uid')) {
                                                                                            //查询收款账号是否存在
                                                                                            $merchant_polling = DB::table('member_polling')->where(array('username' => $arr->input('merchant_uid'),'type'=>$code_type))->first();
                                                                                            if ($merchant_polling) {
                                                                                                if ($merchant_polling->status == 1 && !empty($merchant_polling->token)) {
                                                                                                    if ($merchant_polling->loop == 1) {
                                                                                                        $orders['polling_id'] = $merchant_polling->Id;
                                                                                                    } else {
                                                                                                        $json['state'] = 0;
                                                                                                        $json['msg'] = "当前收款账号已禁止参与轮循";
                                                                                                    }
                                                                                                } else {
                                                                                                    $json['state'] = 0;
                                                                                                    $json['msg'] = "当前收款账号不在线";
                                                                                                }
                                                                                            } else {
                                                                                                $json['state'] = 0;
                                                                                                $json['msg'] = "当前不存在此收款账号";
                                                                                            }
                                                                                        }
                                                                                        //查询是否提交指定通道
                                                                                        if ($arr->filled('channel_id')) {
                                                                                            //查询通道ID码商是否存在
                                                                                            $map2['member_id'] = $merchantinfo->Id;
                                                                                            if(isset($merchant_polling)){
                                                                                                $map2['polling_id'] = $merchant_polling->Id;
                                                                                            }
                                                                                            $map2['passageway_id'] = $arr->input('channel_id');
                                                                                            $payment = $plpayment->where($map2)->with('payment')->first();
                                                                                            if ($payment) {
                                                                                                if(!isset($json)){
                                                                                                    //判断当前通道是否支持该支付方式
                                                                                                    if (stristr($payment->payment->paytype, $arr->input('paytype')) !== false) {
                                                                                                        //判断当前用户是否支持该通道
                                                                                                        $paylist = PaymentModel::where(array('user_id'=>$userinfo->Id,'passageway_id'=>$arr->input('channel_id'),'status'=>1))->get();
                                                                                                        if($paylist->isEmpty()){
                                                                                                            $json['state'] = 0;
                                                                                                            $json['msg'] = "当前商户不支持该通道,请联系客服";
                                                                                                        }
                                                                                                    } else {
                                                                                                        $json['state'] = 0;
                                                                                                        $json['msg'] = "当前收款通道不支持该支付方式";
                                                                                                    }
                                                                                                }
                                                                                            } else {
                                                                                                $json['state'] = 0;
                                                                                                $json['msg'] = "当前码商不存在此收款通道";
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                } else {
                                                                                    //查询当前码商目前支持哪些码
                                                                                    $diepayment = DiepollingpaymentModel::where(array('member_id'=>$merchantinfo->Id,'status'=>1))->first();
                                                                                    $livepayment = LivepollingpaymentModel::where(array('member_id'=>$merchantinfo->Id,'status'=>1))->first();
                                                                                    //查询当前用户支持哪些码
                                                                                    $mapuserpay['user_id'] = $userinfo->Id;
                                                                                    $mapuserpay['passageway_type'] = 1;
                                                                                    $mapuserpay['status'] = 1;
                                                                                    $dielist = PaymentModel::where($mapuserpay)->whereHas('diepay', function ($query) use ($paydata) {
                                                                                        $query->where('paytype', 'like', '%'.$paydata['paytype'].'%');
                                                                                    })->with('diepay')->get();
                                                                                    $mapuserpay['passageway_type'] = 2;
                                                                                    $livelist = PaymentModel::where($mapuserpay)->whereHas('livepay', function ($query) use ($paydata) {
                                                                                        $query->where('paytype', 'like', '%'.$paydata['paytype'].'%');
                                                                                    })->with('livepay')->get();
                                                                                    if($diepayment && $livepayment){
                                                                                        if(!$dielist->isEmpty() && !$livelist->isEmpty()){
                                                                                            $code_type = rand(1, 2);
                                                                                            if ($code_type == 1) {
                                                                                                $plpayment = new DiepollingpaymentModel;
                                                                                                $paylist = $dielist;
                                                                                            } else {
                                                                                                $plpayment = new LivepollingpaymentModel;
                                                                                                $paylist = $livelist;
                                                                                            }
                                                                                        }else if(!$dielist->isEmpty()){
                                                                                            $code_type =1;
                                                                                            $plpayment = new DiepollingpaymentModel;
                                                                                            $paylist = $dielist;
                                                                                        }else{
                                                                                            $code_type =2;
                                                                                            $plpayment = new LivepollingpaymentModel;
                                                                                            $paylist = $livelist;
                                                                                        }
                                                                                    }else if($diepayment){
                                                                                        //判断当前用户是否支持固码
                                                                                        if(!$dielist->isEmpty()){
                                                                                            $code_type = 1;
                                                                                            $plpayment = new DiepollingpaymentModel;
                                                                                            $paylist = $dielist;
                                                                                        }else{
                                                                                            $json['state'] = 0;
                                                                                            $json['msg'] = "当前商户不支持该通道,请联系客服";
                                                                                        }
                                                                                    }else{
                                                                                        //判断当前用户是否支持活码
                                                                                        if(!$livelist->isEmpty()){
                                                                                            $code_type = 2;
                                                                                            $plpayment = new LivepollingpaymentModel;
                                                                                            $paylist = $livelist;
                                                                                        }else{
                                                                                            $json['state'] = 0;
                                                                                            $json['msg'] = "当前商户不支持该通道,请联系客服";
                                                                                        }
                                                                                    }
                                                                                }
                                                                            } else {
                                                                                $json['state'] = 0;
                                                                                $json['msg'] = "当前码商预存款不足,请先充值";
                                                                            }
                                                                        } else {
                                                                            $json['state'] = 0;
                                                                            $json['msg'] = "当前码商已被冻结,如有疑问请咨询客服";
                                                                        }
                                                                    } else {
                                                                        $json['state'] = 0;
                                                                        $json['msg'] = "当前码商不存在,请查看是否提交正确key";
                                                                    }
                                                                }
                                                                //判断提交方式
                                                                if($arr->filled('format')  && $arr->input('format')== 'json'){
                                                                    //检测IP是否提交
                                                                    if($arr->filled('ip') && checkip($arr->input('ip'))){
                                                                        //查询当前IP地址省编号及市编号
                                                                        $ipData = loginip($arr->input('ip'));
                                                                        if($ipData){
                                                                            $orders['region_id'] = $ipData['proCode'];
                                                                            $orders['city_id'] = $ipData['cityCode'];
                                                                        }else{
                                                                            $orders['region_id'] = 999999;
                                                                            $orders['city_id'] = 0;
                                                                        }
                                                                    }else{
                                                                        $json['state'] = 0;
                                                                        $json['msg']  = "请填写正确的IP地址";
                                                                    }
                                                                }else{
                                                                    //查询当前IP地址省编号及市编号
                                                                    $ipData = loginip($arr->getClientIp());
                                                                    if($ipData){
                                                                        $orders['region_id'] = $ipData['proCode'];
                                                                        $orders['city_id'] = $ipData['cityCode'];
                                                                    }else{
                                                                        $orders['region_id'] = 999999;
                                                                        $orders['city_id'] = 0 ;
                                                                    }
                                                                }
                                                                if (!isset($json)) {
                                                                    if (!isset($merchantinfo)) {
                                                                        //查询当前用户支持此支付方式的哪些码
                                                                        $mapuserpay['user_id'] = $userinfo->Id;
                                                                        $mapuserpay['passageway_type'] = 1;
                                                                        $mapuserpay['status'] = 1;
                                                                        $dielist = PaymentModel::where($mapuserpay)->whereHas('diepay', function ($query) use ($paydata) {
                                                                            $query->where('paytype', 'like', '%'.$paydata['paytype'].'%');
                                                                        })->with('diepay')->get();
                                                                        $mapuserpay['passageway_type'] = 2;
                                                                        $livelist = PaymentModel::where($mapuserpay)->whereHas('livepay', function ($query) use ($paydata) {
                                                                            $query->where('paytype', 'like', '%'.$paydata['paytype'].'%');
                                                                        })->with('livepay')->get();
                                                                        if(!$dielist->isEmpty() && !$livelist->isEmpty()){
                                                                            $code_type = rand(1, 2);
                                                                            if ($code_type == 1) {
                                                                                $plpayment = new DiepollingpaymentModel;
                                                                                $paylist = $dielist;
                                                                            } else {
                                                                                $plpayment = new LivepollingpaymentModel;
                                                                                $paylist = $livelist;
                                                                            }
                                                                        }else if(!$dielist->isEmpty()){
                                                                            $code_type =1;
                                                                            $plpayment = new DiepollingpaymentModel;
                                                                            $paylist = $dielist;
                                                                        }else{
                                                                            $code_type =2;
                                                                            $plpayment = new LivepollingpaymentModel;
                                                                            $paylist = $livelist;
                                                                        }
                                                                        if(!empty($userinfo->member_arr)){
                                                                        	$orders['member_id'] = explode(",",$userinfo->member_arr);
                                                                        }
                                                                    }
                                                                    if (isset($paylist)) {
                                                                        $orders['amount'] = number_format($arr->input('amount') , 2, ".", "");
                                                                        //开始取商户以及二维码数据
                                                                        /****平台出码方式****/
                                                                        $order_qrcode_type = $adminsite->payment_type;
                                                                        $Order_Redis = new Order_Redis;
                                                                        foreach ($paylist as $k => $v) {
                                                                            $orders['passageway_id'][] = $v->passageway_id;
                                                                        }
                                                                        //dd($orders);
                                                                        /***首先判断此地区是否有码****/

                                                                        $pinfo_a = $Order_Redis->dom($order_qrcode_type,$paydata['paytype'],$code_type,$orders);
                                                                        if($pinfo_a){
                                                                            $pinfo = $pinfo_a;
                                                                        }else{
                                                                            /***判断此地区省份是否有码****/
                                                                            $orders['city_id'] = 0;
                                                                            $pinfo_b = $Order_Redis->dom($order_qrcode_type,$paydata['paytype'],$code_type,$orders);
                                                                            if($pinfo_b){
                                                                                $pinfo = $pinfo_b;
                                                                            }else{
                                                                                /***判断全国是否有码****/
                                                                                $orders['region_id'] = 999999;
                                                                                $orders['city_id'] = 0;
                                                                                $pinfo_c = $Order_Redis->dom($order_qrcode_type,$paydata['paytype'],$code_type,$orders);
                                                                                $pinfo = $pinfo_c;
                                                                            }
                                                                        }
                                                                        if ($pinfo) {
                                                                            //取出所有正在交易订单
                                                                            $orderredis = Redis::lrange("amountpool", 0, -1);
                                                                            if (!empty($orderredis)) {
                                                                                $orderlist = array();
                                                                                $amountarr = array();
                                                                                foreach ($orderredis as $v) {
                                                                                    $orderlist[] = json_decode($v, true);
                                                                                }
                                                                                //取出该账户该通道所有正在交易订单的金额
                                                                                foreach ($orderlist as $v) {
                                                                                    if ($v['polling_user'] == $pinfo['user']['username'] && $v['passageway_id'] == $pinfo['passageway_id']) {
                                                                                        $amountarr[] = $v['order_price'];
                                                                                    }
                                                                                }
                                                                                if (!empty($amountarr)) {
                                                                                    $addorder['order_price'] = orderamount(number_format($arr->input('amount') , 2, ".", "") , $amountarr, array() , $adminsite->order_amount_float);
                                                                                } else {
                                                                                    $addorder['order_price'] = number_format($arr->input('amount') , 2, ".", "");
                                                                                }
                                                                            } else {
                                                                                $addorder['order_price'] = number_format($arr->input('amount') , 2, ".", "");
                                                                            }
                                                                            if($addorder['order_price']){
	                                                                            //设置订单信息
	                                                                            $addorder['apiorder_id'] = date('dhis',time()) . Hashids::encode(time().rand(1000000, 9999999));
	                                                                            $addorder['order_id'] = $paydata['order_id'];
	                                                                            $addorder['passageway_id'] = $pinfo['passageway_id'];
	                                                                            $addorder['order_money'] = number_format($arr->input('amount') , 2, ".", "");
	                                                                            $addorder['order_service'] = number_format($addorder['order_price'] * $userinfo->order_service, 3, ".", "");
	                                                                            $addorder['software_service'] = number_format($addorder['order_price'] * $userinfo->safety_service, 3, ".", "");
	                                                                            $addorder['passageway_service'] = number_format($addorder['order_price'] * $pinfo['merchant']['service'], 3, ".", "");
	                                                                            $addorder['type'] = $paydata['paytype'];
	                                                                            if (isset($paydata['remarks'])) {
	                                                                                $addorder['remarks'] = $paydata['remarks'];
	                                                                            }
	                                                                            $addorder['user_id'] = $userinfo->Id;
	                                                                            $addorder['member_id'] = $pinfo['member_id'];
	                                                                            $addorder['polling_user'] = $pinfo['user']['username'];
	                                                                            $addorder['polling_passageway_key'] = $pinfo['key'];
	                                                                            $addorder['notify_url'] = $paydata['notice_url'];
	                                                                            $addorder['return_url'] = $paydata['return_url'];
	                                                                            $addorder['sub_time'] = time();
	                                                                            $addorder['com_time'] = time() + $pinfo['payment']['order_exptime'];
	                                                                            $addorder['code_type'] = $code_type;
	                                                                            if ($code_type == 1) {
	                                                                                if($addorder['passageway_id'] == 804){
	                                                                                    $addorder['qrcode_url'] = str_replace("(order_price)",$addorder['order_price'],$pinfo['qrcode']);
	                                                                                    $bankcard = cut('cardNo=','&bank',$pinfo['qrcode']);
	                                                                                    $addorder['qrcode_url'] = str_replace($bankcard,substr($bankcard,0,6).'***'.substr($bankcard,-4),$addorder['qrcode_url']);
	                                                                                }else{
	                                                                                    $addorder['qrcode_url'] = $pinfo['qrcode'];
	                                                                                }
	                                                                                $redis_order_table = md5(json_encode(array(
	                                                                                    'passageway_id' => $addorder['passageway_id'],
	                                                                                    'order_price' => $addorder['order_price'],
	                                                                                    'polling_id' => $pinfo['polling_id']
	                                                                                )));
	                                                                            } else {
	                                                                                $redis_order_table = md5($addorder['apiorder_id']);
	                                                                            }
	                                                                            //先添加到数据库
	                                                                            $status = OrderModel::insert($addorder);
	                                                                            if ($status) {
	                                                                                $amountpool['passageway_id'] = $pinfo['passageway_id'];
	                                                                                $amountpool['polling_user'] = $pinfo['user']['username'];
	                                                                                $amountpool['order_price'] = $addorder['order_price'];
	                                                                                $amountpool['exptime'] = $addorder['com_time'];
	                                                                                //添加到金额池
	                                                                                Redis::rpush('amountpool', json_encode($amountpool));
	                                                                                //添加数据库后再添加redis新订单
	                                                                                $addorder['user_token'] = $userinfo->token;
	                                                                                $addorder['notice'] = 1;
	                                                                                $addorder['status'] = 1;
	                                                                                //添加新订单
	                                                                                Redis::setex($redis_order_table,$pinfo['payment']['order_exptime'], json_encode($addorder));
	                                                                                if ($code_type == 2) {
	                                                                                    //添加到socket回调
	                                                                                    $redis_socketarr['apiorder_id'] = $addorder['apiorder_id'];
	                                                                                    $redis_socketarr['channel_code'] = $addorder['passageway_id'];
	                                                                                    $redis_socketarr['money'] = intval($addorder['order_price'] * 100);
	                                                                                    $redis_socketarr['type'] = $addorder['type'] == 'aliwap' ? 'alipay' : $addorder['type'];
	                                                                                    $redis_socket['token'] = $pinfo['user']['token'];
	                                                                                    $redis_socket['content']['type'] = "order";
	                                                                                    $redis_socket['content']['data'] = apiencode($redis_socketarr);
	                                                                                    Redis::rpush('socket', json_encode($redis_socket));
	                                                                                }
	                                                                                //判断format是否为json
	                                                                                if ($arr->filled('format') && $arr->input('format') == 'json') {
	                                                                                    //同步返回
	                                                                                    if ($code_type == 2) {
	                                                                                        sleep(intval($pinfo['payment']['return_time']));
	                                                                                        //暂停时间后查询redis
	                                                                                        $return_arr = json_decode(Redis::get($redis_order_table) , true);
	                                                                                    } else {
	                                                                                        $return_arr = $addorder;
	                                                                                    }
	                                                                                    if (isset($return_arr['qrcode_url'])) {
	                                                                                        $json['state'] = 1;
	                                                                                        $json['paytype'] = $return_arr['type'];
	                                                                                        $json['order_id'] = $return_arr['order_id'];
	                                                                                        $json['apiorder_id'] = $return_arr['apiorder_id'];
	                                                                                        $json['amount'] = $return_arr['order_money'];
	                                                                                        $json['amount_actual'] = $return_arr['order_price'];
	                                                                                        $json['qrcode_url'] = $return_arr['type'] != 'alipay' ? $return_arr['qrcode_url'] : "http://".config('route.domain.api').'/do?key='.encrypt($redis_order_table);
	                                                                                        $json['endtime'] = $return_arr['com_time'];
	                                                                                        $json['msg'] = "获取成功";
	                                                                                    } else {
	                                                                                        $json['state'] = 0;
	                                                                                        $json['msg'] = "获取二维码失败";
	                                                                                    }
	                                                                                } else {
	                                                                                    //跳转地址
	                                                                                    return redirect('/do?key='.encrypt($redis_order_table));
	                                                                                }
	                                                                            } else {
	                                                                                $json['state'] = 0;
	                                                                                $json['msg'] = "平台繁忙,请重新提交";
	                                                                            }
                                                                            }else{
                                                                            	$json['state'] = 0;
                                                                            	$json['msg'] = "当前金额已满,请重新输入金额提交";
                                                                            }
                                                                        } else {
                                                                            $json['state'] = 0;
                                                                            $json['msg'] = "平台繁忙,请重新提交";
                                                                        }
                                                                    } else {
                                                                        $json['state'] = 0;
                                                                        $json['msg'] = "当前商户不支持该通道,请联系客服";
                                                                    }
                                                                }
                                                            } else {
                                                                $json['state'] = 0;
                                                                $json['msg'] = "当前商户已存在此订单号";
                                                            }
                                                        }else{
                                                            $json['state'] = 0;
                                                            $json['msg'] = "当前商户类型当天已限额,请联系客服调整或升级商户";
                                                        }
                                                    } else {
                                                        $json['state'] = 0;
                                                        $json['msg'] = "支付签名错误";
                                                    }
                                                } else {
                                                    $json['state'] = 0;
                                                    $json['msg'] = "当前商户已被冻结,如有疑问请咨询客服";
                                                }
                                            } else {
                                                $json['state'] = 0;
                                                $json['msg'] = "当前不存在此商户";
                                            }
                                        } else {
                                            $json['state'] = 0;
                                            $json['msg'] = "请提交支付签名";
                                        }
                                    } else {
                                        $json['state'] = 0;
                                        $json['msg'] = "当前不支持此支付方式";
                                    }
                                } else {
                                    $json['state'] = 0;
                                    $json['msg'] = "请提交支付方式";
                                }
                            } else {
                                $json['state'] = 0;
                                $json['msg'] = "订单最小提交金额为" . $adminsite->order_min . "最大提交金额为" . $adminsite->order_max;
                            }
                        } else {
                            $json['state'] = 0;
                            $json['msg'] = "请提交订单金额";
                        }
                    } else {
                        $json['state'] = 0;
                        $json['msg'] = "请提交正确的异步跳转地址";
                    }
                } else {
                    $json['state'] = 0;
                    $json['msg'] = "请提交正确的同步跳转地址";
                }
            } else {
                $json['state'] = 0;
                $json['msg'] = "请提交唯一订单号";
            }
        } else {
            $json['state'] = 0;
            $json['msg'] = "请提交商户编号";
        }
        return response()->json($json);
    }
    /****API查询订单****/
    public function query(Request $arr) {
      if ($arr->filled('user_id')) {
            if ($arr->filled('order_id')) {
                if ($arr->filled('sign')) {
                     //获取当前用户信息
                     $userinfo = DB::table('user')->where('Id',$arr->input('user_id'))->first();
                    if($userinfo){
                        //获取当前所有提交信息
                        $postdata = $arr->all();
                        //判断用户token判断签名是否一致
                        if ($arr->input('sign') == getsign($postdata,$userinfo->token)) {
                            $orderinfo = DB::table('order')->where(array('user_id'=>$userinfo->Id,'order_id'=>$arr->input('order_id')))->first();
                            if($orderinfo){
                                $json['user_id'] = $userinfo->Id;
                                $json['order_id'] = $orderinfo->order_id;
                                $json['apiorder_id'] = $orderinfo->apiorder_id;
                                $json['amount'] = $orderinfo->order_money;
                                $json['amount_actual'] = $orderinfo->order_price;
                                $json['success_time'] = $orderinfo->status == 2 ? $orderinfo->com_time : $orderinfo->sub_time;
                                $json['state'] = 1;
                                $json['order_state'] = $orderinfo->status == 2 ? 'success' : 'error';
                                $json['sign'] = getsign($json,$userinfo->token);
                            }else{
                                $json['state'] = 0;
                                $json['msg'] = "当前商户不存在该订单";
                            }
                        }else{
                            $json['state'] = 0;
                            $json['msg'] = "支付签名错误";
                        }
                    }else{
                        $json['state'] = 0;
                        $json['msg'] = "不存在当前商户";
                    }
                }else{
                    $json['state'] = 0;
                    $json['msg'] = "请提交签名";
                }
            }else{
                $json['state'] = 0;
                $json['msg'] = "请提交商户上送唯一订单号";
            }
      }else{
            $json['state'] = 0;
            $json['msg'] = "请提交商户编号";
      }
      return $json;
    }
    /****商户接收升级****/
    public function member_notice(Request $arr){
    	
    	file_put_contents("success4.txt", "----------------------------\n".date('y-m-d H:i:s', time()).json_encode($arr)."\n", FILE_APPEND);
	        //$user_info = DB::table('user')->where('Id', $v['form']['user_id'])->first();
	
	      //file_put_contents("success3.txt", "----------------------------\n".date('y-m-d H:i:s', time()).json_encode($v).json_encode($user_info)."\n", FILE_APPEND);
	
	      /*
	      if ($user_info->daili_id) {
	        $change_data['type'] = 1; //
	        $daili_info = DB::table('daili')->where('Id', $user_info->daili_id)->first();
	        $change_data['user_id'] = $daili_info->Id; //代理id
	        $change_data['amount'] = $v['form']['amount'] * ($user_info->order_service - $daili_info->service);
	        $change_data['time'] = time();
	        $change_data['user_price'] = $daili_info->price + $change_data['amount'];
	        //再给商户加余额
	        $status = DB::table('daili')->where('Id', $daili_id)->update(array(
	            'price' => $change_data['user_price']
	        ));
	
	        //添加商户余额明细
	        $addstatus = DB::table('daili_amount_change')->insert($change_data);
	        $change_data['user_order_service'] = $user_info->order_service;
	        $change_data['daili_order_service'] = $daili_info->service;
	        file_put_contents("success2.txt", "----------------------------\n".date('y-m-d H:i:s', time()).json_encode($change_data)."\n", FILE_APPEND);
	      }
	      */
        if($arr->filled('sign')){
            $data = $arr->all();
            //查询用户
            $userinfo = DB::table('user')->where('Id',$data['user_id'])->first();
            if(getsign($data,$userinfo->token) == $arr->input('sign')){
                //查询充值单号
                $pay = DB::table('user_upgradepay')->where(array('user_id'=>$data['user_id'],'order_id'=>$data['order_id']))->first();
                if($pay->status != 2){
                    //修改状态为成功
                    $pay_updata['com_time'] = time();
                    $pay_updata['status'] = 2;

                    //修改用户等级
                    if($pay->up_type == 2){
                        $site = DB::table('admin_user_senior_site')->first();
                    }else{
                        $site = DB::table('admin_user_vip_site')->first();
                    }
                    $user_updata['order_service'] = $site->order_service;
                    $user_updata['safety_service'] =  $site->safety_service;
                    $status = DB::table('user')->where('Id',$pay->user_id)->update($user_updata);
                    if($status){
                        $pay_updata['result'] = 2;
                    }else{
                        $pay_updata['result'] = 3;
                    }
                    $pay_status = DB::table('user_upgradepay')->where('Id',$pay->Id)->update($pay_updata);
                    if($pay_status){
                        return 'success';
                    }else{
                        return 'error';
                    }
                }else{
                    return 'error';
                }
            }else{
                return 'error';
            }
        }else{
            return 'error';
        }
    }
    /****码商接收充值****/
    public function merchant_notice(Request $arr){
        if($arr->filled('sign')){
            $data = $arr->all();
            //查询用户
            $userinfo = DB::table('user')->where('Id',$data['user_id'])->first();
            if(getsign($data,$userinfo->token) == $arr->input('sign')){
                //查询充值单号
                $pay = DB::table('member_pay')->where(array('order_id'=>$data['order_id']))->first();
                if($pay->status != 2){
                    //修改状态为成功
                    $pay_updata['com_time'] = time();
                    $pay_updata['status'] = 2;

                    //修改码商余额
                    $merchant = DB::table('member')->where('Id',$pay->member_id)->first();

                    $updata['price'] = $merchant->price + $pay->amount_actual;
                    $status = DB::table('member')->where('Id',$merchant->Id)->update(updata);
                    if($status){
                        $pay_updata['result'] = 2;
                    }else{
                        $pay_updata['result'] = 3;
                    }
                    $pay_status = DB::table('member_pay')->where('Id',$pay->Id)->update($pay_updata);
                    if($pay_status){
                        return 'success';
                    }else{
                        return 'error';
                    }
                }else{
                    return 'error';
                }
            }else{
                return 'error';
            }
        }else{
            return 'error';
        }
    }
    /****测试接收通知****/
    public function demo_notice(Request $arr){
    	file_put_contents("success5.txt", "----------------------------\n".date('y-m-d H:i:s', time()).json_encode($arr)."\n", FILE_APPEND);
        if ($arr->isMethod('get')) {
        	
            return "支付成功";
        }

        if($arr->isMethod('post')){
            return "success";
        }
    }
    public function ceshi(Request $arr){
    	$list = Redis::lrange('sort_alipay_die',0,-1);
	        dd($list);
    }
}
