<?php

namespace App\Jobs\OpenWork\External;

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

/**
 * 离职成员客户继承队列
 * @author 唐远望
 * @version 1.0
 * @date 2025-07-01
 */
class ResignationMembersJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $contacts_data;
    private ContactService $contact_service;
    private $Records;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $contacts_data)
    {
        //
        $this->contacts_data = $contacts_data;


        $this->contact_service = app(ContactService::class);
    }

    public function getCorpId()
    {
        return $this->contacts_data['corpid'] ?? null;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        try {
            $corpId = $this->contacts_data['corpid'];
            (new DbService())->getConnectionNameByCorpId($corpId);

            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $this->contacts_data['corpid'] . '_ResignationMembersJobs',
                'name' => static::class,
                'payload' => json_encode($this->contacts_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $ExternalAllocationRecordsModel = new ExternalAllocationRecordsModel();
            //查询客户信息
            $corpid = $this->contacts_data['corpid'];
            $externalUserId = $this->contacts_data['externalUserId'];
            $handoverUserId = $this->contacts_data['handoverUserId'];
            $takeoverUserId = $this->contacts_data['takeoverUserId'];
            $operator_userid = $this->contacts_data['operator_userid'];
            $work = OpenWork::getWork($corpid);
            $result = $work->external_contact->resignedTransferCustomer($externalUserId, $handoverUserId, $takeoverUserId);
            if (!$result || $result['errcode']) {
                Log::info('job_error', 'ResignationMembersJobs离职继承失败', ['data' => $this->contacts_data, 'error' => $result]);
            }
            $insert_data = [];
            foreach ($externalUserId as $key => $value) {
                $insert_data[] = [
                    'corpid' => $corpId,
                    'external_userid' => $value,
                    'original_followup_person' => $handoverUserId,
                    'current_followup_person' => $takeoverUserId,
                    'operator_userid' => $operator_userid,
                    'inherit_type' => '2', //1=在职继承2=离职继承
                    'insert_time' => time(),
                    'status' => '1'
                ];
            }
            //执行成功后，才写入数据库
            $ExternalAllocationRecordsModel->insert($insert_data);
            //延时更新离职继承状态
            $message_data = [
                'corpid' => $corpId,
                'inherit_type' => '2', //1=在职继承 2=离职继承
                'handover_userid' => $handoverUserId,
                'takeover_userid' => $takeoverUserId,
            ];
            UserInheritanceJobs::dispatch($message_data)->delay(86400); //延时1天执行
            //删除任务记录
            $this->Records->delete();
            // 成功处理...
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', 'ResignationMembersJobs任务队列执行失败', ['data' => $this->contacts_data, 'error' => $e->getMessage()]);
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', 'ResignationMembersJobs任务队列执行彻底失败', ['data' => $this->contacts_data, 'error' => $exception->getMessage()]);
        // 失败处理...
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
