<?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\ExternalUser;
use App\Jobs\OpenWork\Statistics\MomentsCustomerInteractionJobs;


/**
 * SCRM 企微朋友圈发送成功客户列表
 * @author  唐远望
 * @version  1.0
 * @date   2025-08-08
 */
class MomentsVisibleCustomerJobs 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 . '_MomentsVisibleCustomerJobs',
                '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'];
            $userid = $this->message_data['userid'];
            $cursor = $this->message_data['cursor'];
            $limit = $this->message_data['limit'];
            // 同步可见客户列表
            $work                    = OpenWork::getWork($corpid);
            $result                 = $work->external_contact_moment->getSendResult($momentId, $userid, $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]);
            }
            $external_user_list = ExternalUser::where(['corpid' => $corpid, 'moment_id' => $momentId])->pluck('external_userid')->toarray();
            $customer_list = $result['customer_list'];
            if (!empty($customer_list)) {
                foreach ($customer_list as $task) {
                    if (!empty($external_user_list) && in_array($task['external_userid'], $external_user_list)) {
                        ExternalUser::where(['corpid' => $corpid, 'moment_id' => $momentId, 'external_userid' => $task['external_userid']])->update(['is_deliver' => 2]);
                    }
                }
            }
            //删除任务记录
            $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;
                MomentsVisibleCustomerJobs::dispatch($this->message_data);
            } else {
                //写入成功后执行互动数据更新(最后一页时)
                $CustomerInteraction_message = ['corpid' => $corpid, 'moment_id' => $momentId, 'userid' => $userid, 'company_id' => $companyId];
                MomentsCustomerInteractionJobs::dispatch($CustomerInteraction_message);
                // MomentsCustomerInteractionJobs::dispatchSync($CustomerInteraction_message);
            }
        } 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();
        }
    }
}
