<?php
if (!defined('puyuetian')) {
    exit('403');
}

$uid   = input('get.uid/d');
$page  = cnum(input('get.page/d'), 1, true, 1);
$limit = cnum(input('get.limit/d'), 20, true, 1, 500);
$type  = input('get.type/s');
if (InArray('addcollect,delcollect,addfriend,delfriend,addidol,delidol', $type)) {
    $uid = user('id');
}

if ($uid && user('id') != $uid) {
    if (!InArray(getUserQX(), 'lookuser')) {
        if (user('id')) {
            $txt = '你无权浏览用户资料';
            if ($type) {
                v8Error($txt);
            }
            PkPopup('{
                title:"警告",
                content:"' . $txt . '",
                icon:2,
                close:function(){
                    location.href="index.php"
                },
                hideclose:1,
                shade:1
            }');
        } else {
            if ($type) {
                v8Error('请先登录');
            }
            ExitGourl(ReWriteURL('login', '', 'referer=' . urlencode(sys('location'))));
        }
    }
    $user = table('user')->where($uid)->find();
    if (!$user) {
        $txt = '不存在的用户';
        if ($type) {
            v8Error($txt);
        }
        if (404 == set('deletedreadshowtype')) {
            header('HTTP/1.1 404 Not Found');
            header('status: 404 Not Found');
            set([
                'webtitle'       => '404 Not Found',
                'webkeywords'    => '',
                'webdescription' => '',
            ]);
            g('htmlcode.main', template('error', true));
            template(g('template.main'));
            exit;
        }
        PkPopup('{
            content:"' . $txt . '",
            icon:0,
            close:function(){
                location.href="index.php"
            },
            hideclose:1,
            shade:1,
            nomove:1
        }');
    }
} else {
    if (user('id')) {
        $user = user();
    } else {
        if ($type) {
            v8Error('请先登录');
        }
        ExitGourl(ReWriteURL('login', '', 'referer=' . urlencode(sys('location'))));
    }
}

// 当前用户其他信息整理
$user['data'] = JsonData($user['data']);
$group        = table('usergroup')->where($user['groupid'])->find();
if ($group) {
    $user['usergroupname'] = $group['usergroupname'];
    if (!$group['readlevelmax'] || ($group['readlevelmax'] && $group['readlevel'] > $user['readlevel'])) {
        $user['readlevel'] = $group['readlevel'];
    }
    $user['usergroupquanxian'] = $group['quanxian'];
    $user['groupdata']         = $group;
}
// 生日
if ($user['birthday']) {
    $user['birthday'] = substr($user['birthday'], 0, 4) . '-' . substr($user['birthday'], 4, 2) . '-' . substr($user['birthday'], 6, 2);
} else {
    $user['birthday'] = '';
}

// 是否好友
$user['is_friend'] = true;
if (strpos(user('friends'), '_' . $user['id'] . '_') === false) {
    $user['is_friend'] = false;
}
// 是否关注
$user['is_idol'] = true;
if (strpos(user('idol'), '_' . $user['id'] . '_') === false) {
    $user['is_idol'] = false;
}
$user['readcount']  = table('read')->where('uid', $user['id'])->count();
$user['replycount'] = table('reply')->where('uid', $user['id'])->count();
$user['edit']       = 0;
if (user('id') == $user['id'] || user('id') == 1) {
    $user['edit'] = 1;
}

if (!$user['edit']) {
    // 隐私检测
    if ($type && $user['data']['privacysettings']) {
        v8Error('该用户设置了隐私无法查看');
    }
    // 权限检测
    if (InArray('getjtrecord,getmsglist,lookmsg,save,saveuserhead', $type)) {
        v8Error('无权操作');
    }
}

switch ($type) {
    case 'getreadlist':
        $data = table('read')->field('id,title,sortid,uid,posttime')->where([
            'uid' => $user['id'],
        ])->page($page, $limit)->order('id desc')->select();
        foreach ($data as $k => $v) {
            $data[$k]['url']              = ReWriteURL('read', "id={$v['id']}&page=1");
            $data[$k]['forumdata']        = table('readsort')->field('id,title')->where($v['sortid'])->find();
            $data[$k]['forumdata']['url'] = ReWriteURL('forum', "id={$data[$k]['forumdata']['id']}");
        }
        v8Success('ok', [
            'list'  => $data,
            'count' => table('read')->where('uid', $user['id'])->count(),
        ]);
        break;
    case 'getreplylist':
        $data = table('reply')->field('id,fnum,rid,uid,posttime')->where([
            'uid' => $user['id'],
        ])->page($page, $limit)->order('id desc')->select();
        foreach ($data as $k => $v) {
            $data[$k]['readdata']        = table('read')->field('id,title,sortid,lookonlyme')->where($v['rid'])->find();
            $data[$k]['readdata']['url'] = ReWriteURL('read', "id={$data[$k]['readdata']['id']}&page=1");
        }
        v8Success('ok', [
            'list'  => $data,
            'count' => table('reply')->where('uid', $user['id'])->count(),
        ]);
        break;
    case 'getfriends':
    case 'getfans':
    case 'getidol':
        $key        = str_replace('get', '', $type);
        $frienduids = explode('__', substr($user[$key], 1, strlen($user[$key]) - 2));
        $data       = table('user')->field('id,username,nickname,sign,sex')->where([
            'id' => ['IN', $frienduids],
        ])->page($page, $limit)->order('id desc')->select();
        foreach ($data as $k => $v) {
            $data[$k]['url'] = ReWriteURL('center', "uid={$v['id']}");
        }
        v8Success('ok', [
            'list'  => $data,
            'count' => table('user')->where('id', 'IN', $frienduids)->count(),
        ]);
        break;
    case 'getcollect':
        $readids = explode('__', substr($user['collect'], 1, strlen($user['collect']) - 2));
        $data    = table('read')->field('id,title,sortid,uid,posttime')->where([
            'id' => ['IN', $readids],
        ])->page($page, $limit)->order('id desc')->select();
        foreach ($data as $k => $v) {
            $data[$k]['url']              = ReWriteURL('read', "id={$v['id']}&page=1");
            $data[$k]['forumdata']        = table('readsort')->field('id,title')->where($v['sortid'])->find();
            $data[$k]['forumdata']['url'] = ReWriteURL('forum', "id={$data[$k]['forumdata']['id']}");
        }
        v8Success('ok', [
            'list'  => $data,
            'count' => table('read')->where('id', 'IN', $readids)->count(),
        ]);
        break;
    case 'getjtrecord':
        $data = table('jtrecord')->where([
            'uid' => $user['id'],
        ])->page($page, $limit)->order('id desc')->select();
        v8Success('ok', [
            'list'  => $data,
            'count' => table('jtrecord')->where('uid', $user['id'])->count(),
        ]);
        break;
    case 'getmsglist':
        $data = table('user_message')->where([
            'uid' => $user['id'],
        ])->page($page, $limit)->order('islook asc,id desc')->select();
        foreach ($data as $k => $v) {
            if (!$v['fid']) {
                continue;
            }
            $data[$k]['from_userdata'] = table('user')->field('id,username,nickname')->where($v['fid'])->find();
            $data[$k]['from_userurl']  = ReWriteURL('center', "uid={$v['fid']}");
        }
        v8Success('ok', [
            'list'  => $data,
            'count' => table('user_message')->where('uid', $user['id'])->count(),
        ]);
        break;
    case 'lookmsg':
        $mid   = input('get.id/d');
        $where = [
            'uid' => $uid,
        ];
        if ($mid) {
            $where['id'] = $mid;
        }
        table('user_message')->where($where)->update([
            'islook' => 1,
        ]);
        v8Success('ok');
        break;
    case 'saveuserhead':
        $userhead   = substr(input('post.userhead/s'), 22);
        $uploadsize = Cnum(set('uploadheadsize'), 512, true, 0);
        if (!$userhead) {
            v8Error('选择的图片文件无效');
        }
        if (strlen($userhead) > $uploadsize * 1024) {
            v8Error("头像图片不能超过{$uploadsize}KB");
        }
        if (!InArray(getUserQX(), 'uploadhead')) {
            v8Error('您无权上传头像');
        }
        if (file_put_contents(PK_USERHEAD_PATH . "{$uid}.png", base64_decode($userhead)) === false) {
            v8Error('头像保存失败');
        }
        v8Success('头像更换成功', true);
        break;
    case 'save':
        $fields = 'sex,nickname,sign,qq,weixin,adress,email,phone,password,data-privacysettings,birthday';
        $post   = input('post.');
        foreach ($post as $k => $v) {
            if (!InArray($fields, $k)) {
                v8Error('非法参数"' . $k . '"');
            }
            if ('sex' == $k) {
                $v = Cstr($v, false, 'gbs', 1, 1);
                if (!$v) {
                    v8Error('性别参数非法');
                }
            }
            if (InArray('nickname,sign,adress', $k)) {
                $v = strip_tags(preg_replace('/[\x00-\x1F\x7F\s]+/u', '', $v));
                switch ($k) {
                    case 'nickname':
                        if (mb_strlen($v) < 1 || mb_strlen($v) > 10) {
                            v8Error('昵称限制在1-10个字之间');
                        }
                        break;
                }
                //检测用户信息是否包含违禁词
                if (set('banregwords')) {
                    foreach (explode(',', set('banregwords')) as $w) {
                        if (!$w) {
                            continue;
                        }
                        if (strpos($v, $w) !== false) {
                            v8Error('内容包含违禁词“' . $w . '”，请修改后重试');
                        }
                    }
                }
            }
            if ('qq' == $k) {
                $v = Cnum($v, false, true, 10000, 99999999999);
                if (!$v) {
                    v8Error('QQ号格式错误');
                }
            }
            if ('weixin' == $k) {
                $v = Cstr($v, false, g('string.safechars') . '-', 6, 20);
                if (!$v) {
                    v8Error('微信号格式错误');
                }
            }
            if ('phone' == $k) {
                $v = Cnum($v, false, true, 13000000000, 19999999999);
                if (!$v) {
                    v8Error('手机号格式错误');
                }
                if (table('user')->where([
                    'phone' => $v,
                    'id'    => ['<>', $uid],
                ])->find()) {
                    v8Error('该手机号已存在');
                }
            }
            if ('email' == $k) {
                $v = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
                if (!$v) {
                    v8Error('邮箱格式错误');
                }
                if (table('user')->where([
                    'email' => $v,
                    'id'    => ['<>', $uid],
                ])->find()) {
                    v8Error('该邮箱已存在');
                }
            }
            if ('password' == $k) {
                if (strlen($v) < 5) {
                    v8Error('密码不能小于5位');
                }
                if (strlen($v) > 16) {
                    v8Error('密码不能大于16位');
                }
                $v = md5($v);
            }
            if ('birthday' == $k) {
                $v = cnum(str_replace(['/', '-'], '', $v));
                if (strlen($v) != 8) {
                    v8Error('生日格式错误');
                }
            }
            if (mb_strlen($v) > 100) {
                v8Error('内容不能超过100个字');
            }
            $post[$k] = $v;
            if ('data-privacysettings' == $k) {
                $v            = Cnum($v);
                $data         = table('user')->where($uid)->find('data');
                $data         = JsonData($data, 'privacysettings', $v);
                $post['data'] = $data;
                unset($post['data-privacysettings']);
            }
        }
        if (!table('user')->where($uid)->update($post)) {
            v8Error(table()->error());
        }
        v8Success('ok');
        break;
    case 'addidol':
        $_uid = input('get.uid/d');
        if (user('id') == $_uid) {
            v8Error('自己不能关注自己');
        }
        if (strpos(user('idol'), "_{$_uid}_") !== false) {
            v8Error('你已经关注过Ta了');
        }
        $userdata = table('user')->where($_uid)->find();
        if (!$userdata) {
            v8Error('关注的用户不存在');
        }
        table('user')->update([
            'id'   => user('id'),
            'idol' => user('idol') . "_{$_uid}_",
        ]);
        table('user')->update([
            'id'   => $_uid,
            'fans' => $userdata['fans'] . '_' . user('id') . '_',
        ]);
        v8Success('关注成功');
        break;
    case 'delidol':
        $_uid = input('get.uid/d');
        if (strpos(user('idol'), "_{$_uid}_") === false) {
            v8Error('你未关注该用户');
        }
        table('user')->update([
            'id'   => user('id'),
            'idol' => str_replace("_{$_uid}_", '', user('idol')),
        ]);
        $userdata = table('user')->where($_uid)->find();
        if ($userdata) {
            table('user')->update([
                'id'   => $_uid,
                'fans' => str_replace('_' . user('id') . '_', '', $userdata['fans']),
            ]);
        }
        v8Success('取关成功');
        break;
    case 'addfriend':
        $_uid = input('get.uid/d');
        if (user('id') == $_uid) {
            v8Error('自己不能添加自己');
        }
        if (strpos(user('friends'), "_{$_uid}_") !== false) {
            v8Error('你已经添加过Ta了');
        }
        if (!table('user')->where($_uid)->find()) {
            v8Error('添加的用户不存在');
        }
        table('user')->update([
            'id'      => user('id'),
            'friends' => user('friends') . "_{$_uid}_",
        ]);
        v8Success('添加成功');
        break;
    case 'delfriend':
        $_uid = input('get.uid/d');
        if (strpos(user('friends'), "_{$_uid}_") === false) {
            v8Error('你未添加该用户');
        }
        table('user')->update([
            'id'      => user('id'),
            'friends' => str_replace("_{$_uid}_", '', user('friends')),
        ]);
        v8Success('删除成功');
        break;
    case 'addcollect':
        //收藏这里的uid为文章的id
        $_rid = input('get.uid/d');
        if (strpos(user('collect'), "_{$_rid}_") !== false) {
            v8Error('你已经收藏过该文章了');
        }
        $readdata = table('read')->where($_rid)->find();
        if (!$readdata) {
            v8Error('收藏的文章不存在');
        }
        table('user')->update([
            'id'      => user('id'),
            'collect' => user('collect') . "_{$_rid}_",
        ]);
        v8Success('收藏成功');
        break;
    case 'delcollect':
        //收藏这里的uid为文章的id
        $_rid = input('get.uid/d');
        if (strpos(user('collect'), "_{$_rid}_") === false) {
            v8Error('你未收藏该文章');
        }
        table('user')->update([
            'id'      => user('id'),
            'collect' => str_replace("_{$_rid}_", '', user('collect')),
        ]);
        v8Success('取消成功');
        break;
    default:
        # code...
        break;
}

//seo优化
set([
    'webkeywords'    => "{$user['nickname']},{$user['username']}",
    'webdescription' => $user['sign'],
    'webtitle'       => (user('id') == $user['id'] ? '我的资料' : "{$user['username']}的个人主页") . (set('webaddedwords') ? '-' . set('webaddedwords') : ''),
]);

gConcat('htmlcode.output', template('center', [
    'user'  => $user,
    'infos' => $infos,
]));
