<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class AddAction extends ForumAction
{
    public function run()
    {
        $this->isManager();

        if ($_POST['uid'] && $_POST['expiry'])
        {
            $uid = S::gp('uid', 'P', 2);
            $expiry = S::gp('expiry', 'P', 2);
            $remark = trim(S::gp('remark', 'P'));
            
            if (isBlackUser($uid))
            {
                throw new iSystemException('此用户不能被设置副管');
            }

            try
            {
                $member = Members::single()->getOne($uid);
            }
            catch (Exception $exce)
            {
                throw new iSystemException($exce->getMessage());
            }
            if (!$member['verify'])
            {
                throw new iSystemException('未验证用户不能设置成副管');
            }
            if ($expiry < 1 || $expiry > 3)
            {
                throw new iSystemException('副管有效期不能超过3天');
            }
            if (empty($remark))
            {
                throw new iSystemException('请输入设置原因');
            }
            $check = $this->db()->getValue('SELECT COUNT(*) FROM '.BookManageDeputy::table().' WHERE bookid='.$this->id().' AND expiry >='.CTIME);
            if ($check >= 3)
            {
                throw new iSystemException('最多只能设置3个副管');
            }
            $uCheck = $this->db()->getValue('SELECT COUNT(*) FROM '.BookManageDeputy::table().' WHERE uid='.$uid.' AND expiry >='.CTIME);
            if ($uCheck)
            {
                throw new iSystemException('一个书友最多只能担任一个书会的副管');
            }

            $expiry = CTIME + $expiry * 24 * 3600;
            $sql = 'REPLACE INTO '.BookManageDeputy::table().' SET '.S::sqlSingle(array('bookid'=>$this->id(),'uid'=>$uid,'expiry'=>$expiry,'createdate'=>CDATETIME,'remark'=>$remark,'ouid'=>$this->uid()));
            $this->db()->query($sql);

            BookManageDeputy::single()->updateAllCache($this->id());

            iforward(url('system', array('s'=>'forum','c'=>'deputy','id'=>$this->id())));
        }

        $this->getController()->render('add', array('bookid'=>$this->id()));
    }
}