<?php
/**
 * Created by PhpStorm.
 * User: sunmoon<i@liming.me>
 * Date: 2019-07-30
 * Time: 16:47
 */

namespace common\libs\logging\login;

use common\helpers\Date;
use common\helpers\Form;
use common\models\forms\LogUserLoginForm;
use common\models\Period;
use Yii;

class UserLogin {

    /**
     * 登录成功
     * @param $userInfo
     * @return LogUserLoginForm
     * @throws \Exception
     */
    public static function success($userInfo){
        $returnResult = '';
        $successTimes = intval($userInfo['LOGIN_NUMS']) + 1;
        $result = self::recorder($userInfo['USER_NAME'], '1', $returnResult, $userInfo['FAIL_NUMS'], $successTimes);
        return $result;
    }

    /**
     * 登录失败
     * @param $userInfo
     * @param $returnResult
     * @return LogUserLoginForm
     * @throws \Exception
     */
    public static function fail($userInfo, $returnResult){
        $failTimes = intval($userInfo['FAIL_NUMS']) + 1;
        $result = self::recorder($userInfo['USER_NAME'], '0', $returnResult, $failTimes, $userInfo['LOGIN_NUMS']);
        return $result;
    }

    /**
     * 记录器
     * @param $account
     * @param $optType
     * @param $returnResult
     * @param $failTimes
     * @param $successTimes
     * @return LogUserLoginForm
     * @throws \Exception
     */
    public static function recorder($account, $optType, $returnResult, $failTimes, $successTimes){
        $period = Period::instance();
        $periodNum = $period->getNowPeriodNum();
        $form = new LogUserLoginForm([
            'user_name' => trim($account),
            'ip' => Yii::$app->request->getUserIP(),
            'created_at' => intval(Date::nowTime()),
            'user_agent' => Yii::$app->request->getUserAgent(),
            'period_num' => intval($periodNum),
            'opt_type' => $optType,
            'success_times' => intval($successTimes),
            'fail_times' => intval($failTimes),
            'device' => Yii::$app->request->getDevice(),
            'request_route' => Yii::$app->requestedRoute,
            'return_result' => $returnResult,
        ]);
        if(!$form->add()){
            throw new \Exception(Form::formatErrorsForApi($form->getErrors()));
        }
        return $form;
    }
}