<?php

namespace Modules\Channel\Services\WechatOpenPlatform;

use EasyWeChat\Factory;
use EasyWeChat\OpenPlatform\Application;
use EasyWeChat\OpenPlatform\Message;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Modules\Channel\Models\WechatAuthorizationInfo;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;
use Modules\Common\Services\BaseService;

class WechatOpenPlatformService extends BaseService
{
    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
        ];
        $config  = array_merge($config, config('easywechat'));
        $app = Factory::openPlatform($config);
        $app->rebind('cache', Cache::store('redis'));
        return $app;
    }

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

    /**
     *  获取公众号的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,
        ])->first();
    }

    /**
     *  获取公众号的refreshToken
     * name:getAppInfoById
     * @param $id 公众号授权id
     * @return Model|Builder|object|null
     */
    public static function getAppInfoById($id)
    {
        $info =   DB::table('wechat_authorization_infos')
            ->where([
                'id' =>  $id,
                'is_enabled'  =>  1,
            ])->first();
        if (is_empty($info)){
            self::throwErrMsg("公众号不存在或已取消授权");
        }
        return  $info;

    }
}