<?php
namespace Smi\Controller;
use Think\Controller;
header("Content-type:text/html;charset=utf-8");
class AuthController extends BaseController {
    /**
     * 分组
     */
    public function group_list()
    {
        $where = 1;
        $order = "`id` DESC";
        $l = 10;//确定每页记录数
        $count = M("group") -> where($where) -> count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page -> show();// 分页显示输出
        $list = M("group") -> where($where) -> order($order) -> limit($Page -> firstRow . ',' . $Page -> listRows) -> select();
        $this -> assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this -> assign("list", $list);
        $this -> display("group_list");die;
    }

    /**
     * 建立新分组
     */
    public function group_add()
    {
        $this -> assign("legend", "New grouping");
        $this -> display("group_add");die;
    }

    /**
     * 编辑分组
     */
    public function group_edit()
    {
        // 接收 ID
        $id = I("id");
        if (!$id) {$this -> error("System failure，Cannot receive ID");die;}
        
        // 获取该记录信息
        $info = M("group") -> where("`id` = $id") -> field('id, groupname') -> find();

        $this -> assign("info", $info);
        $this -> assign("legend", "Editing group“{$info['groupname']}”");
        $this -> display("group_add");die;
    }

    /**
     * [gourp_op 权限操作]
     * @AuthorHTL
     * @DateTime  2018-03-08T16:10:29+0800
     * @return    [type]                   [description]
     */
    public function gourp_op()
    {
         // 接收 ID
        $id = I("id");
        // if (!$id) $this->ajaxReturn(['status' => -1, 'msg' => '系统故障，无法接收 ID']);

        if (!empty($id)) {// 更新
            // 提交后处理表单
            // 接收表单
            $groupname = I("groupname");
            $auth = I("auth");
            $time = time();
            $ip = $_SERVER['REMOTE_ADDR'];
            // 空值处理
            if (!$groupname) $this->ajaxReturn(['status' => -1, 'msg' => 'Please fill in the group name']);
            // 查重
            $return = D("Group") -> check_same($groupname, $id);
            if ($return) $this->ajaxReturn(['status' => -1, 'msg' => 'The group name has been used']);
            // 权限
            $auth = implode(",", $auth);
            // 数据保存
            $data['groupname'] = $groupname;

            $data['auth'] = $auth;
            $data['edit_ip'] = $ip;
            $data['edit_time'] = $time;
            $insert_id = M("group") -> where("`id` = $id") -> save($data);
        } else {// 添加
            // 接收表单
            $groupname = I("groupname");
            $auth = I("auth");
            $time = time();
            $ip = $_SERVER['REMOTE_ADDR'];
            // 空值处理
            if (!$groupname) $this->ajaxReturn(['status' => -1, 'msg' => 'Please fill in the group name']);
            // 查重
            $return = D("Group") -> check_same($groupname);
            if ($return) $this->ajaxReturn(['status' => -1, 'msg' => 'The group name has been used']);
            // 权限
            $auth = implode(",", $auth);
            // 数据保存
            $data['groupname'] = $groupname;
            $data['auth'] = $auth;
            $data['create_ip'] = $ip;
            $data['create_time'] = $time;
            $insert_id = M("group") -> add($data);
        }

        if ($insert_id) {
            session('auth',explode(',',  M('group')->where(array('group_id' => session('group_id')))->find()['auth']));// 编辑成功，重新分配权限
            $this->ajaxReturn(['status' => 1, 'msg' => 'Operation is successful']);
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => 'The operation failure']);
        }
    }

    /**
     * 获取权限节点
     */
    public function all_node()
    {
        $group_id = I('post.group_id');

        // if (empty($group_id)) $this->ajaxReturn(['status' => -1, 'msg' => '权限组id为空']);

        $auth_list = array();

        if (!empty($group_id)) {
             // 获取该记录信息
            $info = M("group") -> where("`id` = $group_id") -> field('id, groupname, auth') -> find();
            // 权限拆分
            $auth_list = explode(",", $info['auth']);
        }

        $node_list = M('node')->field('id, pid, title, auth_name, remark')->select();

        foreach ($node_list as $key => &$value) {
            if (!empty($value['remark'])) {
                $value['title'] .= '（'.$value['remark'].'）';
            }

            unset($node_list[$key]['remark']);

            if(in_array($value['auth_name'], $auth_list)) {
                $value['checked'] = true;
            } else {
                $value['checked'] = false;
            }
        }

        $this->ajaxReturn($node_list);
    }

    /**
     * 删除分组
     */
    public function group_del()
    {
        //接收 ID
        $id = I("id");
        if (!$id) {$this -> error("System failure, unable to receive ID");die;}
        $bool = M("group") -> delete($id);
        $this -> redirect("group_list");die;
    }

    /**
     * 管理员
     */
    public function admin_list()
    {
        $where = "a.`is_business` = 2";
        $order = "a.`login_num` DESC,a.`id` DESC";
        $l = 10;//确定每页记录数
        $count = M("admin") -> join(" a LEFT JOIN `am_group` g ON a.`group_id` = g.`id`") -> where($where) -> count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page -> show();// 分页显示输出
        $list = M("admin") -> join(" a LEFT JOIN `am_group` g ON a.`group_id` = g.`id`") -> where($where) -> field("a.*,g.`groupname`") -> order($order) -> limit($Page -> firstRow . ',' . $Page -> listRows) -> select();
        $this -> assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this -> assign("list", $list);
        $this -> display("admin_list");die;
    }

    /**
     * 录入新管理员
     */
    public function admin_add()
    {
        if ($_POST) {
            // 提交后处理表单
            // 接收表单
            $username = I("username");
            $password = I("password");
            $group_id = I("group_id");
            $status = I("status");
            $time = time();
            $ip = $_SERVER['REMOTE_ADDR'];
            // 空值处理
            if (!$username) {$this -> error("Please fill in the user name");die;}
            if (!$password) {$this -> error("Please fill in the password");die;}
            if ($group_id == "no") {$this -> error("Please select group");die;}
            // 上帝账号保护
            if ($username == "admin") {$this -> error("Ban the use of 'admin'");die;}
            // 查重
            $return = D("Admin") -> check_same($username);
            if ($return) {$this -> error("The user name has been used");die;}
            // 密码
            $password = md5($password);
            // 数据保存
            $data['username'] = $username;
            $data['password'] = $password;
            $data['group_id'] = $group_id;
            $data['status'] = $status;
            $data['create_ip'] = $ip;
            $data['create_time'] = $time;
            $data['is_business'] = 2;
            $insert_id = M("admin") -> add($data);
            $this -> redirect("admin_list");die;
        }
        // 获取分组列表
        $group_list = D("Group") -> get_list();
        $this -> assign("group_list", $group_list);
        $this -> assign("legend", "Enter new administrator");
        $this -> display("admin_add");die;
    }

    /**
     * 编辑管理员
     */
    public function admin_edit()
    {
        // 接收 ID
        $id = I("id");
        if (!$id) {$this -> error("System failure, unable to receive ID");die;}
        if ($_POST) {
        // 提交后处理表单
            // 接收表单
            $username = I("username");
            $group_id = I("group_id");
            $status = I("status");
            $time = time();
            $ip = $_SERVER['REMOTE_ADDR'];
            // 空值处理
            if (!$username) {$this -> error("Please fill in the user name");die;}
            if ($group_id == "no") {$this -> error("Please select group");die;}
            // 上帝账号保护
            if ($username == "admin") {$this -> error("Ban the use of 'admin'");die;}
            // 查重
            $return = D("Admin") -> check_same($username, $id);
            if ($return) {$this -> error("The user name has been used");die;}
            // 数据保存
            $data['username'] = $username;
            $data['group_id'] = $group_id;
            $data['status'] = $status;
            $data['edit_ip'] = $ip;
            $data['edit_time'] = $time;
            $bool = M("admin") -> where("`id` = $id") -> save($data);
            $this -> redirect("admin_list");die;
        }
        // 获取分组列表
        $group_list = D("Group") -> get_list();
        $this -> assign("group_list", $group_list);
        // 获取该记录信息
        $info = M("admin") -> where("`id` = $id") -> find();
        $this -> assign("info", $info);
        $this -> assign("legend", "Edit admin“{$info['username']}”");
        $this -> display("admin_add");die;
    }

    /**
     * 删除管理员
     */
    public function admin_del()
    {
        //接收 ID
        $id = I("id");
        if (!$id) {$this -> error("System failure, unable to receive ID");die;}
        $bool = M("admin") -> delete($id);
        $this -> redirect("admin_list");die;
    }

    /**
     * 重置密码
     */
    public function password_reset()
    {
        // 接收 ID
        $id = I("id");
        $password = I("password");
        $time = time();
        $ip = $_SERVER['REMOTE_ADDR'];
        if (!$id) {$this -> error("ystem failure, unable to receive ID");die;}
        if (!$password) {$this -> error("Please fill in the password");die;}
        // 密码
        $password = md5($password);
        // 数据保存
        $data['password'] = $password;
        $bool = M("admin") -> where("`id` = $id") -> save($data);
        $this -> success("重置成功", U("admin_list"));die;
    }
}