<?php

namespace App\Modules\Mini\Services;

use App\Base\BaseService;
use App\Exceptions\ClientException;
use App\Models\User\User;
use EasyWeChat\Kernel\HttpClient\Response;
use EasyWeChat\MiniApp\Application;
use Illuminate\Support\Arr;

class WechatService extends BaseService
{
    protected $config;

    /**
     * @param $config
     */
    public function __construct()
    {
        $this->config = config('account.wechat.mini_app');
    }

    public function decryptUserInfo($params)
    {
        $data = $this->wechat()->getUtils()->decryptSession($params['session_key'], $params['iv'], $params['encrypted_data']);
//{
//    "openId": "oGZUI0egBJY1zhBYw2KhdUfwVJJE",
//    "nickName": "Band",
//    "gender": 1,
//    "language": "zh_CN",
//    "city": "Guangzhou",
//    "province": "Guangdong",
//    "country": "CN",
//    "avatarUrl": "http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0",
//    "unionId": "ocMvos6NjeKLIBqg5Mr9QjxrP1FA",
//    "watermark": {
//        "timestamp": 1477314187,
//        "appid": "wx4f4bc4dec97d474b"
//    }
//}
        /** @var User $user */
        $user = \Auth::user();
        if (is_null($user)) {
            throw new ClientException("need Authentication");
        }
        $user->name = $data['nickName'];
        $user->extra = array_merge($user->extra, [
            "wechat" => $data,
        ]);
        $user->save();
    }

    public function decryptPhone($params)
    {
        $data = $this->wechat()->getUtils()->decryptSession($params['session_key'], $params['iv'], $params['encrypted_data']);
        logger()->info("decryptPhone", $data);
        /** @var User $user */
        $user = \Auth::user();
        if (is_null($user)) {
            throw new ClientException("need Authentication");
        }
        if ($phone = Arr::get($data, "purePhoneNumber")) {
            $user->phone = $phone;
            $user->save();
        }
    }

    /**
     * @return Application
     */
    private function wechat()
    {
        return new Application($this->config);
    }

    /**
     * @see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
     */
    public function codeToSession($code)
    {

        $options = [
            'query' => [
                'appid' => $this->config['app_id'],
                'js_code' => $code,
                'secret' => $this->config['secret'],
                "grant_type" => "authorization_code",
            ],
        ];
        return $this->render($this->wechat()->getClient()->get("/sns/jscode2session", $options));
    }

    /**
     * @param Response $resp
     */
    private function render($resp)
    {
        if ($resp->isFailed()) {
            logger()->error("wechat render failer", [
                "resp" => $resp->getContent(),
            ]);
            throw new ClientException("调用微信接口出错,请稍后再试");
        }

        return json_decode($resp->getContent(), true);
    }
}