<?php

namespace App\Jobs\OpenWork\Company;

use App\Servers\DB\DbService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Facades\Servers\Wechat\OpenWork;
use App\Models\OpenWork\Corp\AuthCorp as AuthCorpModel;
use App\Servers\OpenWork\Corp\AuthCorp as AuthCorpService;
use App\Facades\Servers\Logs\Log;
use App\Models\OpenWork\job\Records;

/**
 * 更新企业授权信息
 * @author 唐远望
 * @version 1.0
 * @date   2025-04-21
 * 
 */

class AuthCorpJobs 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;
    }

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        try {
            $corpId = $this->message_data['authCorpId'];
            (new DbService())->getConnectionNameByCorpId($corpId);
            // 创建任务记录

            $this->Records = Records::create([
                'job_id' => $this->message_data['corpid'] . '_AuthCorpJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);

            $this->update_authcorp_info($this->message_data['corpid']);
            //删除任务记录

            $this->Records->delete();

            // 成功处理...
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', '更新企业授权信息失败',['error' => $e->getMessage()]);
        }
    }


    /**
     * 更新企业授权信息
     * @author 唐远望
     * @version 1.0
     * @date   2025-04-21
     * 
     */

    private function update_authcorp_info($authCorpId)
    {

        $permanent_code                = (new AuthCorpModel())->query()->where([['corpid', '=', $authCorpId]])->value('permanent_code');
        if (!$permanent_code) {
            return json_send(['code' => 'error', 'msg' => '获取永久授权码失败']);
        }
        // 获取配置
        $app                = OpenWork::getApp();
        // 传入临时授权码，获取永久授权码
        $requert_data        = $app->corp->getAuthorization($authCorpId, $permanent_code);
        $result = (new AuthCorpService())->update_corp_authcorp($requert_data);
        // 如果获取结果失败
        if (!$result)  return json_send(['code' => 'error', 'msg' => '更新失败']);
        // 错误提示
        if (isset($result['errcode'])) return json_send(['code' => 'error', 'msg' => $result['errmsg']]);
        // 输出结果
        return          json_send(['code' => 'success', 'msg' => '更新成功', 'data' => $result]);
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', 'AuthCorpJobs彻底失败', ['data'=>$this->message_data,'error' => $exception->getMessage()]);
        // 失败处理...
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
