<?php

namespace Modules\Channel\Services\WechatOpenPlatform;

use EasyWeChat\OpenPlatform\Application;
use EasyWeChat\OpenPlatform\Message;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;

class WechatOpenPlatformService
{
    public static function getComponentInfoByCompanyUid($companyUid) {
        $componentInfo = DB::table('wechat_open_platform_infos')
            ->where([
                'company_uid' => $companyUid,
                'is_enabled' => 1,
            ])->orderBy('id', 'desc')
            ->first();
        if(!$componentInfo) {
            CommonBusinessException::throwError(Errors::OPENPLATFORM_COMPANY_INFO_NOT_EXISTS);
        }
        return $componentInfo;
    }

    public static function getComponentInfoByAppid($componentAppid) {
        $componentInfo =  DB::table('wechat_open_platform_infos')
            ->where([
                'app_id' => $componentAppid,
                'is_enabled' => 1,
            ])->orderBy('id', 'desc')
            ->first();
        if(!$componentInfo) {
            CommonBusinessException::throwError(Errors::OPENPLATFORM_COMPANY_INFO_NOT_EXISTS);
        }
        return $componentInfo;
    }

    /**
     * 构造app
     * @param $componentInfo
     * @return Application
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public static function buildApplication($componentInfo) {
        $config = [
            'app_id' => $componentInfo->app_id, // 开放平台账号的 appid
            'secret' => $componentInfo->secret,   // 开放平台账号的 secret
            'token' => $componentInfo->token,  // 开放平台账号的 token
            'aes_key' => $componentInfo->aes_key,   // 明文模式请勿填写 EncodingAESKey
            'http' => [
                'throw'  => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
                'retry' => true, // 使用默认重试配置
            ],
        ];
        $app = new Application($config);
        $app->setCache(Cache::store('redis'));
        return $app;
    }

    /**
     * 取消授权
     * @param Message $message
     */
    public static function handleUnauthorized($message) {
        $component_appid = $message['AppId'];
        $authorizer_appid = $message['AuthorizerAppid'];
        DB::table('wechat_authorization_infos')
            ->where([
                'component_appid' => $component_appid,
                'authorizer_appid' => $authorizer_appid,
            ])->delete();
    }

    /**
     *  获取公众号的refreshToken
     * name: getRefreshToken
     * @param $authorizer_appid
     * @param $component_appid
     * date 2023/07/07 10:16
     */
    public static function getRefreshToken($authorizer_appid, $component_appid)
    {
        return  DB::table('wechat_authorization_infos')
        ->where([
            'component_appid' => $component_appid,
            'authorizer_appid' => $authorizer_appid,
            'is_enabled'  =>  1,
        ])->value('authorizer_refresh_token');
    }
}
