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

namespace qcbase\controllers;

use Yii;
use common\models\LoginForm;
use yii\console\Request;
use common\models\User;
use qcbase\models\UserInfo;
use qcbase\models\Cache;
use qcbase\models\Version;

/**
 * 后台默认控制器
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class SiteController extends Controller
{
    //public $layout = 'frame';

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [];
    }

    /**
     * 后台主页
     */
    public function actionIndex()
    {
        $cache = Yii::$app->cache;
        //第一次安装要更新缓存
        $model = new \qcbase\models\Menu();
        //获取菜单
        $navTree = $model->getAdminMenu();
        
        $users = $cache->get('user_list');
        $needCache = (empty($users)) ? 1 : 0;
        
        return $this->renderPartial('index', ['navTree' => $navTree, 'needCache' => $needCache]);
    }

    /**
     * 更新缓存
     */
    public function actionCache()
    {
        if (isset($_REQUEST['do_submit']) && $_REQUEST['do_submit'] == 1) {
            $id = (int) Yii::$app->request->get('id');
            $cacheConfig = Cache::getConfig();
            $cacheIds = array_keys($cacheConfig);

            if (isset($cacheIds[$id])) {
                try {
                    Cache::update($cacheIds[$id]);
                    $tip = $cacheConfig[$cacheIds[$id]]['name'] . '缓存更新成功...';
                    $type = 'success';
                }
                catch (ErrorException $e) {
                    $tip = $e->getMessage();
                    $type = 'error';
                }
                $id++;
                $url = ['cache', 'do_submit' => 1, 'id' => $id];
            }
            else {
                $tip = '缓存全部更新完成...';
                $type = 'error';
                $url = '#';
            }

            echo "<script type='text/javascript'>window.parent.showMsg('$tip','$type');</script>";
            return $this->flash(['time' => 0, 'url' => $url]);
        }
        else {
            return $this->render('cache');
        }
    }

    /**
     * 后台统一错误页面
     */
    public function actionError()
    {
        $exception = Yii::$app->errorHandler->exception;
        if ($exception !== null) {
            return $this->flash('非常抱歉，出错了！' . $exception->getMessage(), 'error', '', null);
        }
    }

    /**
     * 后台公共提示页面
     * @param string $info 提示信息 也可以是数组['info' => '操作成功']
     * @param string $type 提示类型 success error
     * @param string $url 要跳转的地址 默认为返回上一页
     * @return type
     */
    public function actionFlash($info = '', $type = '', $url = '')
    {
        return $this->flash($info, $type, $url);
    }

    /**
     * 个人中心详情页
     * @author yxd
     */
    public function actionInfo()
    {
        $model = new User;
        $model->info = new UserInfo;
        $model = User::find()
            ->where(['user_id' => Yii::$app->user->id])
            ->with('info')
            ->one();
        if (Yii::$app->request->isPost) {
            $model->scenario = 'info';
            $model->load(Yii::$app->request->post());
            $model->user_id = Yii::$app->user->id;
            if ($model->validate() && $model->save()) {
                return $this->flash('个人信息更新成功', 'success');
            } else {
                return $this->flash('个人信息更新失败', 'error');
            }
        }
        return $this->render('info', ['model' => $model]);
    }

    /**
     * 系统信息
     * @author xiaobai
     */
    public function actionMain()
    {
        $info = [
            'SERVER_SOFTWARE' => PHP_OS . ' ' . $_SERVER["SERVER_SOFTWARE"],
            'mysql_get_server_info' => php_sapi_name(),
            'upload_max_filesize' => ini_get('upload_max_filesize'),
            'max_execution_time' => ini_get('max_execution_time') . "秒",
            'disk_free_space' => round((@disk_free_space(".") / (1024 * 1024)), 2) . 'M',
        ];

        $office = [
            '北京时间' => gmdate("Y年n月j日 H:i:s", time() + 8 * 3600),
                '服务器域名/IP' => $_SERVER['SERVER_NAME'],
                /*'版本:' => 'V1.0.0 2014-11-06',*/
                '作者&Author' => 'kefu@u-bo.com',
                '版权&Copyright' => '<a href="http://www.u-bo.com/" target=_blank>南京友博网络科技有限公司</a>',
                '官网&Office' => '<a href="http://www.uboa.com.cn/" target=_blank>http://www.uboa.com.cn</a>',
            ];
        $copyright = [
            '授权域名' => $_SERVER['SERVER_NAME'],
            '授权使用' => '免费开源',
            '授权类型' => '友博CRM客户管理系统',
            '授权时间' => '永久',
            '版本号' => Version::getVersion(),
        ];

        $id = Yii::$app->user->id;
        $map = [
            'user_id' => $id,
        ];
        $user = User::find()
            ->select('username,last_login_time,last_login_ip')
            ->where($map)
            ->asArray()
            ->one();

        $user = [
            '用户名' => $user['username'],
            '用户角色'=> implode(',', Yii::$app->session->get('user_roles')),
            '最后登录时间' => date("Y-m-d H:i:s", $user['last_login_time']),
            '最后登录ip' => $user['last_login_ip'],
        ];


        return $this->render('main', [
                'info' => $info,
                'office' => $office,
                'copyright' => $copyright,
                'user' => $user,
            ]);
    }

    /**
     * 密码修改
     * @author xiaobai
     */
    public function actionRepwd()
    {
        $model = new User();
        $id = Yii::$app->user->id;
        $pk = $model->getId();

        if (isset($_POST['User'])) {
            $model = $model->findIdentity($id);
            $model->scenario = 'repwd'; //指定场景
            $model->attributes = $_POST['User'];
            $model->role = \qcbase\models\Auth::getRolesByUser($model->user_id);
            if ($model->save()) {
                return $this->flash('密码更新成功', 'success');
            } else {
                return $this->flash('密码更新不成功', 'error');
            }
        } else {
            return $this->render('repwd', [
                'model' => $model,
                'pk' => $pk,
            ]);
        }
    }

}
