<?php

namespace App\Jobs\OpenWork\Company;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\OpenWork\Corp\AuthCorp as Model;
use App\Facades\Servers\Wechat\OpenWork;
use App\Facades\Servers\Logs\Log;

/**
 * 获取企业永久授权码
 * @author 唐远望
 * @version 1.0
 * @date   2025-05-06
 * 
 */
class PermanentCodeJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $message_data;

    /**
     * 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()
    {
        // 接收参数
        $message                                = $this->message_data;
        $auth_code                              = $message['AuthCode'];
        $Model                                  = new Model();
		// 获取配置
		$app				                    = OpenWork::getApp();
		// 传入临时授权码，获取永久授权码
		$permanentCode		                    = $app->corp->getPermanentByCode($auth_code);
		// 失败
		if( !$permanentCode )                   return json_send(['code' => 'error', 'msg' => '获取永久授权码失败']);
		// 如果没有获取到没有授权码
		if( isset($permanentCode['errcode']) )  return json_send(['code' => 'error', 'msg' => $permanentCode['errmsg'], 'data' => $permanentCode]);
        // 授权企业
        $corpid                                 = $permanentCode['auth_corp_info']['corpid'];
        // 保存永久授权码
        try {
            // 成功
            $data                               = ['corpid' => $permanentCode['auth_corp_info']['corpid'], 'corp_name' => $permanentCode['auth_corp_info']['corp_name'], 'permanent_code' => $permanentCode['permanent_code'], 'corpid' => $corpid, 'status' => 0];
            // 查询是否已经授权过
            $authId                             = $Model->query()->where([['corpid', '=', $data['corpid']]])->value('id');
            // 保存
            $result                             = $authId ? $Model->edit($authId, $data) : $Model->add($data);
            // 成功处理...
            return                              $result;
        } catch (\Exception $e) {
            Log::info('job_error', '永久授权码失败',['error' => $e->getMessage()]);
        }
    }

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