<?php
/**
 * Created by IntelliJ IDEA.
 * User: solu
 * Date: 2019/3/7
 * Time: 11:07 AM
 */
class AuthController extends BaseController {

    protected $ajaxLoginActions = [
        'getAccessToken',
    ];

    public function __construct()
    {
        parent::__construct(true);
    }


    /**
     * 授权页面
     * @author solu
     * @param $args
     */
    public function actionLogin($args) {
        $this->tpl->display('');
    }

    /**
     * 获取access_token
     * @author solu
     * @param $args
     * @return array
     */
    public function actionGetAccessToken($args) {
        $rules = [
            'app_id' => ['string', 'desc' => 'appid'],
            'ts' => ['int', 'desc' => '发起请求时间戳'],
            'sign' => ['string', 'desc' => '签名'],
        ];
        Param::checkParam2($rules, $args);

        $user_id = (int)User::getUserId();

        try {
            (new AppInfo())->verify($args['app_id'], $args['ts'], $args['sign']);
        } catch (Exception $e) {
            Response::error($e->getCode(), $e->getMessage());
        }

        $access_token = AppInfo::genAccessToken($args['app_id'], $user_id);
        $ttl = AppInfo::ACCESS_TOKEN_TTL;

        return compact('user_id', 'access_token', 'ttl');
    }

    /**
     * 校验access_token有效性
     * @author solu
     * @param $args
     * @return array
     */
    public function actionCheckAccessToken($args) {
        $rules = [
            'app_id' => ['string', 'desc' => 'appid'],
            'user_id' => ['int', 'desc' => '用户id'],
            'access_token' => ['string', 'desc' => 'access_token'],
        ];
        Param::checkParam2($rules, $args);

        $valid = AppInfo::checkAccessToken($args['app_id'], $args['user_id'], $args['access_token']);
        return compact('valid');
    }

    /**
     * 用户信息
     * @author solu
     * @param $args
     * @return array
     */
    public function actionGetUserInfo($args) {
        $rules = [
            'app_id' => ['string', 'desc' => 'appid'],
            'user_id' => ['int', 'desc' => '用户id'],
            'access_token' => ['string', 'desc' => 'access_token'],
        ];
        Param::checkParam2($rules, $args);

        if (!AppInfo::checkAccessToken($args['app_id'], $args['user_id'], $args['access_token'])) {
            Response::error(CODE_PARAM_ERROR, 'access token timeout');
        }

        return User::getUserInfo($args['user_id'], 0, 0);
    }

//    public function actionTest($args) {
//        $appId = 'XJQ2Qc24bMJnAZWg9p43JUsH';
//        $secret = 'uQhF3M8t3MkNKG2g';
//
//        $ts = time();
//        $sign = AppInfo::doSign($appId, $secret, $ts);
//
//        return compact('appId', 'ts', 'sign');
//    }
}