<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class BookBmAction extends ForumAction
{
    public function run()
    {
        $month = date("Y-m");
        
        $voteObj = BookVote::single();

        $sql = "SELECT * FROM `".BookVote::table()."` WHERE FROM_UNIXTIME(createdate,'%Y-%m') = '$month' AND bookid = {$this->id()}";
        $vote = $this->db()->setQueryString($sql)->find(true);
        if (empty($vote))
        {
            throw new iSystemException('暂时没有书管投票');
        }
    
        $voteId = $vote['id'];
        $expire = $vote['expire'];
        $voterids = explode(',', $vote['voterids']);
    
        if ($expire < time())
        {
            define('IS_OVER', true);
        }
        else
        {
            define('IS_OVER', false);
        }
    
        if ($_GET['confirm'])
        {
            $this->getController()->isLogin();
            $permissions = Members::single()->getPermissions($this->uid());
            $iorange = $this->iorange();
            
            if (IS_OVER)
            {
                throw new iSystemException('新的一期书管投票暂未开始，请耐心等待^_^');
            }
            if (!$permissions['isbmvote'])
            {
                $this->NoPermission();
            }
            if (!$iorange['user']['bookvote'])
            {
                throw new iSystemException('您已经没有选票了');
            }
            if (!empty($voterids) && in_array($this->uid(), $voterids))
            {
                throw new iSystemException('您已经投过票了');
            }
            $optionId = S::gp('optionid','G',2);
            $option = $voteObj->getOption($optionId);
            if (empty($option) || $vote['bookid'] != $this->id())
            {
                throw new iSystemException('非法操作');
            }
            
            $voteObj->addVotes($optionId);
    
            $voterids[] = $this->id();
            $voteObj->update($voteId, array('voterids'=>implode(',', $voterids)));
    
            $this->db()->update(Memberfields::table())->decrField(array('bookvote'=>1))->where(array('uid'=>$this->uid()))->q();
            if ($vote['award'])
            {
                iCredits::single($this->uid(), $this->userName())->addMoney($vote['award']);
            }
    
            $message[] = '投票成功';
            $message[] = '返回'.ilink('书管投票',url('system',array('s'=>'forum','c'=>'vote','a'=>'bookbm','id'=>$this->id()))).'.'.memberLink().'.'.indexLink();
            $this->showMessage($message);
        }

        $vote['options'] = $voteObj->getOptions($voteId);
        $this->getController()->render('bookbm', array(
                'bookid' => $this->id(),
                'vote' => $vote,
                'voterids' => $voterids,
            )
        );
    }
}