<?php
namespace app\controller\manager;

use app\model\{Member, Log};

class Safe extends Base 
{
    /**
     * 安全设置
     * @return Safe
     */

    public function index()
    {
        $auth = session('auth');
        if($this->request->isPost()){
            if ($auth) {
                $authId = $auth['userId'];
                $oldPassword = trim(input('post.password_old'));
                $password = trim(input('post.password'));
                $passwordAgain = trim(input('post.password_again'));
                $name = trim(input('post.name'));

                $user = Member::getByID($authId);
                if (empty($user)) {
                    return $this->json(1, '登录失效,请重新登录后再试!');
                }
                if (empty($name)) {
                    return $this->json(2, '用户名不能为空!');
                }
                $hasUser = Member::getByUserName($name);
                if (!empty($hasUser) && $hasUser['id'] != $authId) {
                    return $this->json(3, '该用户名已被其他用户使用,请更换!');
                }
                if (empty($password) || empty($oldPassword)) {
                    return $this->json(4, '用户密码不能为空!');
                }
                if ($password != $passwordAgain) {
                    return $this->json(5, '新密码两次输入不一致!');
                }
                if (mb_strlen($password) < 6 || mb_strlen($password) > 30) {
                    return $this->json(6, '新密码长度格式不正确,请输入6~30位密码!');
                }
                if ($user['password'] != md5($oldPassword)) {
                    return $this->json(7,'原密码不正确');
                }
                $data['password'] = md5($password);
                Member::updateById($authId, $data);
                Log::write('safe', 'index', "安全设置,ID:{$authId}, 管理员:{$name}");
                session('auth', null);
                //cache('rules_'.$authId, null);    //当前看代码,这个是无用代码;先注释掉,如果在使用过程中不会用到,再删除。
                cache('group_rules_'.$authId, null);
                cache('rule_names_'.$authId, null);
                return $this->json(0, '修改成功,请重新登录!');
            } else {
                return $this->json(1, '登录失效,请重新登录后再试!');
            }
        }else{
            $this->data['item'] = $auth;
            return $this->view();
        }
    }
}