<?php

namespace App\Jobs\OpenWork\External;

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\Facades\Servers\Logs\Log;
use App\Servers\DB\DbService;
use App\Models\OpenWork\job\Records;
use App\Models\OpenWork\External\FollowTag as FollowTagModel;
use App\Models\OpenWork\External\AuthCorp as AuthCorpmodel;

/**
 * 用户标签缓存更新任务队列
 * @author  唐远望
 * @version  1.0
 * @date   2025-10-29
 */
class UserTagCacheJobs 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 {
            $message_data = $this->message_data;
            if (array_key_exists('corpid', $message_data) && $message_data['corpid'] != '') {
                $corpid = $this->message_data['corpid'];
                (new DbService())->getConnectionNameByCorpId($corpid);

                // 创建任务记录
                $this->Records = Records::create([
                    'job_id' => $corpid . '_UserTagCacheJobs',
                    'name' => static::class,
                    'payload' => json_encode($this->message_data),
                    'status' => 'processing',
                    'started_at' => now()
                ]);
                $authcorp_data = $this->get_auth_info($corpid);
                if (!$authcorp_data) {
                    Log::info('job_error', '用户标签缓存更新队列执行失败', ['data' => $this->message_data, 'error' => '未找到该企业的绑定信息']);
                    return false;
                }
                $companyId = $authcorp_data['company_id'];
                $custom_uid = $this->message_data['custom_uid'];
                $external_userid = $this->message_data['external_userid'];
                $FollowTagModel = new FollowTagModel();
                $FollowTagModel->getExternalTagList($custom_uid, $companyId, $external_userid);
            }else if(array_key_exists('company_id', $message_data) && $message_data['company_id'] != ''){
                $company_id = $this->message_data['company_id'];
                (new DbService())->getConnectionNameByCompanyId($company_id);
                // 创建任务记录
                $this->Records = Records::create([
                    'job_id' => $company_id . '_UserTagCacheJobs',
                    'name' => static::class,
                    'payload' => json_encode($this->message_data),
                    'status' => 'processing',
                    'started_at' => now()
                ]);
                $custom_uid = $this->message_data['custom_uid'];
                $external_userid = $this->message_data['external_userid'];
                $FollowTagModel = new FollowTagModel();
                $FollowTagModel->getExternalTagList($custom_uid, $company_id, $external_userid);
            }
            //删除任务记录
            if ($this->Records) {
                $this->Records->delete();
            }
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', '用户标签缓存更新队列执行失败', ['data' => $this->message_data, 'error' => $e->getMessage()]);
        }
    }

    /**
     * 获取绑定商户信息
     * @author 唐远望
     * @version 1.0
     * @date 2025-10-29
     */
    public function get_auth_info($corpid)
    {
        if ($corpid == '') {
            return false;
        }
        $data = [];
        $AuthCorpmodel = new AuthCorpmodel();
        $authcorp = $AuthCorpmodel->where([['corpid', '=', $corpid]])->first();
        if (!$authcorp) {
            return false;
        }
        $data = [
            'company_id' => $authcorp->company_id,
            'corpid' => $authcorp->corpid,
        ];
        return $data;
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', '用户标签缓存更新队列完全执行失败', ['data' => $this->message_data, 'error' => $exception->getMessage()]);
        // 只有在Records存在时才删除
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
