<?php
namespace app\api\controller;
use liuniu\MiniProgramService;
use liuniu\UtilService;
use think\Cache;
use app\common\model\User;

class Routine
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ['*'];
    /**
     * 支付异步回调
     */
    public function notify()
    {
        ob_clean();
        MiniProgramService::handleNotify(input('cid',0));
    }
    /**
     * 小程序授权登录
     * @param Request $request
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function mp_auth(Request $request)
    {
        $cache_key = '';
        list($code, $post_cache_key, $login_type) = UtilService::postMore([
            ['code', ''],
            ['cache_key', ''],
            ['login_type', 2]
        ], $request, true);
        $session_key = Cache::get('eb_api_code_' . $post_cache_key);
        if (!$code && !$session_key)
            $this->error('授权失败,参数有误');
        if ($code && !$session_key) {
            try {
                $userInfoCong = MiniProgramService::getUserInfo($code);
                $session_key = $userInfoCong['session_key'];
                $cache_key = md5(time() . $code);
                Cache::set('eb_api_code_' . $cache_key, $session_key, 86400);
            } catch (\Exception $e) {
                $this->error('获取session_key失败,请检查您的配置!');
            }
        }

        $data = UtilService::postMore([
            ['spread_spid', 0],
            ['spread_code', ''],
            ['iv', ''],
            ['encryptedData', ''],
        ]);//获取前台传的code
        try {
            //解密获取用户信息
            $userInfo = MiniProgramService::encryptor($session_key, $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
        }
        if (!isset($userInfoCong['openid'])) return app('json')->fail('openid获取失败');
        if (!isset($userInfo['unionId'])) $userInfo['unionId'] = '';
        $userInfo['openId'] = $userInfoCong['openid'];
        $userInfo['spid'] = $data['spread_spid'];
        $userInfo['code'] = $data['spread_code'];
        $userInfo['session_key'] = $session_key;
        $userInfo['login_type'] = $login_type;
        $uid = User::setRoutineUser($userInfo);
        $user = User::where('uid', $uid)->find();
        $this->auth->direct($user['id']);
        // 设置推广关系
        User::setSpread(intval($data['spread_spid']), $user->id);
        return $this->success('登录成功', $this->auth->getUserinfo());
    }

}