<?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\TemplateResult as TemplateResultModel;
use App\Servers\OpenWork\External\ContactService;


/**
 * SCRM 客户群发成员执行结果
 * @author  唐远望
 * @version  1.0
 * @date   2025-08-12
 */
class MembersSendResultsInGroupsJobs 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 . '_MembersSendResultsInGroupsJobs',
                                        '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'];
            $userid                 = $this->message_data['userid'];
            $tplId                  = $this->message_data['tpl_id'];
            // 同步获取企业群发成员执行结果
            $work                   = OpenWork::getWork($corpid);
            $result                 = $work->external_contact_message->getGroupmsgSendResult($msgId, $userid, $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['send_list'])) {
                // 发送成员执行结果
                $sendList            = $result['send_list'];
                // 接收者ID，//external_userid 外部联系人userid，群发消息到企业的客户群不返回该字段，chat_id 外部客户群id，群发消息到客户不返回该字段
                $receiveIds          = isset($sendList[0]['external_userid']) ? array_column($sendList, 'external_userid') : array_column($sendList, 'chat_id');
                //获取本地群发成员任务列表
                $localMsgList        = TemplateResultModel::where(['tpl_id'=>$tplId,'msgid'=>$msgId])->whereIn('receive_id',$receiveIds)->select(['id','status','receive_id'])->get()->toArray();
                // 换格式
                $localMsgList        = $localMsgList ? array_column($localMsgList, null,'receive_id') : [];
                // 明文ID转换成明文ID服务，并获取本地群发成员任务列表，并更新
                $ContactService      = new ContactService();
                // 要新增的数据
                $insertData          = [];
                // 循环发送信息
                foreach ($sendList 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'];
                    }
                    //外部联系人userid  or 外部客户群id
                    $receiveId      = isset($task['external_userid']) ? $task['external_userid'] : ($task['chat_id'] ? $task['chat_id'] : '');
                    // 发送时间
                    $sendTime       = isset($task['send_time']) ? $task['send_time'] : 0;
                    // 如果存在接受者的数据
                    if( isset($localMsgList[$receiveId]) ) {
                        // 判断状态是不是一致
                        if( $localMsgList[$receiveId]['status'] != $task['status'] ){
                            // 更新数据
                            TemplateResultModel::where(['id'=>$localMsgList[$receiveId]['id']])->update(['status'=>$task['status'],'send_time'=>$sendTime]);
                        }
                    }else{
                        $insertData[]= [
                                        'tpl_id'        => $tplId,
                                        'msgid'         => $msgId,
                                        'userid'        => $task['userid'],
                                        'receive_id'    => $receiveId,
                                        'status'        => $task['status'], // 0-未发送 1-已发送 2-因客户不是好友导致发送失败 3-因客户已经收到其他群发消息导致发送失败
                                        'send_time'     => $sendTime,
                                        'insert_time'   => time()
                                    ];
                    }
                }
                // 统一写入
                TemplateResultModel::insert($insertData);
            }
            //删除任务记录
            $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;
                // 下一队列
                MembersSendResultsInGroupsJobs::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();
        }
    }
}
