<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class ListAction extends SoftAction
{
    public function run()
    {
        $sortKey = array(
            1 => 'id',
            2 => 'download',
            3 => 'comments',
            4 => 'good',
        );
        $keyMap = array(
            1 => '最新',
            2 => '下载',
            3 => '评论',
            4 => '好评',
        );

        $pid = S::gp('pid', 'G', 2);
        $cid = S::gp('cid', 'G', 2);
        $tid = S::gp('tid', 'G', 2);
        $sort = empty($_GET['sort']) || !key_exists($_GET['sort'], $sortKey) ? 1 : S::gp('sort', 'G');
        $order = $sortKey[$sort];
        $tag = $keyMap[$sort];

        $addCondition = $mergeArray = array();
        if ($pid)
        {
            $pName = SoftPlatforms::getName($pid);
            $addCondition[] = 'pid = '.$pid;
            $mergeArray['pid'] = $pid;
        }
        if ($cid)
        {
            $cName = softCategoryName($cid);
            $addCondition[] = 'cid = '.$cid;
            $mergeArray['cid'] = $cid;
        }

        $where = '';
        if (array() !== $addCondition)
        {
            $where = ' WHERE '.implode(' AND ', $addCondition);
        }
        $count = $this->db()->getValue('SELECT COUNT(*) FROM '.SoftContents::table().$where);
        $pageObj = new iPage();
        $pageObj->setPageSize(10);
        $pageObj->setTotalRecord($count);

        $sql = 'SELECT id,cid,date,name FROM '.SoftContents::table().$where.' ORDER BY '.$order.' DESC '.S::sqlLimit($pageObj->getOffset(), $pageObj->getPageSize());
        $softs = $this->db()->setQueryString($sql)->find();

        $floor = $pageObj->getFloor();

        $navArray = array();
        foreach ($keyMap as $key => $value)
        {
            if ($sort == $key)
            {
                $navArray[] = $value;
            }
            else
            {
                $navArray[] = ilink($value, url('system', array_merge(array('s'=>'soft','a'=>'list','sort'=>$key), $mergeArray)));
            }
        }

        $this->getController()->render('list', array(
                'softs' => $softs,
                'floor' => $floor,
                'pageObj' => $pageObj,
                'navArray' => $navArray,
                'tag' => $tag,
                'pName' => $pName,
                'cName' => $cName,
            )
        );
    }
}