<?php

namespace App\Jobs\OpenWork\Statistics;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
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;


/**
 * SCRM 客户群发数据任务
 * @author  唐远望
 * @version  1.0
 * @date   2025-08-12
 */
class CustomerGroupSendingListJobs 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 . '_MomentsCustomerInteractionJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $chatType = $this->message_data['chat_type'];
            $corpid = $this->message_data['corpid'];
            $userId = $this->message_data['userid'];
            $startTime = $this->message_data['start_time'];
            $endTime = $this->message_data['end_time'];
            $msgId = $this->message_data['msg_id'];
            $limit = $this->message_data['limit'];
            $cursor = $this->message_data['cursor'];
            // 同步获取群发记录列表
            $work                    = OpenWork::getWork($corpid);
            $result                 = $work->external_contact_message->getGroupmsgListV2($chatType, $startTime, $endTime, $msgId, $limit, $cursor, $userId);
            // 如果获取失败
            if (!$result) {
                Log::info('job_error', '获取客户群发数据失败', ['data' => $this->message_data]);
            }
            if (isset($result['errcode']) && $result['errcode'] > 0) {
                $error_message = OpenWork::getErrmsg($result['errcode']);
                Log::info('job_error', '获取客户群发数据失败', ['data' => $this->message_data, 'error' => $error_message]);
            }




            //如果存在下一页，继续执行
            if (isset($result['next_cursor'])) {
                $next_cursor = $result['next_cursor'];
                $next_message_data = $this->message_data;
                $next_message_data['cursor'] = $next_cursor;
                CustomerGroupSendingListJobs::dispatch($next_message_data);
            }
            //删除任务记录
            $this->Records->delete();
        } 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();
        }
    }
}
