<?php
/**
 * Created by PhpStorm.
 * Author: NODELOG
 * DateTime: 2017/3/8 14:30
 * Description:
 */

namespace api\modules\v1\controllers;


use api\common\behaviors\QueryParamAuth;
use api\common\controllers\Controller;
use api\common\models\User;
use api\modules\v1\models\LoginForm;
use common\enums\CodeEnum;
use common\helpers\wx\Application;
use common\helpers\wx\mini\PhoneNumber;
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\ServerErrorHttpException;


class AuthController extends Controller
{
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => QueryParamAuth::className(),
                'tokenParam' => 'token',
                'optional' => ['login', 'login-by-id']
            ]
        ]);
    }

    /**
     * @api {post} /v1/auth/login 微信登录
     * @apiGroup 授权
     * @apiVersion 1.0.0
     *
     * @apiDescription 微信小程序微信授权自动注册登录
     *
     * @apiSuccess {Number} errcode    状态码，0：请求成功
     * @apiSuccess {String} errmsg   提示信息
     * @apiSuccess {Object} data    用户信息
     * @apiSuccess {String} token    授权访问token
     *
     * @apiError {Number} errcode    状态码，500：请求失败
     * @apiError {String} errmsg   提示信息
     *
     * @apiSuccessExample {json} 成功响应:
     * {"errcode":0,"errmsg":"ok","data":{},"token":''}
     *
     * @apiErrorExample {json} 失败响应:
     * {"errcode":500,"errmsg":"请求失败"}
     *
     * @author nodelog
     */
    public function actionLogin()
    {
        $model = new LoginForm();
        $model->load(request()->post(), '');
        if ($model->login()) {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
//            if (empty($user->token) || $user->expired_at < time()) {
                $user->generateAccessToken(request()->headers->get('token'));
                $user->save(false);
//            }
            return ['data' => User::findOne($user->id)];
        } else {
            return ['errcode' => CodeEnum::CODE_ERROR, 'errmsg' => '登录失败' . current($model->getErrors())[0]];
        }
    }


    /**
     * @api {post} /v1/auth/logout 退出登录
     * @apiGroup 授权
     * @apiName logout
     * @apiVersion 1.0.0
     *
     * @apiDescription 清除登录状态
     *
     * @apiParam {Integer} token 授权访问token.
     *
     * @apiSuccess {Number} errcode    状态码，0：请求成功
     * @apiSuccess {String} errmsg   提示信息
     *
     * @apiError {Number} errcode    状态码，500：请求失败
     * @apiError {String} errmsg   提示信息
     *
     * @apiSuccessExample {json} 成功响应:
     * {"errcode":0,"errmsg":"ok"}
     *
     * @apiErrorExample {json} 失败响应:
     * {"errcode":500,"errmsg":"请求失败"}
     *
     */
    public function actionLogout()
    {
        if (\Yii::$app->user->logout()) {
            return [];
        }
    }
}