<?php

namespace App\Jobs;

use App\Modules\OfficialAccount\Models\WechatTemplateMsgs;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Redis;

class TemplateMsgSendJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        \Log::info('========初始化一个实例');
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        try {

            $wechatTemplateMsgs = $this->data;

            $appid = $wechatTemplateMsgs['appid'];
            $template_id = $wechatTemplateMsgs['template_id'];
            $send_time = $wechatTemplateMsgs['send_time'];
            $template_content = $wechatTemplateMsgs['template_content'];
            $redirect_url = $wechatTemplateMsgs['redirect_url'];
            $task_id = $wechatTemplateMsgs['id'];

            $templateMsgs = WechatTemplateMsgs::wechatTemplateMsgsById($task_id);
            if (!$templateMsgs || $templateMsgs['del_flag'] == 1 || $templateMsgs['status'] == '4'){
                \Log::info('========模板消息已被停止或删除，不发送==========task_id = '.$wechatTemplateMsgs['id']);
                return;
            }else{
                \Log::info('========现将模板消息设置成发送状态 "8" 用户不能操作（删除，编辑，停止） = '.$wechatTemplateMsgs['id']);
                $templateMsgs['status'] = '8';
                $templateMsgs->save();

                $officialAccountArray = $templateMsgs->toArray();
                Redis::hset('send_wechat_msg:task_id:'.$templateMsgs['id'], 'wechat_msg', json_encode($officialAccountArray));
            }

            \Log::info('-----------------模板消息参数--------------appid = '.$appid.', channelid = '.$wechatTemplateMsgs['distribution_channel_id']);
            \Log::info('========发送的模板消息内容========== template_content');
            \Log::info($template_content);
            //1,通过筛选得到条件符合的强关用户
            $skip = 0;
            while ( $skip <= 2500000) {
                \Log::info('-------------模板消息-----分页取强关用户，目前页数----------'.$skip);
                $users = ForceSubscribeService::forceUserCountByTemplatePrams($appid,$wechatTemplateMsgs['distribution_channel_id'],$wechatTemplateMsgs['subscribe_time'],$wechatTemplateMsgs['sex'],$wechatTemplateMsgs['balance'],$wechatTemplateMsgs['category_id'],$wechatTemplateMsgs['order_type'],$skip);
                \Log::info('-----------------实际发送模板消息用户数量-------------'.count($users));
                if(count($users)>0){
                    for ($i=0; $i < count($users); $i++) {

                        //2，循环用户发送模板消息
                        //发送到最后一条时，将
                        if ($i == count($users)-1) {

                            $data = array();
                            $data['statusstr'] = (time());
                            $data['openid'] = $users[$i]['openid'];
                            $data['appid'] = $appid;
                            $data['template_id'] = $template_id;

                            //4，通过RebitMQ发送模板消息
                            // $data['template_content'] = $templateSendContents;
                            $data['template_content'] =str_replace(".DATA","",$template_content);
                            $data['type'] = 'last_task';// last_task,one_task
                            $data['url'] = $redirect_url;
                            $data['task_id'] = $task_id;
                            $data['send_time'] = $send_time;
                            $send_data=array(
                                'send_time'=>$send_time,
                                'data' => $data
                            );

                            $now_time = strtotime($send_time)-time();
                            $delay = $now_time;
                            \Log::info('------------------发送最后一条模板消息----------task_id = '.$task_id.', 时间差 = '.$now_time);
                            $job = (new SendTemplate($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_template_list');
                            dispatch($job);


                        }else{
                            $data = array();
                            $data['statusstr'] = (time());
                            $data['openid'] = $users[$i]['openid'];
                            $data['appid'] = $appid;
                            $data['template_id'] = $template_id;

                            \Log::info('========================[[[[send template message]]]]====================');
                            \Log::info(str_replace(".DATA","",$template_content));
                            $data['template_content'] =str_replace(".DATA","",$template_content);
                            $data['type'] = 'one_task';// last_task,one_task
                            $data['url'] = $redirect_url;
                            $data['task_id'] = $task_id;
                            $data['send_time'] = $send_time;
                            $send_data=array(
                                'send_time'=>$send_time,
                                'data' => $data
                            );

                            $now_time = strtotime($send_time)-time();
                            $delay = $now_time;
                            \Log::info('========================发送模板消息 不是最后一条模板=================task_id = '.$task_id.'. openid = '.$data['openid'].', 时间差 = '.$delay);
                            $job = (new SendTemplate($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_template_list');
                            dispatch($job);

                        }

                    }

                }else{
                    \Log::info('========================发送模板消息_没找到用户===================='.$task_id);
                    break;
                }

                $skip += count($users);
            }

            //更新模板消息的用户数量并更新redis
            \Log::info('========================更新模板消息并存redis====================task_id = '.$task_id);
            $templateMsgs['user_num'] = $skip;
            $templateMsgs->save();

            $officialAccountArray = $templateMsgs->toArray();
            Redis::hset('send_wechat_msg:task_id:'.$templateMsgs['id'], 'wechat_msg', json_encode($officialAccountArray));

        } catch (\Exception $e) {
            \Log::info('========================循环用户发送模板消息时报错====================');
            \Log::info($e->getMessage());
        }

    }
}
