<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class UseAction extends BaseAction
{
    public function run()
    {
        $bookid = S::gp('bid', 'G', 2);
        $this->getController()->isLogin();

        $book = fetchBookInfo($bookid);
        if (empty($book))
        {
            throw new iSystemException('不存在的小说');
        }
        
        if (false === ($recommend = $this->getController()->hasPropMemberLog($this->uid(), 'recommend')))
        {
            throw new iSystemException('您还没有疯狂推荐票，是否需要' . ilink('购买', url('system',array('s'=>'props','c'=>'recommend'))) . '？');
        }
        
        $option = unserialize($recommend['option']);
        if (!$option['time'])
        {
            throw new iSystemException('您的疯狂推荐票已经用完，是否需要' . ilink('购买', url('system',array('s'=>'props','c'=>'recommend'))) . '？');
        }
        $usetime = CTIME;

        $data = array(
            'uid' => $this->uid(),
            'username' => filter_content($this->userName()),
            'bookid' => $bookid,
            'subject' => filter_content($book['bookname']),
            'starttime' => CTIME,
            'createdate' => CTIME,
            'usetime' => $option['time'],
        );
        $this->db()->insert(MemberRecommend::table())->value($data)->q();
        $commends = $this->_getCommends($option['time']);
        $this->db()->update(Book::table())->incrField(array('commends'=>$commends))->where('bookid='.S::sqlEscape($bookid))->q();
        $key = md5("MemberRecommend");
        $this->cache()->set($key, array('bookid'=>$bookid,'subject'=>$book['bookname'],'uid'=>$this->uid()), $option['time']);
        
        $option['time'] = 0;
        $this->getController()->updatePropMemberLog($this->uid(), $this->userName(), $recommend['property_id'], serialize($option));

        $feed = '{{'.$this->uid().'}}推荐了小说[url='.staticUrl('bookshow',array('bid'=>$bookid)).']《'.$book['bookname'].'》[/url]';
        iFeed::single()->create($feed, $this->uid(), 'book');

        $message[] = '恭喜,使用道具成功,赶紧去各个角落看看效果吧!<br/>返回'.bookLink($bookid).'.'.memberLink().'.'.indexLink();
        $this->showMessage($message);
    }
    
    private function _getCommends($time)
    {
        switch ($time)
        {
            case '60':
                return 2;
            case '300':
                return 3;
            case '30':
            default:
                return 1;
        }
    }
}