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

$id         = input('get.id/d');
$page       = Cnum(input('get.page/d'), 1, true, 1);
$desc       = Cnum(input('get.desc'), Cnum(set('replyorder'), 1, true, 0, 1), true, 0, 1);
$limit      = Cnum(set('replylistnum'), 10, true, 1);
$orderfield = input('get.orderfield/s');
if ('zannum' == $orderfield) {
    $orderfield = 'zannum desc,posttime';
} else {
    $orderfield = 'posttime';
}

$readdata = table('read')->where($id)->find();
if (!$readdata) {
    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;
    }
    set([
        'webtitle'       => '该主题已被删除或正在审核',
        'webkeywords'    => '',
        'webdescription' => '',
    ]);
    PkPopup('{
		content:"该主题已被删除或正在审核",
		icon:2,
		shade:1,
		nomove:1,
		hideclose:1
	}');
}
// $replypage = ceil(table('reply')->where('rid', $id)->count() / $limit);

//各种检测
if ((!InArray(usergroup('quanxian'), 'lookread') && usergroup('id')) || (!InArray(user('quanxian'), 'lookread') && !usergroup('id'))) {
    set([
        'webtitle'       => '提示',
        'webkeywords'    => '',
        'webdescription' => '',
    ]);
    PkPopup('{
		content:"您无权阅读文章",
		icon:2,
		shade:1,
		nomove:1,
		hideclose:1
	}');
}

//用户阅读权限的检测
if (!chkReadSortQx($readdata['sortid'], 'looklevel') || ((usergroup('id') && (Cnum($readdata['readlevel']) > Cnum(usergroup('readlevel')))) || (!usergroup('id') && (Cnum($readdata['readlevel']) > Cnum(user('readlevel')))))) {
    set([
        'webtitle'       => '提示',
        'webkeywords'    => '',
        'webdescription' => '',
    ]);
    PkPopup('{
		content:"您的阅读权限太低或您的用户组不被允许",
		icon:2,
		shade:1,
		nomove:1,
		hideclose:1
	}');
}

if (!isset($_SESSION['HS_LOOKREAD_' . $id]) || set('readlooknumaddtype')) {
    $_SESSION['HS_LOOKREAD_' . $id] = $readdata['looknum'];
    table('read')->update([
        'id'      => $id,
        'looknum' => $readdata['looknum'] + 1,
    ]);
}

//整片文章回复后查看的检测
if ($readdata['replyafterlook'] && user('id') != $readdata['uid'] && 1 != user('id')) {
    if (user('id')) {
        if (!table('reply')->where([
            'rid' => $readdata['id'],
            'uid' => user('id'),
        ])->find()) {
            $readdata['content'] = '<p class="pk-width-all pk-padding-15 pk-text-center pk-text-default" style="border:dashed 1px orangered">该文章设置了回复查看，请回复后查看内容</p>';
        }
    } else {
        $readdata['content'] = '<p class="pk-width-all pk-padding-15 pk-text-center pk-text-default" style="border:dashed 1px orangered">您需要<a target="_blank" class="pk-text-primary pk-hover-underline" href="' . ReWriteURL('login', '', 'referer=' . urlencode(sys('location'))) . '">登录</a>并回复后才可以查看该文章内容</p>';
    }
}

//部分内容回复后可见
if (strpos($readdata['content'], '<p class="PytReplylook">') !== false && user('id') != $readdata['uid'] && 1 != user('id')) {
    $_ls = '';
    if (user('id')) {
        if (!table('reply')->where([
            'rid' => $readdata['id'],
            'uid' => user('id'),
        ])->find()) {
            $_ls = '<p class="PytReplylook">该内容设置了回复查看，请回复后查看隐藏内容</p>';
        }
    } else {
        $_ls = '<p class="PytReplylook">您需要<a target="_blank" class="pk-text-primary pk-hover-underline" href="' . ReWriteURL('login', '', 'referer=' . urlencode(sys('location'))) . '">登录</a>并回复后才可以查看隐藏的内容</p>';
    }
    if ($_ls) {
        $readdata['content'] = preg_replace('/\<p class="PytReplylook"\>[\s\S]+?\<\/p\>/', $_ls, $readdata['content']);
    }
}

//文章所属分类
$sortid            = $readdata['sortid'];
$forumdata         = table('readsort')->where($sortid)->find();
$readdata['forum'] = $forumdata;
temp('bkadmin', InArray($forumdata['adminuids'], user('id')) && user('id'));
if ($readdata['uid']) {
    $readdata['user']      = table('user')->where($readdata['uid'])->find();
    $readdata['usergroup'] = table('usergroup')->where($readdata['user']['groupid'])->find();
} else {
    $readdata['user'] = JsonData(set('guestdata'));
}
// 引用数据，后续模板设计需要
$readdata['forumdata']     = &$readdata['forum'];
$readdata['userdata']      = &$readdata['user'];
$readdata['usergroupdata'] = &$readdata['usergroup'];

// 是否显示最后编辑时间
if (set('showreadlastedittime') && $readdata['lastedituid']) {
    if ($readdata['lastedituid'] == $readdata['uid']) {
        $lasteditud = $readdata['user'];
    } else {
        $lasteditud = table('user')->where($readdata['lastedituid'])->find();
    }
    $readdata['content'] .= '<div class="readedittime" style="text-align:center;font-size:12px;margin:15px 0;padding:5px 0;letter-spacing:1px;color:#aaa">本文章最后由 <a target="_blank" class="pk-hover-underline" href="' . ReWriteURL('center', 'uid=' . $lasteditud['id']) . '">' . $lasteditud['username'] . '</a> 于 <span>' . date('Y-m-d H:i', $readdata['lastedittime']) . '</span> 编辑</div>';
}

// 是否好友
$readdata['is_friend'] = true;
if (strpos(user('friends'), '_' . $readdata['uid'] . '_') === false) {
    $readdata['is_friend'] = false;
}
// 是否关注
$readdata['is_idol'] = true;
if (strpos(user('idol'), '_' . $readdata['uid'] . '_') === false) {
    $readdata['is_idol'] = false;
}
// 是否收藏
$readdata['is_collect'] = true;
if (strpos(user('collect'), '_' . $readdata['id'] . '_') === false) {
    $readdata['is_collect'] = false;
}

$replylist   = [];
$topreplyids = [];
if (1 == $page) {
    //==============================置顶回复处理===========================
    $replylist = table('reply')->where([
        'rid' => $readdata['id'],
        'top' => 1,
    ])->select();
    foreach ($replylist as $v) {
        $topreplyids[] = $v['id'];
    }
}
//==============================普通回复处理===========================
// $replypage = ceil(table('reply')->where('rid', $readdata['id'])->count() / $limit);
$replylist = array_merge($replylist, table('reply')->where('rid', $readdata['id'])->page($page, $limit)->order($orderfield, $desc ? 'desc' : 'asc')->select());
if ($replylist) {
    $_topreplyids = [];
    foreach ($replylist as $k => $replydata) {
        // 是否在置顶评论里面
        if (in_array($replydata['id'], $topreplyids)) {
            if (in_array($replydata['id'], $_topreplyids)) {
                unset($replylist[$k]);
                continue;
            } else {
                $_topreplyids[] = $replydata['id'];
            }
        }
        if ($replydata['uid']) {
            $replylist[$k]['user']      = table('user')->where($replydata['uid'])->find();
            $replylist[$k]['usergroup'] = table('usergroup')->where($replylist[$k]['user']['groupid'])->find();
        } else {
            $replylist[$k]['user'] = JsonData(set('guestdata'));
        }

        // 引用数据，后续模板设计需要
        $replylist[$k]['userdata']      = &$replylist[$k]['user'];
        $replylist[$k]['usergroupdata'] = &$replylist[$k]['usergroup'];

        if ($readdata['lookonlyme'] && (!user('id') || !InArray("{$readdata['uid']},{$replydata['uid']}", user('id')))) {
            $replylist[$k]['content'] = '<p class="pk-width-all pk-padding-15 pk-text-center pk-text-default" style="border:dashed 1px orangered">该回复仅文章作者自己可见</p>';
        }
        // 是否好友
        $replylist[$k]['is_friend'] = true;
        if (strpos(user('friends'), '_' . $replydata['uid'] . '_') === false) {
            $replylist[$k]['is_friend'] = false;
        }
        // 是否关注
        $replylist[$k]['is_idol'] = true;
        if (strpos(user('idol'), '_' . $replydata['uid'] . '_') === false) {
            $replylist[$k]['is_idol'] = false;
        }
        // 楼中楼
        if (set('replyreplyopen')) {
            $replylist[$k]['content'] .= '<div class="reply-reply-box"><div class="reply-reply-textbar"><span class="' . ($replydata['replycount'] ? '' : 'pk-hide') . '">共' . $replydata['replycount'] . '条回复</span><a href="javascript:;" data-rid="' . $replydata['id'] . '" data-page="1" class="show ' . ($replydata['replycount'] ? '' : 'pk-hide') . '">,点击查看</a><a href="javascript:;" data-rid="' . $replydata['id'] . '" class="reply ' . (InArray(getUserQX(), 'postreply') ? '' : 'pk-hide') . '" data-fnum="' . $replydata['fnum'] . '">回复</a></div><div class="reply-reply-list" data-rid="' . $replydata['id'] . '"></div></div>';
        }
    }
}

$is_null = false;
if (!$replylist) {
    $is_null = true;
}

//seo重塑
$title       = str_replace('"', ' ', strip_tags($readdata['title']));
$keywords    = str_replace('"', ' ', strip_tags($readdata['label']));
$description = str_replace('"', ' ', strip_tags($readdata['content']));
$description = str_replace(["\t", "\r", "\n"], ' ', $description);
$description = trim(preg_replace('/[ ]+/', ' ', $description));
$description = mb_substr(htmlspecialchars($description, ENT_QUOTES), 0, 100);
if (set('readseokeywordsaddtitle') && $keywords && mb_strlen($keywords) < 15) {
    $keywords .= ',' . $title;
}
set('webkeywords', $keywords ? $keywords : $title);
set('webdescription', $description ? $description : $title);
$title .= (1 != $page ? "-第{$page}页" : '');
if (set('readseoaddwords')) {
    $title .= "-{$forumdata['title']}";
    if (set('webaddedwords')) {
        $title .= '-' . set('webaddedwords');
    }
}
set('webtitle', $title);

// 上下页url
$q = '';
if (input('get.orderfield/s')) {
    $q .= "&orderfield={$orderfield}";
}
if (input('get.desc')) {
    $q .= "&desc=" . input('get.desc/d');
}
$q && $q = substr($q, 1);
$syy     = $page - 1;
if ($syy < 1) {
    $syy = 1;
}
$syyurl = ReWriteURL('read', "id={$readdata['id']}&page=" . $syy, $q);
$xyy    = $page + 1;
// if ($xyy > $readpage) {
//     $xyy = $readpage;
// }
$xyyurl = ReWriteURL('read', "id={$readdata['id']}&page=" . $xyy, $q);
$varurl = ReWriteURL('read', "id={$readdata['id']}&page=[page]", $q);

// 加载楼中楼驱动
if (set('replyreplyopen')) {
    setConcat('embed_head', '<link rel="stylesheet" href="template/puyuetianUI/css/replyreply.css"><script src="template/puyuetianUI/js/replyreply.js"></script>');
}

// 输出模板
gConcat('htmlcode.output', template('read', [
    'readdata'   => $readdata,
    'replylist'  => $replylist,
    'page'       => $page,
    'syy'        => $syy,
    'xyy'        => $xyy,
    'syyurl'     => $syyurl,
    'xyyurl'     => $xyyurl,
    'varurl'     => $varurl,
    'limit'      => $limit,
    // 'replypage'  => $replypage,
    'orderfield' => $orderfield,
    'desc'       => $desc,
    'is_null'    => $is_null,
]));
