<?php

namespace App\Jobs;

use App\Modules\OfficialAccount\Models\CustomSendMsgs;
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 CustomMsgSendJob 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 {

            $customSendMsgsPrams = $this->data;

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

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



            $appids = $customSendMsgsPrams['appid'];

            $appidArray  = explode(',', $appids);

            $usercountnum = 0;

            for ($j=0; $j < count($appidArray); $j++) {

                $skip = 0;

                while ( $skip <= 2500000) {

                    \Log::info('------------------分页取强关用户，目前页数----------'.$skip);

                    //5,获取所选条件下筛选出的用户
                    $sign_time = 'z';
                    $force_user = ForceSubscribeService::forceUserCountByCustomPrams($appidArray[$j],$customSendMsgsPrams['distribution_channel_id'],$customSendMsgsPrams['subscribe_time'],$customSendMsgsPrams['sex'],$customSendMsgsPrams['balance'],$customSendMsgsPrams['category_id'],$customSendMsgsPrams['order_type'],$sign_time,$skip);

                    if (count($force_user)>0) {

                        $usercountnum += count($force_user);

                        for ($i=0; $i < count($force_user); $i++) {

                            if ($i == count($force_user)-1) {

                                // \Log::info('--------------------客服消息接收用户 last_task');
                                // \Log::info($force_user[$i]['openid']);
                                // \Log::info($appidArray[$j]);
                                //  7，循环用户发送客服消息
                                $data = array();
                                $data['openid'] = $force_user[$i]['openid'];
                                $data['appid'] = $appidArray[$j];
                                $data['news_content'] = $customSendMsgsPrams['content'];
                                $data['type'] = 'last_task';
                                $data['task_id'] = $customSendMsgsPrams['task_id'];
                                $data['send_time'] = $customSendMsgsPrams['send_time'];
                                $send_data=array(
                                    'send_time'=>$customSendMsgsPrams['send_time'],
                                    'data' => $data
                                );

                                $now_time = strtotime($customSendMsgsPrams['send_time'])-time();
                                \Log::info('------------------！！！发送客服消息时间！！！----------');
                                \Log::info($customSendMsgsPrams['send_time']);
                                \Log::info($now_time);

                                $delay = $now_time;
                                // \Log::info('客服消息找到用户并发送===================================');
                                // \Log::info($data['openid']);
                                // \Log::info($data['appid']);
                                // \Log::info($data['news_content']);
                                \Log::info('------------------发送最后一条客服消息----------'.$customSendMsgsPrams['task_id']);
                                $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
                                dispatch($job);

                            }else{

                                // \Log::info('--------------------客服消息接收用户 one_task');
                                // \Log::info($force_user[$i]['openid']);
                                // \Log::info($appidArray[$j]);
                                //7，循环用户发送客服消息
                                $data = array();
                                $data['openid'] = $force_user[$i]['openid'];
                                $data['appid'] = $appidArray[$j];
                                $data['news_content'] = $customSendMsgsPrams['content'];
                                $data['type'] = 'one_task';
                                $data['task_id'] = $customSendMsgsPrams['task_id'];
                                $data['send_time'] = $customSendMsgsPrams['send_time'];
                                $send_data=array(
                                    'send_time'=>$customSendMsgsPrams['send_time'],
                                    'data' => $data
                                );

                                $now_time = strtotime($customSendMsgsPrams['send_time'])-time();
                                \Log::info('------------------！！！发送客服消息时间！！！----------');
                                \Log::info($customSendMsgsPrams['send_time']);
                                \Log::info($now_time);

                                $delay = $now_time;
                                // \Log::info('客服消息找到用户并发送===================================');
                                // \Log::info($data['openid']);
                                // \Log::info($data['appid']);
                                // \Log::info($data['news_content']);
                                $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
                                dispatch($job);

                            }


                        }
                    }else{
                        \Log::info('------------------发送客服消息没有查找到强关用户----------'.$customSendMsgsPrams['task_id']);
                        break;
                    }

                    $skip += count($force_user);

                }

            }

            $customSendMsgs['user_num'] = $usercountnum;
            $customSendMsgs->save();

            return 1;

            // }

        } catch (\Exception $e) {
            \Log::info('===================================发送客服消息报错');
            \Log::info($e->getMessage());
            return 0;
        }
    }
}
