<?php

namespace App\Jobs;

use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use DB;
use Redis;
use WechatOP;
use Log;

class ForceUserProperty extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    private $data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $data['send_time']=date("Y-m-d H:i:s");
        $this->data = $data;
    }
 
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{
            $appid = $this->data['appid'];
            $openid = $this->data['openid'];
            $current_time = date('Y-m-d H:i:s');
            $user_data = DB::connection('zhuishuyun_user')->table('force_subscribe_user_properties')->where('appid',$appid)->where('openid',$openid)->first();

            if(!$user_data)
            {
                $redis_key = '[wechat_op.common.component_refresh_token.'.$appid.']';
                $component_refresh_token = Redis::Get($redis_key);

                $options = [
                    'app_id'    => $appid,
                    'secret'    => env('WECHAT_OP_SECRET'),   // 仅适用于 单独配置公众号
                    'token'     => env('WECHAT_OP_TOKEN'),   // 仅适用于 单独配置公众号
                    'aes_key'   => env('WECHAT_OP_AES_KEY'),   // 仅适用于 单独配置公众号
                    'auth_type' => 'COMPONENT', // COMPONENT 开放平台授权公众号，MANUAL 单独配置公众号
                    'component_refresh_token' => $component_refresh_token,   // 授权回调时获取的 authorizer_refresh_token，仅适用于 开放品台授权公众号
                    'cache'   => [
                        'driver' => 'redis',   // redis, filesystem, laravel
                        'dir' => storage_path('tmp') // 只有为filesystem时候这个目录才有效
                    ],
                ];
                $app = WechatOP::app($options);
                $info = $app->user->get($openid);
                $nickname = $info->nickname;
                $sex = $info->sex;
                $data = [
                    'openid'=>$openid,
                    'appid'=>$appid,
                    'current_nickname'=>trim($nickname),
                    'sex'=>$sex,
                    'created_at'=>$current_time,
                    'updated_at'=>$current_time,
                ];
                DB::connection('zhuishuyun_user')->table('force_subscribe_user_properties')->insert($data);
            }
        }
        catch(\Exception $e){
        	v('handle_ept: info:'.$e->getMessage());
        }

    }
    
    /**
     * The job failed to process.
     *
     * @param  Exception  $exception
     * @return void
     */
    public function failed(Exception $exception)
    {
    	// Send user notification of failure, etc...
    	v('sendNews_ept:'.$exception->getMessage().' data:'.json_encode($this->data));
    }
    
}
