<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class SuperBmAction extends ForumAction
{
    public function run()
    {
        $month = date("Y-m");
        $this->showMessage('超管将不在投票');
        $voteObj = BookVote::single();
    
        $sql = "SELECT * FROM `".BookVote::table()."` WHERE FROM_UNIXTIME(createdate,'%Y-%m') = '$month' AND issuper = 1";
        $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 < CTIME)
        {
            define('IS_OVER', true);
        }
        else
        {
            define('IS_OVER', false);
        }
    
        if ($_GET['confirm'])
        {
            $this->getController()->isLogin();
            
            $check = $this->db()->getValue("SELECT COUNT(*) AS c FROM ".BookManagers::table()." WHERE `uid` = {$this->uid()} AND `status` = 1");
            if (1 > $check && !IS_SUPER)
            {
                throw new iSystemException('超管投票只有书管才能参与');
            }
    
            if (IS_OVER)
            {
                throw new iSystemException('新的一期超管投票暂未开始，请耐心等待^_^');
            }
            
            if (!empty($voterids) && in_array($this->uid(), $voterids))
            {
                throw new iSystemException('您已经投过票了');
            }
            $optionId = S::gp('optionid', 'G', 2);
            $voteObj->addVotes($optionId);
    
            $voterids[] = $this->uid();
            $voteObj->update($voteId, array('voterids'=>implode(',', $voterids)));
    
            if ($vote['award'])
            {
                iCredits::single($this->uid(), $this->userName())->addMoney($vote['award']);
            }
    
            $message[] = '投票成功';
            $message[] = '返回'.ilink('超管投票',url('system',array('s'=>'forum','c'=>'vote','a'=>'superbm'))).'.'.memberLink().'.'.indexLink();
            $this->showMessage($message);
        }

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