<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class IndexAction extends ForumAction
{
    public function run()
    {
        $forumInfo = $this->forumInfo();
        $bookInfo = $this->bookInfo();
        
        $pageSize = 10;
        $posts = $condition = array();
        $do = trim(S::gp('do','G'));
        $filter = trim(S::gp('filter','G'));

        !empty($filter) && !in_array($filter, array('digest','advance')) && $filter = '';
        
        if ('time' == $do)
        {
            $this->getController()->render('time', array('bookid'=>$this->id(), 'forumInfo'=>$forumInfo));
            exit(0);
        }
        if (!$bookInfo['bookforum'])
        {
            $message[] = '本书还未开通书友会，是否现在' .ilink('开通', url('system',array('s'=>'forum','a'=>'open','id'=>$this->id()))) . '？';
            $this->showMessage($message);
        }

        switch ($filter)
        {
            case 'digest':
                $condition[] = '`digest` = 1';
                break;
            case 'advance':
                $condition[] = '`isadvance` = 1';
                break;
        }
        
        if (isset($_GET['start']) && preg_match('/^2[0-9]{3}-[0-9]{2}-[0-9]{2}$/i', trim($_GET['start'])))
        {
            $start = trim(S::gp('start','G'));
            $condition[] = "`date` BETWEEN '{$start}'";
        
            if (isset($_GET['end']) && preg_match('/^2[0-9]{3}-[0-9]{2}-[0-9]{2}$/i', trim($_GET['end'])) && $_GET['end'] >= $start)
            {
                $end = trim(S::gp('end','G'));
            }
            else
            {
                $end = date('Y-m-d');
            }
            $condition[] = "'{$end}'";
        }

        if ($forumInfo['shard'])
        {
            $countSqlAdd = array() === $condition ? '' : ' WHERE '.implode(' AND ', $condition);
            $count = $this->db()->getValue('SELECT COUNT(*) AS c FROM '.BookPost::table($this->id()).$countSqlAdd);
        }
        else
        {
            $countSqlAdd = array() === $condition ? '' : (' AND ' . implode(' AND ', $condition));
            $count = $this->db()->getValue('SELECT COUNT(*) AS c FROM '.BookPost::table($this->id())." WHERE bookid = {$this->id()}" . $countSqlAdd);
        }

        $pageObj = new iPage();
        $pageObj->setTotalRecord($count);
        $pageObj->setPageSize($pageSize);

        $sqlAdd = array() === $condition ? '' : ' AND ' . implode(' AND ', $condition);
        $sql = 'SELECT
                    `bookpostsid`, message, b.`uid`, `createdate`, `digest`, `applydigest`,`isadvance`,floor
                FROM
                    `'.BookPost::table($this->id())."` AS b
                WHERE
                     `bookid` = '{$this->id()}' {$sqlAdd} AND bookpostsid IN (SELECT bookpostsid FROM ".BookPost::table($this->id())." WHERE bookid = {$this->id()} {$sqlAdd} ORDER BY b.lastpost DESC)
                ORDER BY b.`lastpost` DESC LIMIT {$pageObj->getOffset()},{$pageObj->getPageSize()}";
        $result = $this->db()->setQueryString($sql)->find();

        foreach ($result as $rows)
        {
            $rows['message'] = $this->getController()->filter(sFilter($rows['message']));
            $rows['prefix'] = $rows['digest'] ? '[<b>精</b>]' : '';
            
            $memberInfo = Members::single()->getOneCache($rows['uid']);
            
            if (!empty($memberInfo['medals']))
            {
                $rows['medals'] = iMedals::single()->getMedalsString($memberInfo['medals']);
            }

            if ($rows['isadvance'])
            {
                $rows['prefix'] .= '[<b>高级</b>]';
                $rows['message'] = preg_replace('/\[[a-z]{3}=\d+\]/i', '', $rows['message']);
                if (mb_strlen($rows['message'],'utf8') > 50)
                {
                    $rows['message'] = mb_substr($rows['message'], 0, 50, 'utf-8');
                }
                $rows['message'] .= ilink('...详细', $this->getController()->url('system',array('s'=>'forum','c'=>'advance','a'=>'read','id'=>$this->id(),'cid'=>$rows['bookpostsid'])));
            }
            else
            {
                $rows['message'] = iubb($rows['message']);
            }
            $posts[] = $rows;
        }
        $floor = $pageObj->getFloor();
        
        $superManagers = $this->superManagers();
        $bookManagers = $this->bookManagers();
        
        $sticks = getForumStick($this->id());
        $stick = '';
        if (!empty($sticks))
        {
            $stick = $sticks[0];
        }
        $style = isset($_SESSION['user']['style']) ? 1 : 0;
        
        $advancePosts = getAdvancePostBookId($this->id());
        $forumRecommend = getForumRecommend();
        
        $floorSet = unserialize($forumInfo['floor']);

        $this->getController()->render('index',array(
                'bookid' => $this->id(),
                'level' => $this->level(),
                'forumInfo' => $forumInfo,
                'todaypost' => $forumInfo['todayposts'],
                'floorSet' => $floorSet,
                'bookInfo' => $bookInfo,
                'style' => $style,
                'posts' => $posts,
                'advancePosts' => $advancePosts,
                'superManagers' => $superManagers,
                'bookManagers' => $bookManagers,
                'stick' => $stick,
                'floor' => $floor,
                'filter' => $filter,
                'pageObj' => $pageObj,
                'forumRecommend' => $forumRecommend,
            )
        );
    }
}