<?php

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

namespace qcbase\controllers;

use Yii;
use yii\web\ForbiddenHttpException;

/**
 * 后台控制器基类
 * 
 * 所有后台控制器继承的基类,对后台的操作进行统一管理，定义公共操作
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class Controller extends \yii\web\Controller
{

    /**
     * @var string 当前操作的主模型名称 比如 '\common\models\User'
     */
    public $model;

    /**
     * 基本配置
     */
    public $basic_config;

    /**
     * 系统配置
     */
    public $system_config;

    /**
     * 判断用户是否登录
     */
    public function beforeAction($action)
    {

        if (parent::beforeAction($action)) {

            //判断登录
            if (Yii::$app->user->isGuest) {
                return $this->redirect(Yii::$app->user->loginUrl);
            }
//            Yii::$app->user->on('saveLog', ['qcbase\models\ActionLog', 'insertLog']); //日志
            //权限认证
            $auth = Yii::$app->params['auth'];
            $moduleId = 'admin';
            $controllerId = $action->controller->id;
            $actionId = $action->id;
            $operation = $moduleId . '/' . $controllerId . '/' . $actionId;
            if ($auth['userAuthOn'] && !Yii::$app->session->get('isSuperAdmin')) {
                //必须认证操作
                if ($auth['requireAuthOperation'] !== [] && in_array($operation, $auth['requireAuthOperation']) && !Yii::$app->user->can($operation)) {
                    throw new ForbiddenHttpException('权限不足！');
                }
                if (!in_array($controllerId, $auth['notAuthController']) && !in_array($actionId, $auth['notAuthAction']) && !in_array($operation, $auth['notAuthOperation']) && !Yii::$app->user->can($operation)) {
                    throw new ForbiddenHttpException('权限不足！');
                }
            }

            //获取配置信息
            $this->basic_config = Yii::$app->cache->get('basic_config');
            $this->system_config = Yii::$app->cache->get('system_config');


            //如果当前的model为空，则自动根据控制器id填充
            if ($this->model == null) {
                $controllerId = $action->controller->id;
                $modelName = '';
                //如果控制器id包含-,则模型名称为-分隔的单词的首字母大写拼接而成
                if (false !== strpos($controllerId, '-')) {
                    $words = explode('-', $controllerId);
                    foreach ($words as $word) {
                        $modelName .= ucwords($word);
                    }
                } else {
                    $modelName = ucwords($action->controller->id);
                }
                if (isset($this->module->module)) {
                    $this->model = 'qcbase\modules\\' . $this->module->id . '\\models\\' . $modelName;
                } else {
                    $this->model = 'qcbase\models\\' . $modelName;
                }
            }
            \qcbase\models\ActionLog::insertLog();
            return true;
        } else {
            return false;
        }
    }

    public function actions()
    {
        return [
            'index' => [
                'class' => 'qcbase\actions\Index',
            ],
            'create' => [
                'class' => 'qcbase\actions\Create',
            ],
            'view' => [
                'class' => 'qcbase\actions\View',
            ],
            'update' => [
                'class' => 'qcbase\actions\Update',
            ],
            'delete' => [
                'class' => 'qcbase\actions\Delete',
            ],
            'sort' => [
                'class' => 'qcbase\actions\Sort',
            ],
        ];
    }

    /**
     * 后台公共提示页面
     * @param string $info 提示信息 也可以是数组['info' => '操作成功']
     * @param string $type 提示类型 success error
     * @param string $url 要跳转的地址 默认为返回上一页
     * @param int $time 跳转等待时间
     * @return type
     */
    public function flash($info = '', $type = '', $url = '', $time = 3000)
    {
        //第一个参数可以直接使用数组，方便直接设置其中一个参数
        if (is_array($info)) {
            $type = (isset($info['type'])) ? $info['type'] : '';
            $url = (isset($info['url'])) ? $info['url'] : '';
            $time = (array_key_exists('time', $info)) ? $info['time'] : 3000;
            $info = (isset($info['info'])) ? $info['info'] : '';
        }
        if ($info == '' || $type == '') {
            $session = Yii::$app->getSession();
            if ($session->hasFlash('success')) {
                $info = $session->getFlash('success', '操作成功', true);
                $type = 'success';
            } else if ($session->hasFlash('error')) {
                $info = $session->getFlash('error', '操作失败', true);
                $type = 'error';
            } else {
                $info = '没有任何提示信息!';
                $type = 'error';
            }
        }

        if ($url == '') {
            $url = 'javascript:history.back(-1)';
        } elseif ($url !== null && $url !== '#') {
            $url = \yii\helpers\Url::to($url);
        }

        return $this->renderPartial('/site/flash', [
                    'info' => $info,
                    'type' => $type,
                    'url' => $url,
                    'time' => $time,
        ]);
    }

}
