<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/2/24
 * Time: 下午12:48
 */
namespace frontendApi\modules\v1\controllers;

use common\helpers\Cache;
use common\helpers\Form;
use common\models\forms\UserForm;
use common\models\UserInfo;
use common\models\UserToken;
use frontendApi\modules\v1\components\UserAuth;
use frontendApi\modules\v1\models\LoginForm;
use Yii;
use frontendApi\modules\v1\models\User;
use yii\web\HttpException;

class OauthController extends BaseController
{
    public $modelClass = User::class;

    public function actionMenu(){
        $menu = require Yii::getAlias('@frontendApi/config/menu.php');
        return $this->_childMenu($menu);
    }

    private function _childMenu($parentArray){
        $menuResult = [];
        foreach($parentArray as $key => $parentMenu){
            // 菜单是否显示
            if(isset($parentMenu['show']) && (!$parentMenu['show'] || !$this->_allowDec($parentMenu))){
                continue;
            }
            // 子菜单同样设置
            if(isset($parentMenu['child']) && !empty($parentMenu['child'])){
                $parentMenu['child'] = $this->_childMenu($parentMenu['child']);
            }
            $menuResult[] = $parentMenu;
        }
        return $menuResult;
    }

    private function _allowDec($item){
        if(!isset($item['allow'])){
            return true;
        }
        $isDecReg = Cache::getSystemConfig()['isDecReg']['VALUE'];
        if(!$isDecReg) return true;

        if(!\Yii::$app->user->id){
            return true;
        }
        $isDec = User::getEnCodeInfo(\Yii::$app->user->id)['IS_DEC'];
        if($isDec==1 && $item['allow']=='declarer'){
            return true;
        }

        return false;
    }

    /**
     * 个人信息
     * @return mixed
     * @throws HttpException
     */
    public function actionInfo(){
        User::updateBaseInfoToRedis(\Yii::$app->user->id);
        return static::notice(User::getEnCodeInfo(\Yii::$app->user->id));
    }

    /**
     * 登录是否需要验证码
     * @return mixed
     * @throws HttpException
     */
    public function actionIsLoginVerify() {
        $userName = Yii::$app->request->post('userName');
        $model = new LoginForm(
            [
                'userName' =>$userName
            ]
        );
        $isLoginVerify = $model->isLoginVerify();

        return static::notice($isLoginVerify ? 1 : 0);
    }

    /**
     * 登录
     * @return mixed
     * @throws HttpException
     * @throws \yii\base\Exception
     */
    public function actionLogin() {
        $userName = preg_replace("/[^A-Z0-9]/", "", Yii::$app->request->post('userName'));
        $posts = Yii::$app->request->post();
        $posts['userName'] = $userName;
        $model = new LoginForm(
            [
                'userName' =>$userName
            ]
        );
        if ( $model->isLoginVerify() ) {
             $model->scenario = 'loginVerify';
        }else {
            $model->scenario = 'login';
        }
        if ($model->load($posts, '') && $model->login()) {
            $token = Yii::$app->getUser()->getToken();
            return static::notice($token);
        } else {
            $firstError = $model->getFirstError('LoginForm');
            if( $firstError === LoginForm::ERROR_IS_MODIFY_PASSWORD ) {
                return static::notice(LoginForm::ERROR_IS_MODIFY_PASSWORD, 403);
            }

            return static::notice(Form::formatErrorsForApi($model->getErrors()), 401);
        }

    }

    /**
     * 用refreshToken刷新accessToken和refreshToken
     * @return mixed
     * @throws HttpException
     */
    public function actionRefreshToken(){
        $refreshToken = Yii::$app->request->get('refresh-token');
        Yii::$app->user->refreshToken($refreshToken);
        $token = Yii::$app->getUser()->getToken();
        if($token){
            return static::notice($token);
        } else {
            return static::notice('更新Token失败', 401);
        }
    }

    /**
     * 用refreshToken刷新accessToken
     * @return mixed
     * @throws HttpException
     */
    public function actionRefreshAccessToken(){
        $refreshToken = Yii::$app->request->get('refresh-token');
        Yii::$app->user->refreshAccessToken($refreshToken);
        $token = Yii::$app->getUser()->getToken();
        if($token){
            return static::notice($token);
        } else {
            return static::notice('更新Token失败', 401);
        }
    }

    /**
     * 用refreshToken刷新refreshToken
     * @return mixed
     * @throws HttpException
     */
    public function actionRefreshRefreshToken(){
        $refreshToken = Yii::$app->request->get('refresh-token');
        Yii::$app->user->refreshRefreshToken($refreshToken);
        $token = Yii::$app->getUser()->getToken();
        if($token){
            return static::notice($token);
        } else {
            return static::notice('更新Token失败', 401);
        }
    }

    /**
     * 后台登录前台
     * @return mixed
     * @throws HttpException
     */
    public function actionLoginByBackend(){
        if(Yii::$app->user->validateBackendAuth()){
            $userId = Yii::$app->request->post('id');
            if($result = Yii::$app->user->loginByBackend($userId)){
                return static::notice($result);
            }
        }
        return static::notice('非法请求', 400);
    }

    /**
     * @return mixed
     * @throws HttpException
     */
    public function actionNoLoginModifyPassword() {
        if(\Yii::$app->request->isPost){
            $form = new UserForm();
            $form->scenario = 'noLoginModifyPassword';
            $post = \Yii::$app->request->post();
            if($form->load($post, '') && $result = $form->noLoginModifyPassword()){
                return static::notice('密码修改成功');
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
            }
        }
        return static::notice('非法访问', 400);
    }

}
