<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class VoteRecommendAction extends MemberAction
{
    public function run()
    {
        $bookId = S::gp('bid', 'G', 2);
        $t = S::gp('t', 'G', 2);
        $t = in_array($t, array(1, 2)) ? $t : 1;
        $fields = 1 == $t ? array('red'=>1, 'd_red' => 1, 'w_red' => 1, 'm_red' => 1) : array('black' => 1, 'd_black' => 1, 'w_black' => 1, 'm_black' => 1);

        if (!u('verify'))
        {
            throw new iSystemException('非验证会员不能投票');
        }
        
        $book = fetchBookInfo($bookId);
        if (empty($book))
        {
            throw new iSystemException('不存在的小说');
        }
        
        if (!Book::isOriginal($book['type']))
        {
            throw new iSystemException('非原创小说不能投票');
        }
        
        $hpNum = $this->db()->getValue('SELECT `hp` FROM '.Memberfields::table().' WHERE uid = '.S::sqlEscape($this->uid()));
        if (!$hpNum)
        {
            throw new iSystemException('您当前的推荐票已经用完');
        }

        if (2 == $t)
        {
            if (!$_GET['confirm'])
            {
                $this->getController()->render('voterecommend', array('bid'=>$bookId));
                exit(0);
            }
            else
            {
                $msg = S::gp('msg', 'P');
                if (empty($msg))
                {
                    throw new iSystemException('原因不能为空，请留下您宝贵的意见，方便作者改进作品！');
                }
                $authorId = $this->db()->getValue('SELECT authorid FROM '.Book::table().' WHERE bookid = '.S::sqlEscape($bookId));
                $msgtouid = Authors::single()->getUid($authorId);
                $subject = '[系统消息]您的原创作品获得黑票';
                $content = '您的原创作品《'.$book['bookname']."》获得黑票一张\n\n【原因】: ".$msg;
                Members::sendMessage($subject, $content, 1, 'admin', $msgtouid);
            }
        }
        $this->db()->insert(BookVoteRecommend::table())->value(array('bid' => $bookId, 'uid' => $this->uid(), 'type' => $t, 'date' => CDATE, 'createdate' => CDATETIME, 'ip' => ONLINE_IP))->q();
        $this->db()->update(Memberfields::table())->decrField(array('hp' => 1))->where('uid='.S::sqlEscape($this->uid()))->q();
        $this->db()->update(Book::table())->incrField($fields)->where('bookid='.S::sqlEscape($bookId))->q();
        
        $message[] = '恭喜，投票成功！';
        $message[] = '返回'.ilink('书页', url('bookshow', array('bid'=>$bookId))) . '.'.memberLink() . '.' . indexLink();

        $feed = '{{'.$this->uid().'}}投了[url='.staticUrl('bookshow',array('bid'=>$bookId)).']《'.$book['bookname'].'》[/url]一张'.($t == 1 ? '红票' : '黑票');
        iFeed::single()->create($feed, $this->uid(), 'book');
        
        $this->showMessage($message);
    }
}