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

namespace common\libs\logging\login;

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

class AdminLogin {

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

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

    /**
     * 记录器
     * @param $account
     * @param $optType
     * @param $returnResult
     * @param $failTimes
     * @param $successTimes
     * @return LogAdminLoginForm
     * @throws \Exception
     */
    public static function recorder($account, $optType, $returnResult, $failTimes, $successTimes){
        $period = Period::instance();
        $periodNum = $period->getNowPeriodNum();
        $form = new LogAdminLoginForm([
            'adm_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;
    }
}