<?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\MomentsVisibleCustomerJobs;
use Illuminate\Support\Facades\DB;

/**
 * SCRM 客户朋友圈发表时选择的可见范围
 * @author  唐远望
 * @version  1.0
 * @date   2025-08-08
 */
class MomentsCustomerListJobs 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 . '_MomentsCustomerListJobs',
                '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'];
            $userId = $this->message_data['userid'];

            $work                    = OpenWork::getWork($corpid);
            $result                 = $work->external_contact_moment->getCustomers($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])->select(DB::raw("CONCAT(userid, '_', external_userid) as userid_external_userid"))->pluck('userid_external_userid')->toarray();
            $customer_list = $result['customer_list'];
            $insert_data = [];
            if (!empty($customer_list)) {
                foreach ($customer_list as $task) {
                    $userid_external_userid = $userId.'_'.$task['external_userid'];
                    if(!empty($external_user_list) && in_array($userid_external_userid,$external_user_list)){
                        continue ;
                    }
                    $insert_data[] = [
                        'corpid' => $corpid,
                        'moment_id' => $momentId,
                        'userid' => $userId,
                        'external_userid' => $task['external_userid'],
                        'insert_time' => time(),
                    ];
                }
                ExternalUser::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;
                MomentsCustomerListJobs::dispatch($this->message_data);
                // MomentsCustomerListJobs::dispatchSync($this->message_data);
            }else{
                //执行完毕查询成功送达的客户
                $VisibleCustomer_message= ['company_id' => $companyId,'corpid' => $corpid,'moment_id' => $momentId,'userid' => $userId,'cursor' => '','limit' => 3000];
                MomentsVisibleCustomerJobs::dispatch($VisibleCustomer_message);
                // MomentsVisibleCustomerJobs::dispatchSync($VisibleCustomer_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();
        }
    }
}
