<?php

namespace App\Jobs;
use App\Http\Controllers\WechatController;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Redis;
use DB;
class SendBatchWechatMaterial extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    private $data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }
 
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        \Log::info('SendBatchWechatMaterial start');
        $param = $this->data;
        \Log::info($param);

        try{
            $param = $param['data'];
            $this->start($param);
        }catch(\Exception $e){
            \Log::error($e->getMessage());
        }


        \Log::info('SendBatchWechatMaterial end');

    }

    public function start($param)
    {
        \Log::info('$param2');\Log::info($param);

        //检查参数
        if(!($param['appid']&&$param['media_id']&&$param['openids']&&$param['task_id'])){
            \Log::info('params_empty');
            return;
        }
        
        // 只有1个用户,则加一个凑数
        if(count($param['openids']) == 1){
            $param['openids'][] = 'test';
        }
        
        //服务号高级发送接口openid限定数量为2-10000之间
        if(!is_array($param['openids'])||count($param['openids'])>10000||count($param['openids'])<2){
            \Log::info('SendBatchWechatMaterial:over_open_num_limt');
            return;
        }

        //调用服务号高级发送接口
        try{
            $WechatController = new WechatController($param['appid']);
            $res = $WechatController->app->broadcast->sendNews($param['media_id'],$param['openids']);
            \Log::info('sendNews_res:');\Log::info($res);
            //发送失败
            if($res['errcode']!=0){
                \Log::info("SendBatchWechatMateria {$param['task_id']} errcode:{$res['errcode']} errmsg:{{$res['errcode']}}");
                return;
            }
            //保存msg_id和msg_data_id
            DB::connection('api_mysql')
                ->table('wechat_material_send_msgs')
                ->where('id',$param['task_id'])
                ->update(['wechat_msg_id'=>$res['msg_id'],'wechat_msg_data_id'=>$res['msg_data_id']]);
            //发送成功更新发送人数
            DB::connection('api_mysql')
                ->table('wechat_material_send_msgs')
                ->where('id',$param['task_id'])
                ->increment('receive_user_num',count($param['openids']));
            //若为最后一条消息则更新发送状态为发送完成
            if($param['type']=='last_task'){
                DB::connection('api_mysql')
                    ->table('wechat_material_send_msgs')
                    ->where('id',$param['task_id'])
                    ->update(['status'=>'has_send','updated_at'=>date('Y-m-d H:i:s')]);
            }
        }catch(\Exception $e){
            \Log::error('sendNews_ept:'.$e->getMessage());
        }
        return;
    }
    
    /**
     * The job failed to process.
     *
     * @param  Exception  $exception
     * @return void
     */
    public function failed(Exception $exception)
    {
    	// Send user notification of failure, etc...
    	v('SendBatchWechatMaterial_ept:'.$exception->getMessage().' data:'.json_encode($this->data));
    }
    
}