<?php

namespace App\Jobs\Company\Tag;

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\Company\Tag\TagTaskTemplates;
use App\Jobs\Company\Custom\TagJobs;

/**
 * 直播打标签任务队列
 * @author  唐远望
 * @version  1.0
 * @date   2025-10-22
 */
class LiveTaskJobs 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);
            $TagTaskTemplates = new TagTaskTemplates();
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $companyId . '_LiveTaskJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $custom_uid = $this->message_data['custom_uid']; //客户ID
            $live_id = $this->message_data['live_id']; //直播间ID
            $chect_behavior_type = $this->message_data['user_behavior_type']; //直播间行为类型
            $tag_id_data = []; //需要打的标签ID
            //查询所有已启用的打标签任务模板
            $all_data = $TagTaskTemplates->with(['task_rules'])->where('company_id', $companyId)->where('status', 0)->get()->toarray();
            if (empty($all_data)) {
                if ($this->Records) {
                    $this->Records->delete();
                }
                return true;
            }
            foreach ($all_data as $key => $value) {
                $task_rules = $value['task_rules'];
                if (empty($task_rules)) {
                    continue;
                }
                foreach ($task_rules as $key => $rule) {
                    $config_data= $rule['config_data'];
                    $task_type = $config_data['task_type'];
                    if($task_type !='2'){ //规则类型1=活动2=直播
                        continue;
                    }
                    $config_tag_id = explode(',', $config_data['tag_ids']);
                    $user_behavior_type = $config_data['user_behavior_type'];
                    $live_ids_arr = explode(',', $config_data['live_ids']);
                    if (!in_array($live_id, $live_ids_arr)) {
                        continue; //如果不在配置的直播间ID中，则跳过
                    }
                    if ($user_behavior_type == $chect_behavior_type) {
                        $tag_id_data = array_merge($tag_id_data, $config_tag_id);
                    }
                }
            }
            if (!empty($tag_id_data)) {
                $tag_message_data['company_id'] = $companyId;
                //移除重复的标签ID
                $tag_id_data = array_unique($tag_id_data);
                //执行打标签操作
                $tag_message_data['custom_list'] = [$custom_uid];
                $tag_message_data['tag_id_list'] = $tag_id_data;
                $tag_message_data['operation_type'] = 'add_tag';
                TagJobs::dispatch($tag_message_data);
                // TagJobs::dispatchSync($tag_message_data);
            }
            //删除任务记录
            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()]);
        }
    }


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