<?php
/**----------------------------------------------------------------------
 * OpenCenter V3
 * Copyright 2014-2018 http://www.ocenter.cn All rights reserved.
 * ----------------------------------------------------------------------
 * Author: wdx(wdx@ourstu.com)
 * Date: 2018/9/28
 * Time: 14:39
 * ----------------------------------------------------------------------
 */

namespace app\admin\controller;

use app\admin\validate\UserRole;
use app\admin\validate\UserRule;
use app\admin\model\AdminLog;
use think\Db;

/**
 * Class User
 * 用户控制器类
 * @package app\admin\controller
 */
class User extends Base
{
    protected $user;
    protected $config;
    protected $userRule;
    protected $userRole;
    protected $userLog;
    protected $userCount;
    protected $scoreType;
    protected $scoreLog;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->config = model('admin/Config');
        $this->userRule = model('admin/UserRule');
        $this->user = model('admin/User');
        $this->userRole = model('admin/userRole');
        $this->userLog = model('admin/userLog');
        $this->userCount = model('admin/userCount');
        $this->scoreType = model('admin/ScoreType');
        $this->scoreLog = model('admin/ScoreLog');
    }

    /**
     * 注册配置
     * @return mixed
     * @author:wdx(wdx@ourstu.com)
     */
    public function registerConfig()
    {
        if ($this->request->isPost()) {
            $data = input('data/a', []);
            $res = $this->config->saveConfig($data);
            if ($res) {
                AdminLog::setTitle('注册配置设置成功');
                $this->success('设置成功');
            } else {
                AdminLog::setTitle('注册配置设置失败');
                $this->error('设置失败');
            }
        } else {
            $config = $this->config->queryConfig();
            $config['register_type'] = explode(',', $config['register_type']);
            $config['reg_switch'] = explode(',', $config['reg_switch']);
            $this->assign('config', $config);
            return $this->fetch();
        }
    }

    /**
     * 用户权限列表
     * @return mixed|\think\response\Json
     * @author:wdx(wdx@ourstu.com)
     */
    public function userAuth()
    {
        if ($this->request->isAjax()) {
            $page = input('get.page/d', 1);
            $limit = input('get.limit/d', 20);
            $map[] = ['status', '>=', 0];
            //用户权限列表
            $userAuthList = $this->userRule->getList($map, $page, $limit);
            //父级权限列表
            $userParentAuthTitle= $this->userRule->getParentTitle();
            foreach ($userAuthList as &$val) {
                to_status($val);
                $val['ptitle'] = ($val['pid'] ? $userParentAuthTitle[$val['pid']] : '-');
            }
            unset($val);
            $count = $this->userRule->where($map)->count();
            $data = [
                'code' => 0,
                'msg' => '数据返回成功',
                'count' => $count,
                'data' => $userAuthList
            ];
            AdminLog::setTitle('获取用户权限列表');
            return json($data);
        }
        AdminLog::setTitle('用户权限列表');
        return $this->fetch();
    }

    /**
     * 删除用户权限
     * @author:wdx(wdx@ourstu.com)
     */
    public function delUserAuth()
    {
        $ids = array_unique(input('post.id/a', []));
        foreach ($ids as $val) {
            $isParent = $this->userRule->where('id', $val)->value('pid');
            $existSon = $this->userRule->where('pid', $val)->where('status', 1)->find();
            if (!$isParent && $existSon) {
                $this->error('存在可用子权限，删除失败');
            } else {
                $rs = $this->userRule->where('id', $val)->setField('status', '-1');
                if (!$rs) {
                    $this->error('删除失败');
                }
            }
        }
        unset($val);
        AdminLog::setTitle('删除用户权限');
        $this->success('删除成功');
    }

    /**
     * 用户权限新增与编辑
     * @return mixed
     * @author:wdx(wdx@ourstu.com)
     */
    public function userAuthForm()
    {
        if ($this->request->isPost()) {
            $data = input('post.data/a', []);
            $title = $data['id'] ? '编辑' : '新增';
            $data['module'] = strtolower($data['module']);
            $data['name'] = strtolower($data['name']);
            $data['status'] = isset($data['status']) ? 1 : 0;
            //自动验证
            $validate = new UserRule();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            if ($data['id']) {
                $res = $this->userRule->update($data);
            } else {
                $res = $this->userRule->insert($data);
            }
            if ($res) {
                AdminLog::setTitle($title . '用户权限成功');
                $this->success($title . '用户权限成功');
            } else {
                AdminLog::setTitle($title . '用户权限失败');
                $this->error($title . '用户权限失败');
            }
        } else {
            $id = input('get.id/d', 0);
            $rule = $this->userRule->find($id);
            $userRuleTree = $this->userRule->getTree('id, pid, title');
            $this->assign('rule', $rule);
            $this->assign('userRuleTree', $userRuleTree);
            return $this->fetch();
        }
    }

    /**
     * 用户角色列表
     * @return mixed|\think\response\Json
     * @author:wdx(wdx@ourstu.com)
     */
    public function userRole()
    {
        if ($this->request->isAjax()) {
            $page = input('get.page/d', 1);
            $limit = input('get.limit/d', 20);
            $map[] = ['status', '>=', 0];
            $pRole = $this->userRole->where('status', 1)->column('title', 'id');
            $pRole[0] = '顶级角色组';
            $userRoleList = $this->userRole->where($map)->page($page, $limit)->select()->toArray();
            $count = $this->userRole->where($map)->count();
            foreach ($userRoleList as &$val) {
                to_status($val);
                $val['pid'] = $pRole[$val['pid']] . '[' . $val['pid'] . ']';
            }
            unset($val);
            $data = [
                'code' => 0,
                'msg' => '数据返回成功',
                'count' => $count,
                'data' => $userRoleList
            ];
            AdminLog::setTitle('获取用户角色列表');
            return json($data);
        }
        AdminLog::setTitle('用户角色列表');
        return $this->fetch();
    }

    /**
     * 用户角色表单
     * @return mixed
     * @author:wdx(wdx@ourstu.com)
     */
    public function userRoleForm()
    {
        if ($this->request->isPost()) {
            $data = input('');
            $data['title'] = $data['name'];
            $title = isset($data['id']) ? '编辑' : '新增';
            $data['status'] = (isset($data['status']) ? 1 : 0);
            //自动验证
            $validate = new UserRole();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            if ($data['id']) {
                $res = $this->userRole->update($data);
            } else {
                $res = $this->userRole->insert($data);
            }
            if ($res) {
                AdminLog::setTitle($title . '用户角色成功');
                $this->success($title . '用户角色成功');
            } else {
                AdminLog::setTitle($title . '用户角色失败');
                $this->error($title . '用户角色失败');
            }
        } else {
            $id = input('get.id/d', 0);
            $role = $this->userRole->find($id);
            $userRuleTree = $this->userRule->getTree('id, pid, title');
            $userRoleTree = $this->userRole->getTree('id, pid, title');
            $this->assign('role', $role);
            $this->assign('userRuleTree', $userRuleTree);
            $this->assign('userRoleTree', $userRoleTree);
            return $this->fetch();
        }
    }

    /**
     * 获取用户权限节点树
     * @author:wdx(wdx@ourstu.com)
     */
    public function getUserAuthTree()
    {
        $id = input('id/d', 0);
        $rules = $this->userRole->where('id', $id)->value('rules');
        if ($rules !== '*') {
            $rules = explode(',', $rules);
        }
        $map[] = ['status', '>=', 0];
        /* 获取所有分类 */
        $list = $this->userRule->field('id, pid, title')->where($map)->order('sort')->select()->toArray();
        foreach ($list as $key => &$val) {
            $val['name'] = $val['title'];
            unset($val['title']);
            $val['value'] = $val['id'];
            if ($rules === '*' || in_array($val['id'], $rules)) {
                $val['checked'] = true;
            } else {
                $val['checked'] = false;
            }
        }
        unset($val);
        $adminAuth = $this->userRule->getAuthTree($list);
        $trees = ['trees' => $adminAuth];
        $data = [
            'code' => 0,
            'msg' => '获取成功',
            'data' => $trees
        ];
        return json($data);
    }

    /**
     * 删除用户角色
     * @author:wdx(wdx@ourstu.com)
     */
    public function delUserRole()
    {
        $ids = array_unique(input('post.id/a', []));
        foreach ($ids as $val) {
            if ($val == 1 || $val == 2) {
                $this->error('禁止删除普通用户或游客分组');
            }
            if ($this->userRole->where('pid', $val)->where('status', 1)->find()) {
                $this->error('该角色分类下存在子角色，删除失败');
            }
            $rs = $this->userRole->where('id', $val)->setField('status', '-1');
            if (!$rs) {
                $this->error('删除失败');
            }
        }
        unset($val);
        AdminLog::setTitle('删除用户角色');
        $this->success('删除成功');
    }

    /**
     * 用户列表
     * @return mixed|\think\response\Json
     * @author:wdx(wdx@ourstu.com)
     */
    public function userList()
    {
        if ($this->request->isAjax()) {
            $page = input('get.page/d', 1);
            $limit = input('get.limit/d', 20);
            $map[] = ['status', '>=', 0];
            $userList = $this->user->where($map)->page($page, $limit)->select()->toArray();
            $count = $this->user->where($map)->count();
            $userRole = $this->userRole->where('status', 1)->column('name', 'id');
            foreach ($userList as &$val) {
                to_time($val, 'reg_time');
                to_time($val, 'last_login_time');
                to_ip($val, 'reg_ip');
                to_ip($val, 'last_login_ip');
                to_status($val);
                $val['role_name'] = $userRole[$val['group_id']];
            }
            unset($val);
            $data = [
                'code' => 0,
                'msg' => '数据返回成功',
                'count' => $count,
                'data' => $userList
            ];
            AdminLog::setTitle('获取用户列表');
            return json($data);
        }
        AdminLog::setTitle('用户列表');
        return $this->fetch();
    }

    /**
     * 用户表单
     * @return mixed
     * @author:wdx(wdx@ourstu.com)
     */
    public function userForm()
    {
        if ($this->request->isPost()) {
            $data = input('post.data/a');
            $title = isset($data['id']) ? '编辑' : '新增';
            $data['status'] = (isset($data['status']) ? 1 : 0);
            foreach ($data as $key => $val) {
                if (strchr($key, 'score')) {
                    $update[$key] = $val;
                    unset($data[$key]);
                }
            }

            if ($data['id']) {
                //自动验证
                if (trim($data['password'])) {
                    $rs = $this->validate($data, 'app\admin\validate\User.add');
                    $data['password'] = think_ucenter_md5(trim($data['password']));
                } else {
                    unset($data['password']);
                    $rs = $this->validate($data, 'app\admin\validate\User.edit');
                }
                if ($rs !== true) {
                    $this->error($rs);
                }

                $res = $this->user->update($data);

                if ($this->userCount->where('uid', $data['id'])->find()) {
                    $this->userCount->where('uid', $data['id'])->update($update);
                } else {
                    $update['uid'] = $data['id'];
                    $this->userCount->where('uid', $data['id'])->insert($update);
                }

                $this->updateScoreLog($data['id'], $update);

                if ($res) {
                    AdminLog::setTitle($title . '用户成功');
                    $this->success($title . '用户成功');
                } else {
                    AdminLog::setTitle($title . '用户失败');
                    $this->error($title . '用户失败');
                }
            }
        } else {
            $id = input('get.id/d', 0);
            $user = $this->user->find($id);
            $userRoleTree = $this->userRole->getTree('id, pid, title');
            $userScoreCount = $this->userCount->getScoreCount($id);
            $scoreType = $this->scoreType->getTypeList();
            $this->assign('user', $user);
            $this->assign('score', $userScoreCount);
            $this->assign('scoreType', $scoreType);
            $this->assign('userRoleTree', $userRoleTree);
            return $this->fetch();
        }
    }

    /**
     * 管理员更新积分日志
     * @param array $data
     * @author:wdx(wdx@ourstu.com)
     */
    private function updateScoreLog($uid = 0, $data = [])
    {
        foreach ($data as $key => $val) {
            $type = substr($key, 5);
            $last = $this->scoreLog
                ->where('uid', $uid)
                ->where('score_type', $type)
                ->order('id desc')
                ->value('finally_value');
            $change = $val - $last;
            $log[] = [
                'uid' => $uid,
                'ip' => $this->request->ip(1),
                'score_type' => $type,
                'value' => $change,
                'finally_value' => $val,
                'create_time' => time(),
                'model' => $this->request->module(),
                'remark' => '管理员[' . $this->aid . ']' . $this->adminName . '编辑'
            ];
        }
        unset($val);
        $this->scoreLog->insertAll($log);
    }

    /**
     * 删除用户
     * @author:wdx(wdx@ourstu.com)
     */
    public function delUser()
    {
        $ids = array_unique(input('post.id/a', []));
        $rs = $this->user->whereIn('id', $ids)->setField('status', '-1');
        if ($rs) {
            AdminLog::setTitle('删除用户');
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 用户日志
     * @return mixed|Json
     * @author:wdx(wdx@ourstu.com)
     */
    public function userLog()
    {
        if ($this->request->isAjax()) {
            $page = input('get.page/d', 1);
            $limit = input('get.limit/d', 20);
            $userLogList = $this->userLog
                ->page($page, $limit)
                ->order('id desc')
                ->select()
                ->toArray();
            foreach ($userLogList as &$val) {
                to_ip($val);
            }
            unset($val);
            $count = $this->userLog->count();
            $data = [
                'code' => 0,
                'msg' => '数据返回成功',
                'count' => $count,
                'data' => $userLogList
            ];
            AdminLog::setTitle('获取用户日志');
            return json($data);
        }
        AdminLog::setTitle('用户日志');
        return $this->fetch();
    }

    /**
     * 删除用户日志
     * @author:wdx(wdx@ourstu.com)
     */
    public function delUserLog()
    {
        $ids = array_unique(input('post.id/a', []));
        $rs = $this->userLog->whereIn('id', $ids)->delete();
        if ($rs) {
            AdminLog::setTitle('删除用户日志');
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 用户退出登录
     * @author:wdx(wdx@ourstu.com)
     */
    public function logout()
    {
        session('user_auth', null);
        session('user_auth_sign', null);
        AdminLog::setTitle('用户退出登录');
        redirect('index/user/login');
    }
}