<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class PayController extends Controller
{
    //支付
    public function pay(Request $req)
    {   
        //首先处理数据，生成订单
        $order = [];
        $user = DB::table('user') -> where('token',$req -> token) -> first();
        $order['user_id'] = $user -> id;
        if(!$order['user_id']) {
            return ['code' => '1009','msg' => 'err','result' => '订单生成失败'];
        }
        $order['order_id'] = '1'.rand(1000000,9999999);
//        $order['md_id'] = $req -> md['id'];
        $order['md_id'] = $req -> md;
        $order['is_yh'] = $req -> yh_id;
        $order['is_jifen'] = 0;
        $order['price'] = $req -> price;
        $order['order_time'] = time();
        $order['goods_date'] = $req -> goods_date;   //自取或者配送时间
        $order['pay_type'] = $req -> pay_type;
        $order['order_type'] = $req -> peisong;   //ziqu_active  为自取  否则为配送
        $order['phone'] = (int)$user -> phone;   
        $order['peisong_price'] = 0;   //配送费
        if($req -> peisong == 'peisong-active') {
            $order['name'] = $user -> name;   //配送才有姓名
            $order['address'] = $user -> address.$user -> menpai;   //配送才有地址
            $order['peisong_price'] = $req -> md['peisong_price'] * 100;   //配送费
            $order['price'] = $order['price'] + $order['peisong_price'];   //加上配送费
        }
        $order['notes'] = $req -> notes;   //订单备注
        $order['status'] = 0;   //0为待付款状态
//        return [
//            'code' => $order,
//            ];
//        exit();
        DB::beginTransaction();
        $orderId = DB::table('order') -> insertGetId($order);   //订单的id
        if($orderId) {
            $goods = [];
            $goods_num = 0;
            foreach($req -> goods as $key => $val) {
                $goods['order_id'] = $order['order_id'];
                $goods['goods_id'] = DB::table('goods') -> where('goods_name',$val['name']) -> value('id');
                $goods['goods_num'] = $val['num'];
                $goods['price'] = $val['price'];
                $goods['guige_id'] = (int)$val['guige_id'];
                $goods_num += DB::table('order_goods') -> insert($goods);
                
            }
            if($goods_num == count($req -> goods)) {
                DB::commit();
                return [
                    'code' => '1000',
                    'msg' => 'OK',
                    'order_id' => $order['order_id'],   //订单id
                    'price' => $order['price'],    //价格
                    'peisong_price'=>$order['peisong_price'],   //配送费
                    'pay_type' => $order['pay_type'],   //支付标识 ,微信wechat还是账户access  
                    'appid' => $req -> appid,  //小程序appid
                ];
            }else{
                DB::rollBack();
                return ['code' => '1008','msg' => 'err','result' => '订单生成失败'];
            }
        }else{
            DB::rollBack();
            return ['code' => '1007','msg' => 'err','result' => '订单生成失败'];
        }
        
    }
    //janPay  验证密码后扣款
    public function janPay(Request $req)
    {
          //验证token  order_id  支付密码
          if($user = DB::table('user') -> where('token',$req -> token) -> first()) {
              if($req -> password == $user -> pay_password) {
                $price = $req -> price / 100;
                $access_price = DB::table('access') -> where('user_id',$user->id) -> value('price');
                if($price < $access_price) {
                    //完成扣款
                    //查询订单
                    $order = DB::table('order') -> where('order_id',$req -> order_id) -> first();
                    //是否有优惠券
                    DB::beginTransaction();
                    if($order -> is_yh) {
                        $yh = DB::table('user_you') -> where('id',$order -> is_yh) -> update(['status' => 1]);
                    }
                    $ok = [];
                    $ok['status'] = 1;   //已付款
                    $ok['pay_time'] = time();
                    if(DB::table('order') -> where('order_id',$req -> order_id) -> update($ok)) {
                        //减去金额
                        $now_price = $access_price - $price;
                        //写回去   价格
                        if(DB::table('access') -> where('user_id',$user -> id) -> update(['price' =>$now_price])) {
                            //增加购买记录   增加积分
                            $goods = DB::table('order_goods') -> where('order_id',$req -> order_id) -> get();
                            $goods_name = [];
                            foreach($goods as $key => $val) {
                                $goods_name[$key] = DB::table('goods') -> where('id',$val -> goods_id) -> value('goods_name');
                            }
                            $record = [];
                            $record['user_id'] = $user -> id;
                            $record['order_id'] = $req -> order_id;
                            $record['goods'] = implode(',',$goods_name);
                            $record['time'] = time();
                            $record['price'] = $order -> price / 100;
                            $record['tag'] = '-';
                            if(DB::table('record') -> insert($record)) {
                                //积分
                                if($user -> level) {
                                    $jifen_rule = DB::table('jifen_rule') -> first();
                                    $jifen = floor($price) * $jifen_rule -> jifen;   //积分
                                }else{
                                    $jifen = floor($price);   //积分
                                }
                                $all_jifen = (int)$jifen + (int)$user -> jifen;
                                $jifen_ok = DB::table('user') -> where('id',$user -> id) -> update(['jifen' => $all_jifen]);
                                if($jifen_ok) {
                                    //增加积分记录
                                    $jifen_record = [];
                                    $jifen_record['user_id'] = $user -> id;
                                    $jifen_record['goods'] = $record['goods'];
                                    $jifen_record['time'] = time();
                                    $jifen_record['jifen'] = $jifen;
                                    $jifen_record['tag'] = '+';
                                    if(DB::table('jifen_record') -> insert($jifen_record)) {
                                        DB::commit();
                                        return ['code' => '1000','msg' => 'OK','result' => '支付成功!'];
                                    } 
                                }
                            }else{
                                DB::rollBack();
                                return ['code' => '1001','msg' => 'err','result' => '支付失败!'];
                            }
                        }
                    }else{
                        DB::rollBack();
                        return ['code' => '1002','msg' => 'err','result' => '支付失败!'];
                    }
                }else{
                    return ['code' => '1003','msg' => 'err','result' => '余额不足'];
                }
              }else{
                return ['code' => '1004','msg' => 'err','result' => '密码错误'];
              }
            
          }
    }
    //微信支付  换区key
    public function wechat(Request $request)
    {
        if($user = DB::table('user') -> where('token',$request -> token) -> first()) {
            $openid = $user -> openid;
            $appid = env('WECHAT_APPID');    //小程序appid
            $mch_id = env('WECHAT_SHID');   //商户号
            $key = env('WECHAT_SHKEY');    //商户key
            $out_trade_no = $request -> order_id;  //订单id
            $total_fee = $request -> price;  //金额
            // $total_fee = 1;  //金额
            $goods = DB::table('order_goods') -> where('order_id',$request -> order_id) -> pluck('goods_id');
            if($goods) {
                $goods_info = DB::table('goods') -> whereIn('id',$goods) -> get();  //商品
            }
            $goods_name = [];
            foreach($goods_info as $k => $val) {
                $goods_name[$k] = $val -> goods_name;
            }
            $body = implode(',',$goods_name);

            $weixinpay = new \WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee);

            $return = $weixinpay->pay();
//            return ['code'=>$appid.'+'.$openid.'+'.$mch_id.'+'.$key.'+'.$out_trade_no.'+'.$body.'+'.$total_fee,'result'=>$weixinpay];
//            return ['code'=>'1','pay_id_save' => 'OK','result' => $return];
            //把perpay_id  存入数据库   需要去掉前面的prepay_id头
            $pay_id = explode('=',$return['package'])[1];
            if($is = DB::table('user') -> where('openid',$openid) -> update(['pay_id' => $pay_id])) {
                return ['code'=>'1','pay_id_save' => 'OK','result' => $return];
            }
        } else {
            return ['code'=>'0','result'=>'error'];
        }
        
    }
    //支付成功回调处理订单状态
    public function wechatPay(Request $req)
    {
        $order_id = $req -> order_id;
        $price = $req -> price;
        $token = $req -> token;
         //是否有优惠券
         if($user = DB::table('user') -> where('token',$token) -> first()) {
            if($yh_id = DB::table('order') -> where('order_id',$order_id) -> value('is_yh')) {
                //使用了优惠券
                DB::table('user_you') -> where('id',$yh_id) -> update(['status' => 1]);
            }
            if(DB::table('order') -> where('order_id',$order_id) -> update(['status' => 1])) {   //更改订单状态
                //增加积分
                if($user -> level) {
                    $jifen_rule = DB::table('jifen_rule') -> first();
                    $jifen = floor($price / 100) * $jifen_rule -> jifen;   //积分
                }else{
                    $jifen = floor($price / 100);   //积分
                }
                $all_jifen = (int)$jifen + (int)$user -> jifen;
                $jifen_ok = DB::table('user') -> where('id',$user -> id) -> update(['jifen' => $all_jifen]);
                if($jifen_ok) {
                    //增加积分记录
                    $goods = DB::table('order_goods') -> where('order_id',$order_id) -> get();
                    $goods_name = [];
                    foreach($goods as $key => $val) {
                        $goods_name[$key] = DB::table('goods') -> where('id',$val -> goods_id) -> value('goods_name');
                    }
                    $record = [];
                    $record['user_id'] = $user -> id;
                    // $record['order_id'] = $order_id;
                    $record['goods'] = implode(',',$goods_name);
                    $record['time'] = time();
                    $record['jifen'] = $jifen;
                    $record['tag'] = '+';
                    if(DB::table('jifen_record') -> insert($record)) {
                        $openid = $user -> openid;
                        $templateid = 'WH6nBFLGzxSrDDvzPueN-LkCTjzRK_QQP2PV7u83loA';
                        $formId = $user -> pay_id;  //创建订单是存入账户
                        $page = '/pages/order/order?status=yzf';
                        $temp_order_id = $order_id;    //订单号
                        $temp_price = $price / 100 .'元';    //价格
                        $temp_date = date('Y年m月d日 H:i:s',time());
                        $temp_goods_name = $record['goods'];   //商品名称
                        if(DB::table('order') -> where('order_id',$order_id) -> value('order_type') == 'peisong') {
                            //自取提醒
                            $temp_address = '顾客电话' . $user -> phone;  //顾客电话
                        } else{
                            $temp_address = $user -> address . $user -> menpai;  //收货地址
                        }
                        $templateMsg = $this -> takeTemplateMsg($openid,$templateid,$formId,$page,$temp_price,$temp_order_id,$temp_date,$temp_goods_name,$temp_address);
                        return ['code' => '1000','msg' => 'OK','templateMsg' => $templateMsg];
                    } 
                }
            } 
         }else{
            return ['code' => '1001','msg' => 'err'];
         }
    }
    //处理支付成功的模板消息
    public function takeTemplateMsg($openid,$templateid,$formId,$page,$temp_price,$temp_order_id,$temp_date,$temp_goods_name,$temp_address)
    {
        $data = array(
            'touser' => $openid,
            'template_id' => $templateid,
            'page' => $page,
            'form_id' => $formId,
            'data' => [
                'keyword1' => [
                    'value' => $temp_price,
                    'color' => '#173177',
                ],
                'keyword2' => [
                    'value' => $temp_order_id,
                    'color' => '#173177',
                ],
                'keyword3' => [
                    'value' => $temp_date,
                    'color' => '#173177',
                ],
                'keyword4' => [
                    'value' => $temp_goods_name,
                    'color' => '#173177',
                ],
                'keyword5' => [
                    'value' => $temp_address,
                    'color' => '#173177',
                ]
            ]
        );
            $result = json_encode($data);
           return $this -> sendTemplateMsg($result);
    }
    //支付成功后发送模板消息
    public function sendTemplateMsg($data)
    {
        //使用appid和secret获取session_key  GET
        $appid = env('WECHAT_APPID');
        $secret = env('WECHAT_SECRET');
        $session_key = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
        $ACCESS_KEY = json_decode($session_key,true);
        //发送模板消息 POST
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$ACCESS_KEY['access_token'];
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER,0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据 (模板消息参数)
        curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        return $data;
    }
    //沙龙积分支付
    public function sl_jifenPay(Request $req)
    {
        if(in_array('',$req -> all())) {
            return ['code' => '1001','msg' => 'err','result' => '缺少重要参数'];
        }
        $sl = DB::table('shalong') -> where('id',$req -> sl_id) -> first();
        //查询是是否过了报名时间和报名人数是否已满
        if($sl -> end_date <= time()) {
            return ['code' => '1001','msg' => 'err','result' => '报名已结束'];
        }
        if($sl -> person_num && $sl -> person_num <= $sl -> person_num_ok){
            return ['code' => '1001','msg' => 'err','result' => '报名人数已满'];
        }
        $user = DB::table('user') -> where('token',$req -> token) -> first();
        if($user -> jifen < $sl -> price) {
            return ['code' => '1001','msg' => 'err','result' => '账户积分不足'];
        }
        $baoming = DB::table('shalong_person') -> where('openid',$user -> id) -> where('shalong_id',$req -> sl_id) -> count();
        if($baoming) {
            return ['code' => '1001','msg' => 'err','result' => '您已经报名'];
        }
        $new_jifen = $user -> jifen - $sl -> price;
        DB::beginTransaction();
        $is = DB::table('user') -> where('token',$req -> token) -> update(['jifen' => $new_jifen]);
        if($is) {
            //写入积分记录
            $jifen_record['user_id'] = $user -> id;
            $jifen_record['time'] = time();
            $jifen_record['goods'] = $sl -> title . ' 报名';
            $jifen_record['jifen'] = $sl -> price;
            $jifen_record['tag'] = '-';
            $iss = DB::table('jifen_record') -> insert($jifen_record);
            if($iss) {
                //沙龙报名人数加1
                $incs = DB::table('shalong') -> where('id',$req -> sl_id) -> increment('person_num_ok');
                $inc['openid'] = $user -> id;
                $inc['shalong_id'] = $req -> sl_id;
                $inc['time'] = time();
                $inc['price'] = $sl -> price;
                $inc_record = DB::table('shalong_person') -> insert($inc);
                if($incs && $inc_record) {
                    DB::commit();
                    return ['code' => '1000','msg' => 'OK','result' => '报名成功'];
                }else{
                    DB::rollBack();
                    return ['code' => '1001','msg' => 'err','result' => '报名失败'];
                }
            }
        }else{
            DB::rollBack();
            return ['code' => '1001','msg' => 'err','result' => '报名失败'];
        }
    }
    //沙龙支付
    public function accessPay(Request $req)
    {
        if(in_array('',$req -> all())) {
            return ['code' => '1001','msg' => 'err','result' => '缺少重要参数'];
        }
        $sl = DB::table('shalong') -> where('id',$req -> sl_id) -> first();
        //查询是是否过了报名时间和报名人数是否已满
        if($sl -> end_date <= time()) {
            return ['code' => '1001','msg' => 'err','result' => '报名已结束'];
        }
        if($sl -> person_num && $sl -> person_num <= $sl -> person_num_ok){
            return ['code' => '1001','msg' => 'err','result' => '报名人数已满'];
        }
        $user = DB::table('user') -> where('token',$req -> token) -> first();
        $baoming = DB::table('shalong_person') -> where('openid',$user -> id) -> where('shalong_id',$req -> sl_id) -> count();
        if($baoming) {
            return ['code' => '1001','msg' => 'err','result' => '您已经报名'];
        }
        if($req -> status == 1){   //账户支付
            //判断账户余额是否足够支付
            $access = DB::table('access') -> where('user_id',$user -> id) -> first();
            if(!$access) {
                return ['code' => '1001','msg' => 'err','result' => '账户未开通'];
            }
            if($access -> price < $sl -> price) {
                return ['code' => '1001','msg' => 'err','result' => '账户余额不足'];
            }
            //开始扣钱
            $new_price = $access -> price - $sl -> price;
            if($new_price >= 0) {
                DB::beginTransaction();    //余额写入
                $is = DB::table('access') -> where('user_id',$user -> id) -> update(['price' => $new_price]);
                if($is) {
                    //写入账户支付记录
                    $record['user_id'] = $user -> id;
                    $record['order_id'] = rand(100000,999999);
                    $record['time'] = time();
                    $record['goods'] = $sl -> title . ' 报名';
                    $record['price'] = $sl -> price;
                    $record['tag'] = '-';
                    $iss = DB::table('record') -> insert($record);
                    if($iss) {
                        //沙龙报名人数加1
                        $incs = DB::table('shalong') -> where('id',$req -> sl_id) -> increment('person_num_ok');
                        $inc['openid'] = $user -> id;
                        $inc['shalong_id'] = $req -> sl_id;
                        $inc['time'] = time();
                        $inc['price'] = $sl -> price;
                        $inc_record = DB::table('shalong_person') -> insert($inc);
                        if($incs && $inc_record) {
                            //加积分
                            $jifen_rule = DB::table('jifen_rule') -> first();
                            $jifen = floor($sl -> price) * $jifen_rule -> jifen;   //积分
                            $new_jifen = (int)$jifen + (int)$user -> jifen;
                            $is_jifen = DB::table('user') -> where('token',$req -> token) -> update(['jifen' => $new_jifen]);
                            //写入积分记录
                            $jifen_record['user_id'] = $user -> id;
                            $jifen_record['time'] = time();
                            $jifen_record['goods'] = $sl -> title . ' 报名';
                            $jifen_record['jifen'] = $sl -> price;
                            $jifen_record['tag'] = '+';
                            $isss = DB::table('jifen_record') -> insert($jifen_record);
                            if($is_jifen && $isss) {
                                DB::commit();
                                return ['code' => '1000','msg' => 'OK','result' => '报名成功'];
                            }
                        }else{
                            DB::rollBack();
                            return ['code' => '1001','msg' => 'err','result' => '报名失败'];
                        }
                    }
                }else{
                    DB::rollBack();
                    return ['code' => '1001','msg' => 'err','result' => '报名失败'];
                }
            }
        }elseif($req -> status == 2) {
            //微信支付
            if($user = DB::table('user') -> where('token',$req -> token) -> first()) {
                $openid = $user -> openid;
                $appid = env('WECHAT_APPID');    //小程序appid
                $mch_id = env('WECHAT_SHID');   //商户号
                $key = env('WECHAT_SHKEY');    //商户key
                $out_trade_no = rand(100000,999999);  //订单id
                $shaLongInfo = DB::table('shalong') -> where('id',$req -> sl_id) -> first();
                $total_fee = $shaLongInfo -> price * 100;  //金额
                // $total_fee = 1;  //金额
                $body = $shaLongInfo -> title;
                $weixinpay = new \WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee);
                $return = $weixinpay->pay();
                //把perpay_id  存入数据库   需要去掉前面的prepay_id头
                $pay_id = explode('=',$return['package'])[1];
                if($is = DB::table('user') -> where('openid',$openid) -> update(['pay_id' => $pay_id])) {
                    return ['code'=>'1000','result'=>$return,'pay_id_save' => 'OK','sl_id' => $req -> sl_id];
                }
            } else {
                return ['code'=>'1001','result'=>'error'];
            }
        }
        
    }
    //沙龙微信支付成功回调处理
    public function sl_wechatPay(Request $req)
    {
        DB::beginTransaction();
        $sl = DB::table('shalong') -> where('id',$req -> sl_id) -> first();
        $user = DB::table('user') -> where('token',$req -> token) -> first();
        //沙龙报名人数加1
        $incs = DB::table('shalong') -> where('id',$req -> sl_id) -> increment('person_num_ok');
        //沙龙报名记录
        $inc['openid'] = $user -> id;
        $inc['shalong_id'] = $req -> sl_id;
        $inc['time'] = time();
        $inc['price'] = $sl -> price;
        $inc_record = DB::table('shalong_person') -> insert($inc);
        if($incs && $inc_record) {
            //加积分
            $jifen_rule = DB::table('jifen_rule') -> first();
            $jifen = floor($sl -> price) * $jifen_rule -> jifen;   //积分
            $new_jifen = (int)$jifen + (int)$user -> jifen;
            $is_jifen = DB::table('user') -> where('token',$req -> token) -> update(['jifen' => $new_jifen]);
            //写入积分记录
            $jifen_record['user_id'] = $user -> id;
            $jifen_record['time'] = time();
            $jifen_record['goods'] = $sl -> title . ' 报名';
            $jifen_record['jifen'] = $sl -> price;
            $jifen_record['tag'] = '+';
            $iss = DB::table('jifen_record') -> insert($jifen_record);
            if($is_jifen && $iss) {
                DB::commit();
                $openid = $user -> openid;
                $templateid = 'J5oTMyQuzEBhSG3NDdBuIxq0TFKzsF6Hp4vl6FcK0iM';
                $formId = $user -> pay_id;  //创建订单是存入账户
                $page = '/pages/shalong/shalong';
                $temp_price = $sl -> price . '元';    //价格
                $temp_date = date('Y年m月d日 H:i:s',time());
                $temp_name = $sl -> title . ' 报名';   //商品名称
                $templateMsg = $this -> slTemplateMsg($openid,$templateid,$formId,$page,$temp_name,$temp_date,$temp_price);
                return ['code' => '1000','msg' => 'OK','result' => '报名成功','templateMsg' => $templateMsg];
            }else{
                DB::rollBack();
                return ['code' => '1001','msg' => 'err','result' => '报名失败,如有款项将在24小时内退款'];
            }
        }else{
            DB::rollBack();
            return ['code' => '1001','msg' => 'err','result' => '报名失败,如有款项将在24小时内退款'];
        }
    }
    //沙龙报名成功模板消息
    public function slTemplateMsg($openid,$templateid,$formId,$page,$temp_name,$temp_date,$temp_price)
    {
        $data = array(
            'touser' => $openid,
            'template_id' => $templateid,
            'page' => $page,
            'form_id' => $formId,
            'data' => [
                'keyword1' => [
                    'value' => $temp_name,
                    'color' => '#173177',
                ],
                'keyword2' => [
                    'value' => $temp_date,
                    'color' => '#173177',
                ],
                'keyword3' => [
                    'value' => $temp_price,
                    'color' => '#173177',
                ]
            ]
        );
            $result = json_encode($data);
            return $this -> sendTemplateMsg($result);
    }

    //前台充值
    public function accessPayMoney(Request $req)
    {
        if(in_array('',$req -> all())){
            return ['code'=>'1001','msg' => 'err','result'=>'error'];
        }
        //查询充值套餐
        $level = DB::table('vip_level') -> where('id',$req -> id) -> first();
        //下单进行支付
        //微信支付
        if($user = DB::table('user') -> where('token',$req -> token) -> first()) {
            $openid = $user -> openid;
            $appid = env('WECHAT_APPID');    //小程序appid
            $mch_id = env('WECHAT_SHID');   //商户号
            $key = env('WECHAT_SHKEY');    //商户key

            $out_trade_no = rand(100000,999999);  //订单id
            $total_fee = $level -> level_price * 100;  //金额
            // $total_fee = 1;  //金额
            $body = $level -> level_name . '充值';
            $weixinpay = new \WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee);

            $return = $weixinpay->pay();
            //把perpay_id  存入数据库   需要去掉前面的prepay_id头
            $pay_id = explode('=',$return['package'])[1];
            if($is = DB::table('user') -> where('openid',$openid) -> update(['pay_id' => $pay_id])) {
                return ['code'=>'1000','result'=>$return,'pay_id_save' => 'OK','order_id' => $out_trade_no];
            }
        } else {
            return ['code'=>'1001','result'=>'error'];
        }
    }
    //支付成功进行充值
    public function accessPayMoneyDo(Request $req)
    {
        if(in_array('',$req -> all())) {
            return ['code' => '1001','msg' => 'err','result' => '缺少重要参数'];
        }
        $level = DB::table('vip_level') -> where('id',$req -> id) -> first();
        $user = DB::table('user') -> where('token',$req -> token) -> first();
        DB::beginTransaction();
        //加钱和赠送  加等级
        $level_price = $level -> level_price;   //充值金额
        $send = $level -> send;   //赠送
        $new_price = $level_price + $user -> chongzhi_price;
        $is = DB::table('user') -> where('id',$user -> id) -> update(['chongzhi_price' => $new_price]);
        if($user -> level < $level -> id) {   //如果用户等级小于现在才变更等级
            DB::table('user') -> where('id',$user -> id) -> update(['level' => $level -> id]);
        }
        //但是还是要送优惠券   4-3
        //  1查询当钱充值等级可用的优惠券
        $youhui = DB::table('admin_you') -> where('vip',$level -> id) -> get();
        if($youhui){
            foreach($youhui as $key => $val) {
                // 发放优惠券
                for($i=0;$i<$val -> send_num;$i++){
                    $user_you['youhui_id'] = $val -> id;  //优惠券id
                    $user_you['user_id'] = $user -> id;  //用户id
                    $user_you['name'] = $val -> name;   //优惠券名称
                    $user_you['type'] = $val -> type;   //优惠券  1直减  2折扣
                    $user_you['price'] =  $val -> price;   //优惠券额度
                    $user_you['use_height'] = $val -> use_height;    //满多少钱可用   无门槛为0
                    $user_you['md'] = $val -> md;    //使用门店限制   0为全部门店  其他为门店id 
                    $user_you['use_type'] = $val -> use_type;   //商品使用范围  1全部 2以下可用  3以下不可用
                    $user_you['use_size'] = $val -> use_size;    //指定商品id   指定商品不可用id   全部不需要id
                    $user_you['tips'] = $val -> tips;              //优惠券说明
                    $user_you['addtime'] = time();      //领取时间
                    $user_you['end_date'] = time() + $val -> end_date * 86400;    //优惠券过期时间  * 时间戳
                    $user_you['status'] = 0;                    //0未使用  1已使用
                    $user_you['vip'] = $level -> id;                    //会员等级
                    DB::table('user_you') -> insert($user_you);
                }  
            }
        }
        //账户加钱
        $access = DB::table('access') -> where('user_id',$user -> id) -> first();
        $new_access_price = $access -> price + $level_price + $send;
        $iss = DB::table('access') -> where('user_id',$user -> id) -> update(['price' => $new_access_price]);
        if($is && $iss) {
            //加充值记录
            $record['user_id'] = $user -> id;
            $record['order_id'] = $req -> order_id;
            $record['time'] = time();
            $record['goods'] = $level -> level_name . ' 充值';
            $record['price'] = $level_price + $send;
            $record['tag'] = '+';
            $iss = DB::table('record') -> insert($record);
            //发送模板消息
            $openid = $user -> openid;
            $templateid = 'ZB4WYWMXwlY5Mk1Zs2TCKRchZeo2HxY0RaI8WM8ry14';
            $formId = $user -> pay_id;  //创建订单是存入账户
            $page = '/pages/access/access';
            $temp_date = date('Y年m月d日 H:i:s',time());
            $temp_price = $level_price;
            $temp_send = $send;
            $temp_all = DB::table('access') -> where('user_id',$user -> id) -> value('price');
            $templateMsg = $this -> moneyPayTemplateMsg($openid,$templateid,$formId,$page,$temp_date,$temp_price,$temp_send,$temp_all);
            DB::commit();
            return ['code' => '1000','msg' => 'OK','templateMsg' => $templateMsg];
        }else{
            return ['code' => '1001','msg' => 'err','templateMsg' => ''];
            DB::rollBack();
        }
    }
    //充值成功发送模板消息
    public function moneyPayTemplateMsg($openid,$templateid,$formId,$page,$temp_date,$temp_price,$temp_send,$temp_all)
    {
        $data = array(
            'touser' => $openid,
            'template_id' => $templateid,
            'page' => $page,
            'form_id' => $formId,
            'data' => [
                'keyword1' => [
                    'value' => '账户充值',
                    'color' => '#173177',
                ],
                'keyword2' => [
                    'value' => $temp_date,
                    'color' => '#173177',
                ],
                'keyword3' => [
                    'value' => $temp_price,
                    'color' => '#173177',
                ],
                'keyword4' => [
                    'value' => $temp_send,
                    'color' => '#173177',
                ],
                'keyword5' => [
                    'value' => $temp_all,
                    'color' => '#173177',
                ]
            ]
        );
            $result = json_encode($data);
            return $this -> sendTemplateMsg($result);
    }
    //订单提醒
    public function sendSocketMsg(Request $req)
    {
        return $req -> all();
    }
}
