<?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;

/**
 * SCRM 企微朋友圈客户互动用户
 * @author  唐远望
 * @version  1.0
 * @date   2025-08-08
 */
class MomentsCustomerInteractionJobs 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()
            ]);
            $corpid = $this->message_data['corpid'];
            $momentId = $this->message_data['moment_id'];
            $userId = $this->message_data['userid'];
            // 同步客户互动数据
            $work                    = OpenWork::getWork($corpid);
            $result                 = $work->external_contact_moment->getComments($momentId, $userId);
            // 如果获取失败
            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]);
            }
            // 保存客户互动数据
            $comment_list = $result['comment_list'];
            if (!empty($comment_list)) {
                foreach ($comment_list as $task) {
                    $where = ['external_userid' => $task['external_userid'], 'moment_id' => $momentId, 'corpid' => $corpid];
                    ExternalUser::where($where)->update(['is_comment' => '2', 'comment_time' => $task['create_time']]);
                }
            }
            $like_list = $result['like_list'];
            if (!empty($like_list)) {
                foreach ($like_list as $task) {
                    $where = ['external_userid' => $task['external_userid'], 'moment_id' => $momentId, 'corpid' => $corpid];
                    ExternalUser::where($where)->update(['is_like' => '2', 'like_time' => $task['create_time']]);
                }
            }
            //删除任务记录
            $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();
        }
    }
}
