<?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;
use App\Models\OpenWork\Statistics\Moment\User as MomentUser;
use App\Jobs\OpenWork\Statistics\MomentsCustomerListJobs;
use App\Servers\OpenWork\External\ContactService;


/**
 * SCRM 同步朋友圈发送数据
 * @author  唐远望
 * @version  1.0
 * @date   2025-08-08
 */
class MomentsSendUserListJobs 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 . '_MomentsSendUserListJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $corpid = $this->message_data['corpid'];
            $momentId = $this->message_data['moment_id'];
            $cursor = $this->message_data['cursor'];
            $limit = $this->message_data['limit'];

            // 同步发送成员列表
            $work                    = OpenWork::getWork($corpid);
            $result                 = $work->external_contact_moment->getTasks($momentId, $cursor, $limit);
            // 如果获取失败
            if (!$result) {
                Log::info('job_error', '获取客户朋友圈企业发表的列表失败',[$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]);
            }
            $ContactService = new ContactService();
            $task_list = $result['task_list'];
            $moment_user_list = MomentUser::where(['corpid' => $corpid, 'moment_id' => $momentId])->pluck('userid')->toarray();
            $insert_data = [];
            foreach ($task_list 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'];
                }
                if (empty($moment_user_list) || in_array($task['userid'], $moment_user_list)) {
                    $insert_data[] = [
                        'corpid' => $corpid,
                        'moment_id' => $momentId,
                        'userid' => $task['userid'],
                        'publish_status' => $task['publish_status'],
                        'insert_time'=>time(),
                    ];
                } 
                $CustomerList_message= [
                    'company_id' => $companyId,
                    'corpid' => $corpid,
                    'moment_id' => $momentId,
                    'userid' => $task['userid'],
                    'cursor' => '',
                    'limit' => 500,
                ];
                MomentsCustomerListJobs::dispatch($CustomerList_message);
                // MomentsCustomerListJobs::dispatchSync($CustomerList_message);
            }
            MomentUser::insert($insert_data);
            //删除任务记录
            $this->Records->delete();
            //如果存在下一页
            if (isset($result['next_cursor']) && $result['next_cursor'] != '') {
                $next_cursor = $result['next_cursor'];
                $this->message_data['cursor'] = $next_cursor;
                $this->message_data['limit'] = $limit;
                MomentsSendUserListJobs::dispatch($this->message_data);
                // MomentsSendUserListJobs::dispatchSync($this->message_data);
            }
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            // 如果错误信息里面包含字符UNIQUE_（数据唯一）则不写日志
            if (stripos($e->getMessage(), 'UNIQUE_') === false) {
                 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();
        }
    }
}
