<?php
namespace App\Helper;

use JPush\Client as JPush;
use App\Models\UserInfoModel;

trait JpushHelper
{
    public function jPush($title,$content='',$userid=0,$type=0,$id=0) {
        $app_key = '69838317211448192366f9d8';
        $master_secret = 'f202d10301151e1816b49e55';
        $client = new JPush($app_key, $master_secret, storage_path('logs/jpush.log'));

        \Log::info('jpush start!');
//        $push = new Push;
//        $push->title = $title;
//        $push->content = $content;
//        $push->user_id = $userid;
//        $res=$push->save();
//        if($userid){
            $user = UserInfoModel::find($userid);
//        }
        if($user&&$user->jpush){
            $regId = array($user->jpush);
            $options = array(
                'apns_production' => true,
            );
            try {
                $pusher = $client->push();
                $pusher->setPlatform(['ios', 'android']);
//                $pusher->addAllAudience();
                $pusher->addRegistrationId($regId);
                if($type!=0&&$id!=0){
                    $pusher->androidNotification($title,[
                        'title' => $content,
                        'content_type' => 'text',
                        'extras' => [
                            'type' => $type,
                            'id' => $id,
                        ]
                    ]);
                    $pusher->iosNotification($title, [
                        'sound' => 'sound',
                        'badge' => '+1',
                        'extras' => [
                            'type' => $type,
                            'id' => $id,
                        ]
                    ]);
                }
                $pusher->setNotificationAlert($title);
                $pusher->options($options);
                $pusher->send();
                \Log::info('jpush send!');
            } catch (\JPush\Exceptions\APIConnectionException $e) {
                // try something here
                \Log::error($e);
            } catch (\JPush\Exceptions\APIRequestException $e) {
                // try something here
                \Log::error($e);
            }
        }
    }

}