<?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\Servers\DB\DbService;
use App\Models\OpenWork\job\Records;
use App\Facades\Servers\Logs\Log;
use App\Servers\OpenWork\External\ContactService;
use App\Models\OpenWork\External\AllocationRecords as AllocationRecordsModel;
use Illuminate\Support\Facades\Cache;


/**
 * 继承状态同步任务（在职继承&离职继承）
 * @author  唐远望
 * @version  1.0
 * @date   2025-11-14
 */
class UserInheritanceJobs 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);
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $corpId . '_UserInheritanceJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $handoveruserId = $this->message_data['handover_userid'];
            $takeoveruserId = $this->message_data['takeover_userid'];
            $inherit_type = $this->message_data['inherit_type'];
            $execution_count = isset($this->message_data['execution_count'])? $this->message_data['execution_count'] : 1;
            $cursor = isset($this->message_data['cursor'])? $this->message_data['cursor'] : '';
            if($inherit_type == '1'){
                $this->queryTransferStatus($corpId, $handoveruserId, $takeoveruserId,$cursor,$execution_count);
            }
            if($inherit_type == '2'){
                $this->queryTransferStatus_resigned($corpId, $handoveruserId, $takeoveruserId,$cursor,$execution_count);
            }
            //删除任务记录
            $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-11-14
     * @param     $authCorpId 授权方企业微信id
     * @param     $handoveruserId 原添加成员的userid
     * @param     $takeoveruserId 接替成员的userid
     * @return    array
     * 
     */
    private function queryTransferStatus($authCorpId, $handoveruserId, $takeoveruserId, $cursor = '',$execution_count = 1)
    {
        $AllocationRecordsModel = new AllocationRecordsModel();
        // 数据结果
        $result = (new ContactService())->transferResultLine($authCorpId, $handoveruserId, $takeoveruserId, $cursor);
        // 如果获取结果失败
        if (!$result) return true;
        // 错误提示
        if ($result['errcode']){
            if (strpos($result['errmsg'], '45035') || strpos($result['errmsg'], '45033')) { //并发操作冲突|接口并发调用超过限制
                if ($execution_count > 2) {
                    Log::info('job_error', '在职继承状态任务队列查询失败,重试了3次仍然失败', ['data' => $this->message_data, 'error' => $result]);
                    return true;
                }
                $message_data = $this->message_data;
                $message_data['execution_count'] = $execution_count + 1;
                $seconds = 5 * $message_data['execution_count']; //每次延长5秒
                $this->dispatch($message_data)->delay($seconds);
                return true;
            } else {
                Log::info('job_error', '在职继承状态任务队列查询错误', ['data' => $this->message_data, 'error' => $result]);
                return true;
            }
        }
        if(!isset($result['customer']) || empty($result['customer'])){
            Log::info('job_error', '在职继承状态任务队列查询错误,找不到转接客户信息', ['data' => $this->message_data, 'error' => $result]);
            return true;
        }
        // 列表结果
        $customer_list = $result['customer'];
        $status_external_userid_datas =[];
        foreach ($customer_list as $key => $value) {
            $status = $value['status']; //接替状态， 1-接替完毕 2-等待接替 3-客户拒绝 4-接替成员客户达到上限
            switch ($value['status']) {
                case '1':
                    $status = '2'; //转移状态1=进行中2=成功3=失败
                    break;
                case '2':
                    $status = '1'; //转移状态1=进行中2=成功3=失败
                    # code...
                    break;
                case '3':
                    $status = '3'; //转移状态1=进行中2=成功3=失败
                    # code...
                    break;
                case '4':
                    $status = '4'; //转移状态1=进行中2=成功3=失败
                    break;
            }
            //状态分组
            $status_external_userid_datas[$status]['external_userid'][] = $value['external_userid'];
            $status_external_userid_datas[$status]['wecom_status'] = $value['status'];
        }
        foreach ($status_external_userid_datas as $status_key => $status_data) {
            $AllocationRecordsModel->query()
                ->whereIn('external_userid', $status_data['external_userid'])
                ->where(['original_followup_person' => $handoveruserId, 'current_followup_person' => $takeoveruserId, 'corpid' => $authCorpId])
                ->update(['status' => $status_key, 'wecom_status' => $status_data['wecom_status'],'update_time'=> time()]);
        }
        //校验是否存在下一页
        if(isset($result['next_cursor']) && $result['next_cursor'] != ''){
            $next_cursor = $result['next_cursor'];
            $message_data = $this->message_data;
            $message_data['cursor'] = $next_cursor;
            $message_data['execution_count'] = 1;
            $this->dispatch($message_data);
        }
        return true;
    }

    /**
     * 查询客户接替状态-离职继承
     * @author    唐远望
     * @version   1.0
     * @date      2025-11-14
     * @param     $authCorpId 授权方企业微信id
     * @param     $handoveruserId 原添加成员的userid
     * @param     $takeoveruserId 接替成员的userid
     * @return    array
     * 
     */
    private function queryTransferStatus_resigned($authCorpId, $handoveruserId, $takeoveruserId, $cursor = '',$execution_count = 1)
    {
        $AllocationRecordsModel = new AllocationRecordsModel();
        // 数据结果
        $result = (new ContactService())->transferResultLine_resigned($authCorpId, $handoveruserId, $takeoveruserId, $cursor);
        // 如果获取结果失败
        if (!$result) return true;
        // 错误提示
        if ($result['errcode']){
            if (strpos($result['errmsg'], '45035') || strpos($result['errmsg'], '45033')) { //并发操作冲突|接口并发调用超过限制
                if ($execution_count > 2) {
                    Log::info('job_error', '离职继承状态任务队列查询失败,重试了3次仍然失败', ['data' => $this->message_data, 'error' => $result]);
                    return true;
                }
                $message_data = $this->message_data;
                $message_data['execution_count'] = $execution_count + 1;
                $seconds = 5 * $message_data['execution_count']; //每次延长5秒
                $this->dispatch($message_data)->delay($seconds);
                return true;
            } else {
                Log::info('job_error', '离职继承状态任务队列查询错误', ['data' => $this->message_data, 'error' => $result]);
                return true;
            }
            
        }
        // 列表结果
        $customer_list = $result['customer'];
        if (empty($customer_list)) {
            return true;
        }
        $status_external_userid_datas =[];
        foreach ($customer_list as $key => $value) {
            $status = $value['status']; //接替状态， 1-接替完毕 2-等待接替 3-客户拒绝 4-接替成员客户达到上限
            switch ($value['status']) {
                case '1':
                    $status = '2'; //转移状态1=进行中2=成功3=失败
                    break;
                case '2':
                    $status = '1'; //转移状态1=进行中2=成功3=失败
                    # code...
                    break;
                case '3':
                    $status = '3'; //转移状态1=进行中2=成功3=失败
                    # code...
                    break;
                case '4':
                    $status = '4'; //转移状态1=进行中2=成功3=失败
                    break;
            }
            //状态分组
            $status_external_userid_datas[$status]['external_userid'][] = $value['external_userid'];
            $status_external_userid_datas[$status]['wecom_status'] = $value['status'];
        }
        foreach ($status_external_userid_datas as $status_key => $status_data) {
            $AllocationRecordsModel->query()
                ->whereIn('external_userid', $status_data['external_userid'])
                ->where(['original_followup_person' => $handoveruserId, 'current_followup_person' => $takeoveruserId, 'corpid' => $authCorpId])
                ->update(['status' => $status_key, 'wecom_status' => $status_data['wecom_status']]);
        }
        //校验是否存在下一页
        if(isset($result['next_cursor']) && $result['next_cursor'] != ''){
            $next_cursor = $result['next_cursor'];
            $message_data = $this->message_data;
            $message_data['cursor'] = $next_cursor;
            $message_data['execution_count'] = 1;
            $this->dispatch($message_data);
        }
        return true;
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', '继承查询更新任务完全失败', ['data' => $this->message_data, 'error' => $exception->getMessage()]);

        $this->Records->delete();
    }
}
