<?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\Group\Chat as ChatModel;
use App\Models\OpenWork\Group\AllocationRecords as GroupAllocationRecordsModel;
use App\Servers\OpenWork\External\ContactService;


/**
 * 客户群在职继承队列
 * @author 唐远望
 * @version 1.0
 * @date 2025-11-18 
 */
class GroupInheritanceJobs 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 {
            $corpId = $this->message_data['corpid'];
            (new DbService())->getConnectionNameByCorpId($corpId);
            $chat_id_list_array = $this->message_data['chat_id_list'];
            $new_owner = $this->message_data['new_owner'];
            $operator_userid = $this->message_data['operator_userid'];
            $inherit_type = $this->message_data['inherit_type'];
            if ($inherit_type == 1) {
                //群在职继承
                $this->on_the_job($corpId, $chat_id_list_array, $new_owner, $operator_userid);
            }
            if ($inherit_type == 2) {
                //群离职继承
                $this->off_the_job($corpId, $chat_id_list_array, $new_owner, $operator_userid);
            }
            return true;
            // 成功处理...
        } catch (\Exception $e) {
            Log::info('job_error', 'GroupInheritanceJobs任务队列处理失败', ['data' => $this->message_data, 'error' => $e->getMessage()]);
        }
    }

    /**
     * 在职继承队列任务处理
     * @author 唐远望
     * @version 1.0
     * @date 2025-11-18 
     */
    public function on_the_job($corpId, $chat_id_list_array, $new_owner, $operator_userid)
    {
        $ChatModel = new ChatModel();
        $GroupAllocationRecordsModel = new GroupAllocationRecordsModel();
        $ContactService = new ContactService();
        $insert_data = [];
        //筛选正常的群
        $chat_data_list = $ChatModel->where(['corpid' => $corpId, 'status' => '0'])->whereIn('chat_id', $chat_id_list_array)->select(['chat_id', 'owner'])->get()->toArray();
        if (empty($chat_data_list)) {
            Log::info('job_error', 'GroupInheritanceJobs任务队列处理失败,群在职继承列表为空', ['data' => $this->message_data]);
            return true;
        }
        $chat_id_list = array_column($chat_data_list, 'chat_id');
        foreach ($chat_data_list as $key => $value) {
            $insert_data[] = [
                'corpid' => $corpId,
                'chat_id' => $value['chat_id'],
                'original_group_leader' => $value['owner'],
                'current_group_leader' => $new_owner,
                'operator_userid' => $operator_userid,
                'inherit_type' => '1', //1=在职继承2=离职继承
                'insert_time' => time(),
            ];
        }
        $result_status = $GroupAllocationRecordsModel->insert($insert_data);
        if (!$result_status) {
            Log::info('job_error', 'GroupInheritanceJobs任务队列处理失败,群在职继承记录插入失败', ['data' => $this->message_data]);
            return true;
        }
        $result = $ContactService->assignResignedCustomerGroups($corpId, $chat_id_list, $new_owner);
        // 如果获取结果失败
        if (!$result) {
            Log::info('job_error', 'GroupInheritanceJobs任务队列处理失败,群在职继承失败', ['data' => $this->message_data]);
            return true;
        }
        // 错误提示
        if ($result['errcode']) {
            Log::info('job_error', 'GroupInheritanceJobs任务队列处理失败,群在职继承失败', ['data' => $this->message_data, 'error' => $result['errmsg']]);
            return true;
        }
        //处理失败或成功的数据
        if (!empty($result['failed_chat_list'])) {
            $failed_chat_list = array_column($result['failed_chat_list'], 'chat_id');
            $GroupAllocationRecordsModel->whereIn('chat_id', $failed_chat_list)->update(['status' => 3, 'update_time' => time()]);
            //筛选不在失败列表的群
            $chat_id_list = array_diff($chat_id_list, $failed_chat_list);
            $GroupAllocationRecordsModel->whereIn('chat_id', $chat_id_list)->update(['status' => 2, 'update_time' => time()]);
        } else {
            $GroupAllocationRecordsModel->whereIn('chat_id', $chat_id_list)->update(['status' => 2, 'update_time' => time()]);
        }
        return true;
    }

    /**
     * 离职继承队列任务处理
     * @author 唐远望
     * @version 1.0
     * @date 2025-11-18 
     */
    public function off_the_job($corpId, $chat_id_list_array, $new_owner, $operator_userid)
    {
        $ChatModel = new ChatModel();
        $GroupAllocationRecordsModel = new GroupAllocationRecordsModel();
        $ContactService = new ContactService();
        $insert_data = [];
        //筛选正常的群
        $chat_data_list = $ChatModel->where(['corpid' => $corpId, 'status' => '0'])->whereIn('chat_id', $chat_id_list_array)->select(['chat_id', 'owner'])->get()->toArray();
        if (empty($chat_data_list)) {
            Log::info('job_error', 'GroupInheritanceJobs任务队列处理失败,群离职继承列表为空', ['data' => $this->message_data]);
            return true;
        }
        $chat_id_list = array_column($chat_data_list, 'chat_id');
        foreach ($chat_data_list as $key => $value) {
            $insert_data[] = [
                'corpid' => $corpId,
                'chat_id' => $value['chat_id'],
                'original_group_leader' => $value['owner'],
                'current_group_leader' => $new_owner,
                'operator_userid' => $operator_userid,
                'inherit_type' => '2', //1=在职继承2=离职继承
                'insert_time' => time(),
            ];
        }
        $result_status = $GroupAllocationRecordsModel->insert($insert_data);
        if (!$result_status) {
            Log::info('job_error', 'GroupInheritanceJobs任务队列处理失败,群离职继承记录插入失败', ['data' => $this->message_data]);
            return true;
        }
        $result = $ContactService->assignResignedCustomerGroups($corpId, $chat_id_list, $new_owner);
        // 如果获取结果失败
        if (!$result) {
            Log::info('job_error', 'GroupInheritanceJobs任务队列处理失败,群离职继承失败', ['data' => $this->message_data]);
            return true;
        }
        // 错误提示
        if ($result['errcode']) {
            Log::info('job_error', 'GroupInheritanceJobs任务队列处理失败,群离职继承失败', ['data' => $this->message_data, 'error' => $result['errmsg']]);
            return true;
        }
        //处理失败或成功的数据
        if (!empty($result['failed_chat_list'])) {
            $failed_chat_list = array_column($result['failed_chat_list'], 'chat_id');
            $GroupAllocationRecordsModel->whereIn('chat_id', $failed_chat_list)->update(['status' => 3, 'update_time' => time()]);
            //筛选不在失败列表的群
            $chat_id_list = array_diff($chat_id_list, $failed_chat_list);
            $GroupAllocationRecordsModel->whereIn('chat_id', $chat_id_list)->update(['status' => 2, 'update_time' => time()]);
        } else {
            $GroupAllocationRecordsModel->whereIn('chat_id', $chat_id_list)->update(['status' => 2, 'update_time' => time()]);
        }
        return true;
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', 'GroupInheritanceJobs任务队列彻底失败', ['data' => $this->message_data, 'error' => $exception->getMessage()]);
    }
}
