<?php
namespace App\Helper;

use JPush\Client as JPush;
use App\Models\Push;
use App\User;

trait JpushHelper
{
    public function jPush($title,$content='',$userid=0) {
        $app_key = '55efccbdf77071c59ccbf0cd';
        $master_secret = 'b9da2f5151a29889cbabee3f';
        $client = new JPush($app_key, $master_secret, storage_path('logs/jpush.log'));

        $push = new Push;
        $push->title = $title;
        $push->content = $content;
        $push->user_id = $userid;
        $res=$push->save();
        if($userid){
            $user = User::find($userid);
        }
        if($res&&$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);
                $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);
            }
        }
    }

}