<?php
/**
 * +------------------------------------------------------------
 * | 用户 user/controller/Admin.php
 * +------------------------------------------------------------
 * | @author: bsh (844783437@qq.com)
 * | @create_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: bsh
 * | @last_modified_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\user\controller;

use app\common\controller\Mail;
use app\common\controller\Sms;
use app\user\model\Company;
use app\user\model\Info;
use app\user\model\User;
use app\user\model\Evaluate;
use app\common\controller\Fields;

class Admin extends Module
{
    private static $fields;

    protected function initialize()
    {
        parent::initialize();
        if (in_array(self::$sys['action'], ['fields', 'fields_form', 'fields_forbid', 'fields_delete', 'fields_status'])) self::$fields = new Fields();
    }

    /**
     * 账号管理
     */
    public function index()
    {
        $attr = input('param.');
        $attr['page'] = max(1, input('param.page', 0));
        $attr['status'] = 1;
        $attr['with'] = 'register';
        $rs = $this->query($attr);
        return json(['code' => 1, 'data' => $rs]);
    }

    /**
     * 改变用户状态
     */
    function change_status($id = [], $status = 0)
    {
        if (!empty($id)) {
            db('user')->where('id', 'in', (array)$id)->update(['status' => $status]);
            $user = db('user')->where('id', 'in', (array)$id)->column('name');
            action('user/Api/log', ['将用户' . ($status == 0 ? '移入' : '移出') . '黑名单', '用户ID:' . join(',', (array)$user)]);
            return json(['code' => 1, 'msg' => '操作成功']);
        }
    }

    /**
     * 日志管理
     */
    public function log()
    {
        if ($this->request->isPost()) {
            if (!empty(input('post.days')) && intval(input('post.days')) >= 30) {
                $delete_time = time() - (intval(input('post.days')) * 86400);
                db('user_log')->where('create_time', '<', $delete_time)->delete();
                action('Api/log', ['日志清除', date('Y-m-d', $delete_time) . '之前的管理员日志']);
                return json(['code' => 1, 'msg' => "已清除 " . date('Y-m-d', $delete_time) . " 之前的管理员日志。"]);
            }
            return json(['code' => 35001, 'msg' => '参数错误']);
        }
        $where = [];
        $rs = db('user_log')->alias('l')
            ->join('user a', 'l.admin_id= a.id')->field('l.*, a.name')->where($where)->order('create_time desc')->paginate(20)->toArray();
        return json(['code' => 1, 'msg' => $rs]);
    }

    /**
     * 用户详情
     */
    public function view($id)
    {
        $rs = $this->query(['id' => $id, 'field' => 'id,group_id,name,email,qq,phone,address,mappoint,money,credit,status']);
        $rs['logs'] = model('app\user\model\Log')->where('user_id', '=', $id)->order('create_time desc')->paginate(20)->toArray();
        $index = model('app\index\model\Data')->where('user_id', '=', $id)->where('status', '<', 4)->order('create_time desc, status desc')->paginate(20)->toArray();
        if (!empty($index['data'])) {
            $columns = load_columns(0, 0, '', '', '');
            foreach ($index['data'] as $k => &$v) {
                $v['column'] = $columns[$v['column_id']];
                $v['url'] = empty($columns[$v['column_id']]['key']) ? '' : url('index/index/view', ['key' => $columns[$v['column_id']]['key'], 'id' => $v['id']], true, true);
                $v['time'] = time_format($v['create_time']);
            }
        }
        $rs['index'] = $index;
        $rs['ip'] = '';
        $rs['ip_address'] = '';
        if ($ip = db('user_log')->where('user_id', '=', $id)->where('action', '=', 'register')->value('ip')) {
            $rs['ip'] = $ip;
            $ip_address = get_ip_address($rs['ip']);
            $rs['ip_address'] = (isset($ip_address['country']) ? $ip_address['country'] : '') . (isset($ip_address['area']) ? $ip_address['area'] : '');
        }
        return json(['code' => 1, 'data' => $rs]);
    }

    /**
     * 数据概览
     */
    public function overview()
    {
        $count = [];
        $count['total'] = User::count();
        $count['blacklist'] = User::where('status', 0)->count();
        $count['week_create'] = db('user_log')->where('action', '=', 'register')->where('create_time', '>', (time() - 60 * 60 * 24 * 7))->count();
        $count['week_login'] = db('user_log')->where('action', '=', 'login')->where('create_time', '>', (time() - 60 * 60 * 24 * 7))->group('user_id')->count();
        $count['month_create'] = db('user_log')->where('action', '=', 'register')->where('create_time', '>', (time() - 60 * 60 * 24 * 30))->count();
        $count['month_login'] = db('user_log')->where('action', '=', 'login')->where('create_time', '>', (time() - 60 * 60 * 24 * 30))->group('user_id')->count();
        $data['count'] = $count;
        $login = array_column(db('user_log')->where("`create_time`>UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 7 DAY))")->where('action', '=', 'login')->group('day')->field("count(*) as count,FROM_UNIXTIME(create_time,'%m-%d') as day")->select(), null, 'day');
        $register = array_column(db('user_log')->where("`create_time`>UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 7 DAY))")->where('action', '=', 'register')->group('day')->field("count(*) as count,FROM_UNIXTIME(create_time,'%m-%d') as day")->select(), null, 'day');
        for ($i = 7; $i > 0; $i--) {
            $day = date("m-d", strtotime("-" . $i . " day"));
            $data['chart']['data'][] = [
                'day' => $day,
                '登陆' => empty($login[$day]['count']) ? 0 : $login[$day]['count'],
                '注册' => empty($register[$day]['count']) ? 0 : $register[$day]['count']
            ];
        }
        $group = action('user/api/group');
        $group_data = array_column(db('user')->field('group_id,count(*) count')->group('group_id')->select(), null, 'group_id');
        foreach ($group as $k => $v) {
            $data['chart']['group'][] = [
                'item' => $v['name'],
                'count' => empty($group_data[$v['id']]['count']) ? 0 : $group_data[$v['id']]['count']
            ];
        }
        $data['chart']['fields'] = ['登陆', '注册'];
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 登录用户
     */
    public function login($id = 0)
    {
        $user = model('app\user\model\User')->with('register')->where('id', $id)->find();
        action('user/Api/log', ['登陆用户【' . $user['name'] . '】', '用户id:' . $id]);
        session('user', $user->append(['login'])->toArray());
        return json(['code' => 1, 'msg' => '登录成功']);
    }

    /**
     * 重置用户信息
     */
    public function reset()
    {
        $data = input('param.');
        if (isset($data['id'])) {
            $user = db('user')->where('id', '=', $data['id'])->find();
            if (!empty($data['name'])) {
                if (db('user')->where('name', '=', $data['name'])->where('id', 'neq', $data['id'])->count()) return json(['code' => 35002, 'msg' => '用户账号已存在']);
                if ($data['name'] != $user['name']) {
                    $msg = $this->validate($data, [
                        'name' => 'require|chsDash|length:4,32'
                    ], [
                        'name.require' => '账号不能为空',
                        'name.chsDash' => '用户名仅可使用汉字、字母、数字、中划线或下划线。',
                        'name.length' => '账号长度在4-32之间'
                    ]);
                    if ($msg !== true) return json(['code' => 35003, 'msg' => $msg]);
                    db('user')->where('id', '=', $data['id'])->setField('name', $data['name']);
                } else {
                    unset($data['name']);
                }
            }
            if (!empty($data['pwd'])) {
                $msg = $this->validate($data, [
                    'pwd' => 'require|length:6,20',
                ], [
                    'pwd.length' => '请输入在6~20位字符的密码。',
                ]);
                if ($msg !== true) return json(['code' => 35004, 'msg' => $msg]);
                db('user')->where('id', '=', $data['id'])->setField('pwd', md5($data['pwd']));
            }
            if (isset($data['phone']) && $data['phone'] == 1) {
                //短信通知
                if (!empty($user['phone'])) {
                    $sms = new Sms();
                    if (!empty($data['name'])) $sms->phone($user['phone'])->type('NAME_1', ['name' => $data['name']])->send();
                    if (!empty($data['pwd'])) $sms->phone($user['phone'])->type('PWD_1', ['pwd' => $data['pwd']])->send();
                }
            }
            if (isset($data['email']) && $data['email'] == 1) {
                //邮箱通知
                if (!empty($user['email'])) {
                    $mail = new Mail();
                    if (!empty($data['name'])) $mail->address($user['email'])->type('reset_name', ['name' => $data['name']])->send();
                    if (!empty($data['pwd'])) $mail->address($user['email'])->type('reset_pwd', ['pwd' => $data['pwd']])->send();
                }
            }
            return json(['code' => 1, 'msg' => '用户信息重置成功']);
        } else {
            return json(['code' => 35005, 'msg' => '用户信息重置失败']);
        }
    }

    /**
     * 用户组
     */
    public function group()
    {
        $group = action('user/api/group');
        return json(['code' => 1, 'data' => $group]);
    }

    /**
     * @param int $id
     */
    function move($id = [], $group_id = 0)
    {
        if (!empty($id)) {
            db('user')->where('id', 'in', (array)$id)->update(['group_id' => $group_id]);
            action('user/Api/log', ['批量移动用户', '用户ID:' . join(',', (array)$id) . ' 用户组ID:' . $group_id]);
            return json(['code' => 1, 'msg' => '移动成功...']);
        }
    }

    /**
     * 黑名单
     */
    function blacklist()
    {
        $attr = input('param.');
        $attr['page'] = max(1, input('param.page', 0));
        $attr['status'] = 0;
        $attr['with'] = 'register';
        $rs = $this->query($attr);
        return json(['code' => 1, 'data' => $rs]);
    }

    /**
     * 删除用户
     * @param int $id
     */
    function delete($id = 0)
    {
        $where[] = ['id', 'in', (array)$id];
        $user = db('user')->where($where)->select();
        db('user')->where($where)->delete();
        action('user/Api/log', ['删除用户【' . implode(',', array_column($user, 'name')) . '】']);
        return json(['code' => 1, 'msg' => '删除成功']);
    }

    function group_form($id = '')
    {
        if (request()->isPost()) {
            $data = [
                'name' => input('post.name', ''),
                'memo' => input('post.memo', ''),
                'status' => input('post.status', 0),
                'setting' => input('post.setting/a', [])
            ];
            $validate = validate('Group');
            if (!$validate->check($data)) return json(['code' => 35006, 'msg' => $validate->getError()]);
            if ($id !== '') {
                $setting = model('Group')->where('id', $id)->value('setting');
                if (!empty($setting)) {
                    $data['setting'] = json_encode(array_replace(json_decode($setting, 1), $data['setting']));
                    db('user_group')->where('id', $id)->update($data);
                    cache('user_group', null);
                } else {
                    $data['setting'] = json_encode($data['setting']);
                    $data['id'] = $id;
                    db('user_group')->insert($data);
                    cache('user_group', null);
                }
            } else {
                $data['type'] = 1;
                $max_id = intval(db('user_group')->max('id'));
                $data['id'] = $max_id + ($max_id == 0 ? 2 : 1);
                $data['setting'] = json_encode($data['setting']);
                db('user_group')->insert($data);
            }
            action('user/api/group', [1]);
            return json(['code' => 1, 'msg' => '用户组更新成功']);
        } else {
            if ($id != '') {
                $data = array_column(action('user/api/group', ['', $id]), null, 'id')[$id];
                if (!empty($data['setting'])) $data['setting'] = json_decode($data['setting'], 1);
                return json(['code' => 1, 'data' => $data]);
            }
        }
    }

    function group_delete($id = '')
    {
        if ($id != '') {
            if (!empty(model('app\user\model\User')->where('group_id', '=', $id)->count())) {
                return json(['code' => 35007, 'msg' => '请先移出该用户组下的用户']);
            }
            $user = model('app\user\model\User')->get($id);
            action('user/Api/log', ['删除用户【' . $user['name'] . '】', '用户id:' . $id]);
            db('user_group')->where('id', '=', $id)->delete();
            cache('user_group', null);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    function _empty($name)
    {
        if (in_array($name, ['group_add', 'group_edit'])) {
            return $this->group_form(input('param.id', ''));
        }
        if (in_array($name, array('role_add', 'role_edit'))) {
            return $this->role_form(input('param.id', 0));
        }
        return parent::_empty($name);
    }

    /**
     * 检测用户名是否存在
     */
    public function search($name = '')
    {
        $data = db('user')->where('name', 'like', '%' . $name . '%')->field('id,name value')->select();
        return json(['code' => 1, 'data' => $data]);
    }

    /*
     * 实名认证
     */
    function auth()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if (empty($data['user_id']) || empty($data['status']) || !in_array($data['status'], [1, 3])) return json(['code' => 35008, 'msg' => '参数错误']);
            if ($data['status'] == 3) {
                if (empty($data['memo'])) return json(['code' => 35009, 'msg' => '请填写审核依据']);
            } else {
                $data['memo'] = '已实名认证';
            }
            model('user')->where('id', '=', $data['user_id'])->setField(['auth' => $data['status']]);
            model('auth')->allowField(true)->save($data, ['user_id' => $data['user_id']]);
            return json(['code' => 1, 'msg' => '操作成功']);
        } else {
            $limit = input('?param.limit') ? input('param.limit') : 20;
            $where = [
                ['u.name', 'like', '%' . input('param.keywords', '') . '%'],
                ['a.status', '=', input('param.status', 2)]
            ];
            $data = model('auth')->alias('a')->join('user u', 'u.id=a.user_id')->field('a.*,u.name user_name')->where($where)->paginate($limit)->toArray();
            return json(['code' => 1, 'data' => $data]);
        }
    }

    /**
     * 添加/修改管理员
     */
    public function form($id)
    {
        if (request()->isPost()) {
            $data = input('post.');
            if ($id) {
                $validate = validate('Edit');
                if (!$validate->check($data)) return json(['code' => 0, 'msg' => $validate->getError()]);
                unset($data['name'], $data['id']);
                if (!empty($data['pwd'])) {
                    $data['pwd'] = md5($data['pwd']);
                } else {
                    unset($data['pwd']);
                }
                model('app\user\model\Admin')->allowField(true)->save($data, ['id' => $id]);
                $admin = db('admin')->where('id', '=', $id)->find();
                //更新用户表信息
                model('app\user\model\User')->allowField(true)->save($data, ['id' => $admin['id']]);
                action('Api/log', ['修改管理员', '帐号:' . input('post.name')]);
                return json(['code' => 1, 'msg' => '管理员《' . input('post.name') . '》已更新。']);
            } else {
                $validate = validate('Add');
                if (!$validate->check($data)) return json(['code' => 0, 'msg' => $validate->getError()]);
                $register = action('user/api/register', [1, [
                    'name' => $data['name'],
                    'pwd' => $data['pwd'],
                    'email' => isset($data['email']) ? $data['email'] : '',
                    'qq' => isset($data['qq']) ? $data['qq'] : '',
                    'phone' => isset($data['phone']) ? $data['phone'] : ''
                ], 0]);
                if ($register['code'] != 1) return json($register);
                $data['id'] = $register['data']['id'];
                model('app\user\model\Admin')->allowField(true)->data($data)->save();
                action('Api/log', ['新增管理员', '帐号:' . $data['name']]);
                return json(['code' => 1, 'msg' => '管理员《' . $data['name'] . '》已新增。']);
            }
        } else {
            if ($id) {
                $rs = model('admin')->alias('a')->join('user u', 'a.id=u.id')->field('a.*,u.name,u.email,u.qq,u.phone')->find($id);
                return json(['code' => 1, 'data' => $rs]);
            }
        }

    }

    /**
     * 删除管理员
     */
    public function admin_delete($id = 0)
    {
        if ($id) {
            if (session('admin.id') == $id) return json(['code' => 35010, 'msg' => '不能删除自己']);
            $rs = db('admin')->alias('a')->join('user u', 'a.id=u.id')->field('a.*,u.name,u.qq,u.email,u.phone')->find($id);
            if ($rs) {
                action('Api/log', ['删除管理员', '帐号:' . $rs['name']]);
                db('admin')->delete($id);
            }
        }
        return json(['code' => 1, 'msg' => "删除成功"]);
    }

    /**
     * 修改密码
     */
    public function pwd()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if (md5($data['old_pwd']) != session('admin.pwd')) {
                return json(['code' => 35011, 'msg' => '您输入的旧密码不正确。']);
            }
            if (empty($data['pwd'])) {
                return json(['code' => 35012, 'msg' => '请输入新密码。']);
            }
            if ($data['pwd'] != $data['confirm_pwd']) {
                return json(['code' => 35013, 'msg' => '您两次新密码输入的不一致。']);
            }
            $data['pwd'] = md5($data['pwd']);
            unset($data['old_pwd']);
            unset($data['confirm_pwd']);
            db('user')->where(['id' => session('admin.id')])->update($data);
            action('Api/log', ['管理员修改密码', '帐号:' . session('admin.name')]);
            return json(['code' => 1, 'msg' => '您的密码已修改。']);
        }
    }

    /**
     * 角色
     */
    public function role($return = 1, $refresh = 0, $status = '')
    {
        if ($refresh) cache('role', null);
        if (!empty(cache('role'))) {
            $rs = cache('role');
        } else {
            $rs = model('role')->select();
            $rs = array_merge(config('app.role'), empty($rs) ? [] : $rs->toArray());
            cache('role', $rs);
        }
        if ($status != '') {
            $data = [];
            foreach ($rs as $k => $v) {
                if (in_array($v['status'], (array)$status)) $data[] = $v;
            }
            $rs = $data;
        }
        return $return ? json(['code' => 1, 'data' => $rs]) : $rs;
    }

    /**
     * 新建/编辑角色
     */
    public function role_form($id)
    {
        if (request()->isPost()) {
            $validate = validate('Role');
            if (!$validate->check(input('post.'))) return json(['code' => 0, 'msg' => $validate->getError()]);
            $data = ['name' => input('post.name'), 'memo' => input('post.memo'), 'status' => input('post.status')];
            if (input('?post.power')) $data['power'] = implode(',', input('post.power/a'));
            if ($id) {
                db('admin_role')->where('id', $id)->update($data);
                action('Api/log', ['编辑角色', 'ID: ' . $id . ' / 名称:' . $data['name']]);
                cache('role', null);
                return json(['code' => 1, 'msg' => '角色《' . $data['name'] . '》已更新。']);
            } else {
                db('admin_role')->insert($data);
                action('Api/log', ['创建角色', '名称:' . $data['name']]);
                cache('role', null);
                return json(['code' => 1, 'msg' => '角色《' . $data['name'] . '》已新增。']);
            }
        } else {
            if ($id) {
                $rs = model('role')->find($id);
                return json(['code' => 1, 'data' => $rs]);
            }
        }
    }

    /**
     * 获得权限列表
     */
    public function navs()
    {
        return json(['code' => 1, 'data' => get_nav_map()]);
    }


    /**
     * 角色删除
     */
    public function role_delete($id = 0)
    {
        $count = db('admin')->where('role_id', $id)->count();
        if ($count == 0) {
            $role = db('admin_role')->find($id);
            action('Api/log', ['删除角色【' . $role['name'] . '】']);
            model('role')->where('id', $id)->delete();
            cache('role', null);
            return json(['code' => 1, 'msg' => '角色删除成功']);
        } else {
            return json(['code' => 35014, 'msg' => '此角色包含' . $count . '位管理员，不可删除。']);
        }
    }

    /**
     * 管理员列表
     */
    public function admin($keywords = '', $limit = 20)
    {
        $where = [];
        if ($keywords) $where[] = ['name', 'like', '%' . $keywords . '%'];
        $rs = model('app\user\model\Admin')->alias('a')->join('user u', 'u.id=a.id')->field('a.*,u.name,u.email,u.qq,u.phone')->where($where)->paginate($limit)->toArray();
        $role = array_column($this->role(0, 1), null, 'id');
        foreach ($rs['data'] as $k => &$v) $v['role'] = empty($role[$v['role_id']]) ? [] : $role[$v['role_id']];
        return json(['code' => 1, 'data' => $rs]);
    }

    /**
     * 当前登录管理员信息
     * @return \think\response\Json
     */
    function info()
    {
        return json(['code' => 1, 'data' => session('admin')]);
    }

    /**
     * 扩展字段
     */
    public function fields($relation_id = 0)
    {
        return self::$fields->fields($relation_id, 'user');
    }

    /**
     * 继承自定义字段禁用
     */
    function fields_forbid($fields_id = 0, $relation_id = 0)
    {
        return self::$fields->forbid($fields_id, $relation_id, 'user');
    }

    /**
     * 扩展字段 添加 / 修改
     */
    function fields_form($id = 0)
    {
        return self::$fields->form($id, 'user');
    }

    /**
     * 扩展字段 删除
     */
    public function fields_delete($id = [])
    {
        return self::$fields->delete($id, 'user');
    }

    /**
     * 批量改变字段状态
     */
    function fields_status($id = [], $status = '', $relation_id = 0)
    {
        return self::$fields->status($id, $status, $relation_id);
    }

}
