<?php

namespace App\Jobs\OpenWork\Msg;

use App\Facades\Servers\Logs\Log;
use App\Servers\DB\DbService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Facades\Servers\Wechat\OpenWork;
use App\Models\OpenWork\Msg\Task;

/**
 * 群发消息任务
 * 
 */
class TaskJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $taskData;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $taskData)
    {
        $this->taskData = $taskData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            // 接收参数
            $taskData                           = $this->taskData;
            // 切换数据
            (new DbService())->getConnectionNameByCorpId($taskData['corpid']);
            // 查询
            $Task                               = (new Task());
            // 查询所有
            $list                               = $Task->query()->where(['corpid' => $taskData['corpid'], 'tpl_id' => $taskData['tpl_id']])->get(['id', 'msg', 'msgid'])->toArray();
            // 实例
            $work                                = OpenWork::getWork($taskData['corpid']);
            // 返回结果
            $updateList                         = [];
            // 获取所有数据
            foreach ($list as  $value)          {
                // 已经发送的，不再重新发送
                if ( $value['msgid'] )          continue;
                // 发送结果
                $value['msg']                   = json_decode($value['msg'], true);
                // 获取token
                $result                         = $work->external_contact_message->submit($value['msg']);
                // 临时结果
                $temp                           = ['id' => $value['id'], 'corpid' => $taskData['corpid'], 'tpl_id' => $taskData['tpl_id'], 'status' => 4, 'errmsg' => '', 'msgid' => '','update_time' => time()];
                // 接口返回失败的话
                if (!$result) {
                    // 错误信息
                    $temp['errmsg']             = '企微接口返回失败';
                    Log::info('job_error', '群发消息任务队列请求企微接口失败', ['data' => $taskData]);
                    // 接口返回失败的话
                } else if ($result['errcode']) {
                    // 获取错误信息
                    $temp['errmsg']             = OpenWork::getErrmsg($result['errcode']);
                    Log::info('job_error', '群发消息任务队列请求企微接口失败', ['data' => $taskData,'error_data'=>$result]);
                } else {
                    // 修改结果
                    $temp['msgid']              = $result['msgid'];
                    $temp['status']             = 0;
                }
                // 修改列表
                $updateList[]                   = $temp;
            }
            // 修改状态
            $result                             = $Task->query()->upsert($updateList, 'id');
            // 返回结果
            if (!$result)                      Log::error('openwork_msg_jobs', $updateList);
        } catch (\Throwable $th) {
            // 错误信息
            Log::info('job_error', '群发消息任务队列执行失败', ['data' => $this->taskData, 'error' => $th->getMessage()]);
        }
    }


    public function failed(\Throwable $exception)
    {
        Log::info('job_error', '群发消息任务队列完全执行失败', ['data' => $this->taskData, 'error' => $exception->getMessage()]);
    }
}
