<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class ApplyAction extends ForumAction
{
    public function run()
    {
        $this->getController()->isLogin();
        
        $permissions = Members::single()->getPermissions($this->uid());
        !$permissions['isapplydigest'] && $this->NoPermission();
        
        $postId = S::gp('cid','G',2);
        $bookPost = BookPost::single()->getOne($postId, $this->id());
        if (empty($bookPost))
        {
            throw new iSystemException('不存在的评论');
        }
        if ($this->uid() != $bookPost['uid'])
        {
            throw new iSystemException('此评论不属于你，不能申请');
        }
        if ($bookPost['applydigest'])
        {
            throw new iSystemException('此评论已经申请过精华，请不要重复申请');
        }
        if (mb_strlen($bookPost['message'], 'utf8') < 50)
        {
            throw new iSystemException('申请的评论长度不能小于50字');
        }
        
        $bookManagers = $this->bookManagers();
        
        if ('send' == trim($_GET['do']))
        {
            if (empty($_GET['uid']))
            {
                throw new iSystemException('请选择申请的书管');
            }
            $uid = S::gp('uid','G',2);
            $bookInfo = $this->bookInfo();
            if (!in_array($uid, $bookManagers))
            {
                throw new iSystemException('UID:'.$uid.'的书友并非不书会书管，不能申请');
            }
            
            $subject = '[系统消息]评论申精';
            $content = '书友'.$this->userName().'在《'.$bookInfo['bookname']."》书会发表的评论申请精华\n以下是评论内容:\n".$bookPost['message']."\n是否[ApplyDigest=".$this->id().'_'.$postId.']同意[/ApplyDigest]？';
            Members::sendMessage($subject, $content, $this->uid(), $this->userName(), $uid);
            BookPost::single()->update($postId, $this->id(), array('applydigest'=>1));
    
            $message[] = '申请成功';
            $message[] = '返回'.ilink('书会',$this->getController()->url('system',array('s'=>'forum','id'=>$this->id()))).'.'.memberLink().'.'.indexLink();
            $this->showMessage($message);
        }
        
        if (!empty($bookManagers))
        {
            $sql = 'SELECT m.uid,m.username FROM '.Members::table().' AS m WHERE m.uid IN ('.implode(',', $bookManagers).')';
            $bookManagers = $this->db()->setQueryString($sql)->find();
        }
        $this->getController()->render('apply', array(
                'bookid' => $this->id(),
                'cid' => $postId,
                'bookManagers' => $bookManagers,
            )
        );
    }
}