<?php

namespace app\home;

use app\BaseController;
use app\common\model\SettingModel;
use app\common\model\UserModel;
use think\exception\HttpResponseException;
use think\facade\View;
use think\Response;

/**
 * 控制器基础类
 */
abstract class HomeBaseController extends BaseController
{
    protected $tab = '';
    protected $user = null;

    // 初始化
    protected function initialize()
    {
        $setting = SettingModel::select();
        $set     = [];
        foreach ($setting as $v) {
            $set[$v['code']] = $v['value'];
        }
        config($set, 'home');

        $user_id = get_user_id();
        if (!empty($user_id)) {
            $this->user = UserModel::where('id',$user_id)->hidden(['password','salt'])->find();
        }

        $this->init();

        View::assign('tab',$this->tab);
        View::assign('user',$this->user);
    }

    protected function init()
    {
    }

    protected function checkLogin()
    {
        $sessionUserId = session('home.user.id');
        if (empty($sessionUserId)) {
            if (request()->isAjax()) {
                $res      = ['code' => 401, 'msg' => '请登录'];
                $response = Response::create($res, 'json');
                throw new HttpResponseException($response);
            } else {
                session('back_url',request()->url());
                $response = redirect('/home/login/index');
                throw new HttpResponseException($response);
            }
        }

        if (empty($this->user)) {
            jump('该用户已删除');
        }
        if ($this->user['status'] != UserModel::STATUS_PASS) {
            jump('该账号暂时无法使用');
        }
    }
}
