<?php

namespace App\Jobs\OpenWork\Statistics;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Servers\DB\DbService;
use App\Models\OpenWork\job\Records;
use App\Facades\Servers\Logs\Log;
use App\Facades\Servers\Wechat\OpenWork;
use App\Models\OpenWork\Msg\Task as TaskModel;
use App\Jobs\OpenWork\Statistics\MembersSendResultsInGroupsJobs;
use App\Servers\OpenWork\External\ContactService;


/**
 * SCRM 客户群发成员任务数据
 * @author  唐远望
 * @version  1.0
 * @date   2025-08-12
 */
class CustomerGroupSendingMembersJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $message_data;
    protected $Records;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $companyId          = $this->message_data['company_id'];
            // 切换数据库
            (new DbService())->getConnectionNameByCompanyId($companyId);
            // 创建任务记录
            $this->Records      = Records::create([
                                    'job_id'        => $companyId . '_CustomerGroupSendingMembersJobs',
                                    'name'          => static::class,
                                    'payload'       => json_encode($this->message_data),
                                    'status'        => 'processing',
                                    'started_at'    => now()
                                ]);
            // 组合数据
            $corpid             = $this->message_data['corpid'];
            $limit              = $this->message_data['limit'];
            $msgId              = $this->message_data['msg_id'];
            $cursor             = $this->message_data['cursor'];
            $tplId              = $this->message_data['tpl_id'];
            // 同步获取群发成员发送任务列表
            $work               = OpenWork::getWork($corpid);
            // 获取群发成员任务列表
            $result             = $work->external_contact_message->getGroupmsgTask($msgId, $limit, $cursor);
            // 如果获取失败
            if (!$result)       Log::info('job_error', '获取客户群发成员任务失败',[$this->message_data]);
            // 如果获取失败
            if ( !empty($result['errcode']) )  Log::info('job_error', '获取客户群发成员任务失败', ['data' => $this->message_data, 'error' => OpenWork::getErrmsg($result['errcode'])]);
            // 如果有任务离别哦
            if (!empty($result['task_list'])) {
                // 服务
                $ContactService = new ContactService();
                // 获取列表
                $taskList       = $result['task_list'];
                //获取本地群发成员任务列表
                $localTaskList  = TaskModel::where(['corpid'=>$corpid,'msgid'=>$msgId])->select(['id','status','userid'])->get()->toArray();
                // 换格式
                $localTaskList  = $localTaskList ? array_column($localTaskList, null,'userid') : [];
                // 循环处理任务数据
                foreach ($taskList as $task) {
                    //处理成员明文ID
                    if (isset($task['userid'])) {
                        $open_userid_info = $ContactService->get_external_contact_batchget_user_list_by_data($corpid, [$task['userid']]);
                        $task['userid'] = !empty($open_userid_info) ? $open_userid_info[0] : $task['userid'];
                    }
                    // 发送时间
                    $send_time  = isset($task['send_time']) ? $task['send_time']:'0';
                    // 如果有任务ID则更新
                    if ( isset($localTaskList[$task['userid']]) ) {
                        // 判断状态是不是一致 
                        if( $localTaskList[$task['userid']]['status'] != $task['status'] ){
                            // 更新状态，0-未发送 2-已发送
                            TaskModel::where(['id'=>$localTaskList[$task['userid']]['id']])->update(['status'=>$task['status'],'send_time'=>$send_time]);
                        }
                    }
                    // 获取成员执行结果
                    MembersSendResultsInGroupsJobs::dispatch(['corpid' => $corpid, 'msg_id' => $msgId, 'cursor' => '', 'limit'  => 1000, 'company_id' => $companyId,'userid'=>$task['userid'],'tpl_id'=>$tplId]);
                }
            }
            //删除任务记录
            $this->Records->delete();
            //如果存在下一页，继续执行
             if (isset($result['next_cursor']) && $result['next_cursor'] !='') {
                $next_cursor = $result['next_cursor'];
                $next_message_data = $this->message_data;
                $next_message_data['cursor'] = $next_cursor;
                CustomerGroupSendingMembersJobs::dispatch($next_message_data);
            }
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', '同步客户群发成员任务失败', ['data' => $this->message_data, 'error' => $e->getMessage()]);
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', '同步客户群发成员任务彻底失败', ['data' => $this->message_data, 'error' => $exception]);
        // 失败处理...
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
