<?php

namespace app\river\controller;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use app\admin\model\Admin;
use think\Session;
use think\Db;
use think\Config;
use think\Hook;
use think\Validate;
use fast\Random;
use fast\Tree;

class User extends Backend
{

    protected $noNeedLogin = ['login'];
    protected $noNeedRight = '*';
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();

        $this->model = new \app\admin\model\reservoir\Messagelog;
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $url2 = $this->request->domain() . '/river/index/index';
        /*if ($this->auth->id) {
            $this->redirect($url);
            //$this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        $this->view->assign('url', $url2);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
        */
        ///--------------
        $url = $this->request->get('url', '/river/index/index');
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
        if ($this->request->isPost()) {
            $username = $this->request->param('username');
            $password = $this->request->param('password');
            $keeplogin = $this->request->param('keeplogin', 1);
            $token = $this->request->param('__token__');

            $rule = [
                'username' => 'require|length:3,30',
                'password' => 'require|length:3,30',
                '__token__' => 'require|token',
            ];
            $data = [
                'username' => $username,
                'password' => $password,
                '__token__' => $token,
            ];

            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            $admin = Admin::get(['username' => $username]);
            if (!$admin) {
                $this->setError('Username is incorrect');
                return false;
            }
            if ($admin['status'] == 'hidden') {
                $this->setError('Admin is forbidden');
                return false;
            }
            if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
                $this->setError('Please try again after 1 day');
                return false;
            }
            if ($admin->password != md5(md5($password) . $admin->salt)) {
                $admin->loginfailure++;
                $admin->save();
                $this->setError('Password is incorrect');
                return false;
            }
            $admin->loginfailure = 0;
            $admin->logintime = time();
            $admin->loginip = request()->ip();
            $admin->token = Random::uuid();
            $admin->save();
            Session::set("admin", $admin->toArray());
            $rd['code'] = 1;
            $rd['msg'] = '登录成功';
            return $rd;
        }

        $background = Config::get('fastadmin.login_background');
        $background = $background ? (stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background) : '';
        $this->view->assign('background', $background);
        $this->view->assign('title', __('Login'));
        $this->view->assign('url', $url2);
        Hook::listen("admin_login_init", $this->request);
        return $this->view->fetch();
        /// --------------

    }

    public function logout()
    {
        if ($this->request->isPost()) {
            $this->token();
            //退出本站
            $this->auth->logout();
            $this->redirect('river/user/login');
            //$this->success(__('Logout successful'), url('user/index'));
        }
        $html = "<form id='logout_submit' name='logout_submit' action='' method='post'>" . token() . "<input type='submit' value='ok' style='display:none;'></form>";
        $html .= "<script>document.forms['logout_submit'].submit();</script>";

        return $html;
    }


}