<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace wap\controllers;

use Yii;
use wap\models\LoginForm;
use yii\helpers\Url;

/**
 * wap端公共控制器
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class PublicController extends \yii\web\Controller
{

    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'minLength' => 4,
                'maxLength' => 4,
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * 登录页面 
     */
    public function actionLogin()
    {
        $request = Yii::$app->request;
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        if ($request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $model = new LoginForm();
            if ($model->load(Yii::$app->request->post()) && $model->login()) {
                \qcbase\models\ActionLog::insertLog('home', '登录');
                return ['status' => 1, 'info' => '登陆成功', 'url' => Url::to(['site/index'])];
            } else {
                if ($model->getFirstError('username') !== null) {
                    $info = $model->getFirstError('username');
                } else {
                    $info = $model->getFirstError('password');
                }
                return ['status' => 0, 'info' => $info];
            }
        } else {
            $configs = Yii::$app->cache->get('basic_config');

            return $this->renderPartial('login', [
                'configs' => $configs,
            ]);
        }
    }

    /**
     * 退出
     */
    public function actionLogout()
    {
        if (!Yii::$app->user->isGuest) {
            \qcbase\models\ActionLog::insertLog('wap', '退出');
            Yii::$app->user->logout();
        }
        return $this->goHome();
    }
}
