<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class BcartAction extends MemberAction
{
    public function run()
    {
        $uid = $_GET['uid'] ? S::gp('uid', 'G', 2) : $this->uid();
        $isSelf = $uid == $this->uid();
        $pageSize = 10;

        if ('down' == $_GET['do'])
        {
            $id = S::gp('id', 'G', 2);
            $favorite = $this->db()->select()->from(Ufavorites::table())->where(array('fid'=>$id))->find(true);
            if (empty($favorite))
            {
                throw new iSystemException('不存在的书单收藏');
            }
            if ($favorite['uid'] != $this->uid())
            {
                throw new iSystemException('这个书单收藏不属于你');
            }
            if (1 == $_GET['confirm'])
            {
                $this->db()->delete(Ufavorites::table())->where(array('fid'=>$id))->q();
                iforward(url('system', array('s'=>'member','c'=>'my','a'=>'bcart')));
            }
            else
            {
                $message[] = '确定要删除吗？删除后将不可恢复！';
                $message[] = ilink('删除',url('system',array('s'=>'member','c'=>'my','a'=>'bcart','do'=>'down','id'=>$id,'confirm'=>1))).'|'.ilink('取消',url('system',array('s'=>'member','c'=>'my','a'=>'bcart')));
                $this->showMessage($message);
            }
        }
        
        $count = $this->db()->getValue('SELECT COUNT(*) FROM '.Ufavorites::table().' AS uf INNER JOIN '.Bcarts::table().' AS b ON b.id = uf.id WHERE type='.S::sqlEscape('bcart').' AND uf.uid='.S::sqlEscape($uid));
        $pageObj = new iPage();
        $pageObj->setPageSize($pageSize);
        $pageObj->setTotalRecord($count);

        $sql = 'SELECT fid,b.id,tid,b.uid,description,subject,favorite,comment,score,scores,bnum,b.createdate,updatedate FROM '.Ufavorites::table().' AS uf INNER JOIN '.Bcarts::table().' AS b ON b.id = uf.id WHERE type='.S::sqlEscape('bcart').' AND uf.uid = '.S::sqlEscape($uid).' ORDER BY fid DESC '.S::sqlLimit($pageObj->getOffset(), $pageObj->getPageSize());
        $bcarts = $this->db()->setQueryString($sql)->find();
        
        $floor = $pageObj->getFloor();
        $merge = array();
        if ($pageObj->getTotalPage() > 1 && $pageObj->getCurrentPage() > 1)
        {
            $merge = array('page'=>$pageObj->getCurrentPage());
        }

        $this->getController()->render('bcart', array(
                'bcarts' => $bcarts,
                'pageObj' => $pageObj,
                'floor' => $floor,
                'uid' => $uid,
                'isSelf' => $isSelf,
                'merge' => $merge,
            )
        );
    }
}