<?php

require_once __DIR__ . '/core.php';

if ($con->request->isAjax()) {
    $action = $con->request->post('action');
    switch ($action) {
        case 'list':
            // 获取分页
            $limit = $con->request->post(['page', 'limit'], FILTER_VALIDATE_INT);
            // 查询数据
            $data = $con->db->table('user')->find('id, u_account, u_name, u_image, u_email, u_phone, u_date, u_ip')
                ->where('id > ?', [1])
                ->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
            // 处理数据
            $users = [];
            foreach ($data as $index => $user) {
                $users[$index]['seq'] = $index + 1;
                $users[$index]['id'] = $user['id'];
                $users[$index]['username'] = $user['u_account'];
                $users[$index]['image'] = '<img id="image-'.($index + 1).'" src="'.loadImage($user['u_image'], $hel).'" alt="头像" height="27">';
                foreach (['name', 'email', 'phone', 'date'] as $key) {
                    $users[$index][$key] = $user['u_' . $key];
                }
                $users[$index]['ip'] = long2ip($user['u_ip']);
            }
            unset($data);
            // 统计总数
            $count = $con->db->table('user')->count('u_account <> ?', ['administrator'], 'u_account');
            // 返回数据
            $data = [
                'msg'   => '',
                'code'  => 0,
                'count' => $count,
                'data'  => $users
            ];
            $con->json($data);
            break;
        case 'edit':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 获取更新用户
            $account = $con->db->table('user')->find('u_account')->where('id = ?', [$unique])->one();
            if ($account) {
	            $refresh = $con->session->get(base64_encode('sem-cms_manager_index')) === base64_encode($account['u_account']);
            } else {
	            $con->json(['code' => false, 'err' => '用户不存在']);
	            break;
            }
            // 取出数据
            $data = $con->request->post(['username', 'password', 'name', 'image', 'email', 'phone']);
            // 处理数据
            if ('' == $data['username']) {
                // 账号为空
                $con->json(['code' => false, 'err' => '账号不能为空']);
                break;
            }
            $user['u_account'] = $data['username'];
            if ('' != $data['email'] && !$hel->isEmail($data['email'])) {
                // 邮箱非法
                $con->json(['code' => false, 'err' => '邮箱格式错误，请输入正确邮箱']);
                break;
            }
            $user['u_email'] = $data['email'];
            if ('' != $data['phone'] && !$hel->isPhone($data['phone'])) {
                // 电话非法
                $con->json(['code' => false, 'err' => '电话格式错误，请输入中国大陆手机号码']);
                break;
            }
            $user['u_phone'] = $data['phone'];
            if ('' != $data['password']) {
                $user['u_ciphers'] = base64_encode(md5(base64_encode(sha1($data['password']))));
            }
            if ('' != $data['image']) {
                $user['u_image'] = $data['image'];
            }
            $user['u_name'] = $data['name'];
            // 更新数据库
            $row = $con->db->table('user')->update($user, 'id = ?', [$unique])->row();
            if (is_numeric($row)) {
                $con->json(['code' => true, 'refresh' => $refresh]);
            } else {
                $con->json(['code' => false, 'err' => '修改失败']);
            }
            break;
        case 'drop':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 删除数据
            $row = $con->db->table('user')->delete('id = ?', [$unique])->row();
            $code = 1 === $row;
            $con->json(['code' => $code]);
            break;
        case 'insert':
            // 取出数据
            $data = $con->request->post(['username', 'password', 'name', 'image', 'email', 'phone']);
            // 处理数据
            if ('' == $data['username']) {
                // 账号为空
                $con->json(['code' => false, 'err' => '账号不能为空']);
                break;
            }
            $count = $con->db->table('user')->find('id')->where('u_account = ?', [$data['username']])->one();
            if (false != $count) {
                // 账号重复
                $con->json(['code' => false, 'err' => '账号已存在，请重试']);
                break;
            }
            $user['u_account'] = $data['username'];
            if ('' == $data['password']) {
                // 密码为空
                $con->json(['code' => false, 'err' => '密码不能为空']);
                break;
            }
            $user['u_ciphers'] = base64_encode(md5(base64_encode(sha1($data['password']))));
            if ('' != $data['email'] && !$hel->isEmail($data['email'])) {
                // 邮箱非法
                $con->json(['code' => false, 'err' => '邮箱格式错误，请输入正确邮箱']);
                break;
            }
            $user['u_email'] = $data['email'];
            if ('' != $data['phone'] && !$hel->isPhone($data['phone'])) {
                // 电话非法
                $con->json(['code' => false, 'err' => '电话格式错误，请输入中国大陆手机号码']);
                break;
            }
            $user['u_phone'] = $data['phone'];
            $user['u_image'] = $data['image'];
            $user['u_name'] = $data['name'];
            // 插入数据库
            $row = $con->db->table('user')->insert($user)->row();
            if (1 === $row) {
                $con->json(['code' => true]);
            } else {
                $con->json(['code' => false, 'err' => '添加失败']);
            }
            break;
        case 'delete':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 删除数据
            $row = $con->db->table('user')->delete('id IN ('.$unique.')')->row();
            $code = is_numeric($row);
            $con->json(['code' => $code]);
            break;
        case 'image':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 查找头像地址
            $name = null;
            // 保存上传文件
            $image = new \sc\Upload();
            if ($image->isImage()) {
                $path = $image->save('file/profile', $name);
                if (!$path) {
                    $con->json(['code' => false, 'err' => '保存失败']);
                } else {
                    $con->json(['code' => true, 'path' => $path]);
                }
            } else {
                $con->json(['code' => false, 'err' => '请上传图片文件']);
            }
            break;
        case 'access':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 取出用户角色
            $user_role = $con->db->table('user')->find('u_role')->where('id = ?', [$unique])->one();
            $user_role = $user_role ? explode(',', $user_role['u_role']) : [];
            // 生成权限列表
            $roles = $con->db->table('role')->find('id, pid, r_name')->where('id > 1 AND r_on = ?', [1])->all();
            $roles = $hel->subTree($roles, 1);
            $con->json(['html' => generate_role_tree($roles, $user_role)]);
            break;
        case 'role':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 取出数据
            $roles = $con->request->post('role');
            $roles = null == $roles ? '' : implode(',', $roles);
            // 重新分配权限
            $row = $con->db->table('user')->update(['u_role' => $roles], 'id = ?', [$unique])->row();
            $code = 1 === $row || 0 === $row;
            $con->json(['code' => $code]);
            break;
        default:break;
    }
} else {
    $con->render('user', ['host' => $hel->url(), 'path' => $hel->path(), 'crumb' => $breadcrumb]);
}

function generate_role_tree($roles, $user_role, $super = true)
{
    $html = $super ? '' : '<ul class="role">';
    foreach ($roles as $role) {
        $html .= $super ?
            '<div class="role"><input class="layui-form-switch" type="checkbox" name="role[]" value="'.$role['id'].'" title="<b>'.$role['r_name'].'</b>" lay-skin="primary" '.(in_array($role['id'], $user_role) ? 'checked' : '').'>' :
            '<li><input class="layui-form-switch" type="checkbox" name="role[]" value="'.$role['id'].'" title="'.$role['r_name'].'" lay-skin="primary" lay-filter="role" '.(in_array($role['id'], $user_role) ? 'checked' : '').'></li>';
        if (isset($role['sub'])) {
            $html .= generate_role_tree($role['sub'], $user_role, false);
        }
        $html .= $super ? '</div>' : '';
    }
    $html .= $super ? '</div>' : '</ul>';
    return $html;
}