<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class ForumAction extends BbsAction
{
    public function run()
    {
        $fid = S::gp('fid', 'G');
        $filter = S::gp('filter','G');

        // TODO 此处需要可以自定义分页数
        $pageSize = $this->getController()->isWebRequest() ? 30 : 20;
        $topCount = 0;
        $tFields = 'id,fid,subject,createdate,uid,username,topped,replies,hits,islock,isdigest,special,isupload,lastpost,type,date,lastpost_user,rating,ratings,ismark,markuid';
        $tTable = Threads::table();
        $forumAdd = $filterAdd = '';
        
        empty($fid) && $this->showMessage('非法操作,请返回');
        $forum = Forums::single()->getOne($fid);
        empty($forum) && $this->showMessage('不存在的版块');
        $this->isAllowVisit($fid);
        $forumSet = unserialize($forum['forumset']);
        
        if(isset($filter))
        {
            if($filter == 'digest')
            {
        		$filterAdd = ' AND isdigest = 1 ';
        	}
        	elseif($filter == 'type')
        	{
        	    $type = intval(S::gp('typeid','G'));
        	    $filterAdd = " AND `type`=$type";
        	}
        	else
        	{
        	    $filter = '';
        	}
        }
        else
        {
            $filter = '';
        }

        $isFilter = !empty($filter) && in_array($filter, array('digest', 'type'));
        $topThreads = Threads::single()->getTopped();
        !empty($topThreads) && $topCount = count(explode(',',$topThreads));

        $displayOrderAdd = !$isFilter && $topCount ? 'topped IN (0,1)' : 'topped IN (0,1,2,3)';
        $count = $this->db()->getValue('SELECT COUNT(*) FROM '.Threads::table().' WHERE fid='.$fid.$filterAdd.' AND ischeck = 1 AND isdelete = 0'.(empty($filter) ? ' AND topped >=0' : ''));
        $pageObj = new iPage();
        $pageObj->setPageSize($pageSize);
        $pageObj->setTotalRecord($count);
        
        $startLimit = ($pageObj->getCurrentPage() - 1) * $pageSize;
        if (($startLimit && $startLimit > $topCount) || !$topCount || $isFilter)
        {
            $topQuery = '';
            $sql = "SELECT {$tFields} FROM {$tTable} 
            		WHERE fid={$fid} {$filterAdd} AND ischeck = 1 AND isdelete = 0 AND {$displayOrderAdd}
            		ORDER BY topped DESC,lastpost DESC LIMIT ".($isFilter ? $startLimit : $startLimit - $topCount).",{$pageObj->getPageSize()}";
            $query = $this->db()->query($sql);
        }
        else
        {
            $sql = "SELECT {$tFields} FROM {$tTable} 
            		WHERE ischeck = 1 AND isdelete = 0 AND id IN ({$topThreads}) AND topped IN (2,3)
            		ORDER BY topped DESC,lastpost DESC LIMIT {$startLimit}, ".($topCount - $startLimit < $pageObj->getPageSize() ? $topCount - $startLimit : $pageObj->getPageSize());
            $topQuery = $this->db()->query($sql);
            $query = '';
            if($pageObj->getPageSize() - $topCount + $startLimit > 0)
            {
                $sql = "SELECT {$tFields} FROM {$tTable} 
            			WHERE fid={$fid} {$filterAdd} AND ischeck = 1 AND isdelete = 0 AND {$displayOrderAdd}
            			ORDER BY topped DESC,lastpost DESC LIMIT ".($pageObj->getPageSize() - $topCount + $startLimit);
                $query = $this->db()->query($sql);
            }
        }
        
        $threads = array();
        while (($topQuery && $thread = $this->db()->getArr($topQuery)) || ($query && $thread = $this->db()->getArr($query)))
        {
            $thread = $this->_threadPagination($thread);
            $threads[] = $this->analyzeType($thread, $forumSet['topictype']);
        }

        $isAllowPost = $this->isAllowPost($fid);
        $isAllowSearch = $this->isAllowSearch();
        $typeList = Forums::getTypeList($fid);
        
        if ($forum['type'] != 'category' && $forum['childid'])
        {
            $childs = Forums::single()->getChilds($fid);
        }

        $this->getController()->render('forum', array(
                'fid' => $fid,
                'forum' => $forum,
                'threads' => $threads,
                'pageObj' => $pageObj,
                'isAllowPost' => $isAllowPost,
                'isAllowSearch' => $isAllowSearch,
                'typeList' => $typeList,
                'childs' => $childs,
            )
        );
    }

    private function _threadPagination($thread)
    {
        $pageSize = Posts::$pageSize;
        if ($pageSize > $thread['replies'] || ($totalPage = ceil($thread['replies'] / $pageSize)) < 2)
        {
            return $thread;
        }
        
        $x = $totalPage > 6 ? 6 : $totalPage;
        $array = array();
        $string = '..';
        for ($i = 2; $i <= $x; $i++)
        {
            $array[] = $this->getController()->link($i, $this->getController()->url('system',array('s'=>'bbs','a'=>'thread','tid'=>$thread['id'],'page'=>$i)));
        }
        $string .= implode('', $array);
        $string .= $totalPage > 6 ? '...'.$this->getController()->link($totalPage, $this->getController()->url('system',array('s'=>'bbs','a'=>'thread','tid'=>$thread['id'], 'page'=>$totalPage))) : '';
        
        $thread['spagination'] = $string;
        
        return $thread;
    }
}