<?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;
use App\Models\Company\CustomClockinRecord as CustomClockinRecordModel;

/**
 * 活动打标签任务队列
 * @author  唐远望
 * @version  1.0
 * @date   2025-10-23
 */
class ActivityTaskJobs 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();
            $CustomClockinRecordModel = new CustomClockinRecordModel();
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $companyId . '_NewLotteryDrawJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
             Log::info('job_error', '活动打标签任务测试日志', ['data' => $this->message_data]);
            $custom_uid = $this->message_data['custom_uid']; //客户ID
            $activity_type = $this->message_data['activity_type']; //活动类型1=拉新抽奖2=拉新活动3=签到4=积分抽奖5=下单抽奖6=答题活动（当task_type=1（活动类型）时必填）
            $activity_ids = $this->message_data['activity_ids']; //活动ID
            $check_behavior_type = $this->message_data['user_behavior_type']; //行为类型(拉新抽奖：1=中奖2=未中奖)、(拉新活动:行为默认为空)、(签到:1=连续签到2=累计签到)、(答题活动:1=中奖2=未中奖) 、(积分抽奖:1=中奖2=未中奖)
            $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 != '1') { //规则类型1=活动2=直播
                        continue;
                    }
                    if ($activity_type != $config_data['activity_type']) {
                        continue; //如果活动类型不匹配，则跳过
                    }
                    $config_tag_id = explode(',', $config_data['tag_ids']);
                    $user_behavior_type = $config_data['user_behavior_type'];
                    $activity_ids_arr = explode(',', $config_data['activity_ids']);
                    if (!in_array($activity_ids, $activity_ids_arr)) {
                        continue; //如果不在配置的拉新抽奖活动ID中，则跳过
                    }
                    //如果是签到活动，则判断签到天数
                    if ($config_data['activity_type'] == 3) {
                        $days = $config_data['days'];
                        $end_time = strtotime(date('Y-m-d', time()) . ' 23:59:59');
                        $start_time = strtotime(date('Y-m-d',  $end_time - $days * 86400) . ' 00:00:00');
                        //连续签到
                        if ($user_behavior_type == 1) {
                            //查询用户连续签到天数
                            $clockin_count = $CustomClockinRecordModel->where('custom_uid', $custom_uid)->where('insert_time', '>=', $start_time)->where('insert_time', '<=', $end_time)->count();
                            if ($clockin_count >= $days) {
                                $tag_id_data = array_merge($tag_id_data, $config_tag_id);
                            }
                        }
                        //累计签到
                        if ($user_behavior_type == 2) {
                            //查询用户累计签到天数
                            $clockin_count = $CustomClockinRecordModel->where('custom_uid', $custom_uid)->count();
                            if ($clockin_count >= $days) {
                                $tag_id_data = array_merge($tag_id_data, $config_tag_id);
                            }
                        }
                    } else if ($config_data['activity_type'] == 2) { //如果是拉新活动,不校验行为类型
                        $tag_id_data = array_merge($tag_id_data, $config_tag_id);
                    } else {
                        if ($user_behavior_type == $check_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();
        }
    }
}
