<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class UseAction extends BaseAction
{
    public function run()
    {
        if (!empty($_POST['bid']))
        {
            $priceMap = array(200, 300, 400, 500);
            $bookId = S::gp('bid', 'P', 2);
            $price = S::gp('p', 'G', 2);
            if (!in_array($price, $priceMap))
            {
                throw new iSystemException('无效的价格');
            }
            
            $this->getController()->isLogin();
            $this->getController()->isVerify();
            
            $book = fetchBookInfo($bookId);
            if (empty($book))
            {
                throw new iSystemException('不存在的小说');
            }
            if (2 != $book['type'])
            {
                throw new iSystemException('非本站原创小说不能使用此道具');
            }
            if (100000 > $book['size'])
            {
                throw new iSystemException('10W字以下的原创小说不能催更');
            }
            $this->getController()->hasMoney($this->uid(), $this->userName(), $price);
            iCredits::single($this->uid(), $this->userName())->consume($price);
            
            $property = $this->getController()->getProp('update');
            if (false !== ($prop = $this->getController()->hasPropMemberLog($this->uid(), 'update')))
            {
                $option = unserialize($prop['option']);
                $this->getController()->updatePropMemberLog($this->uid(), $this->userName(), $property['propertyid'], serialize($option));
            }
            else
            {
                $this->getController()->createPropMemberLog($this->uid(),$this->userName(), $property['propertyid'], serialize(array('class'=>3)));
            }

            $author = $this->db()->select(array('uid'))->from(Authors::table())->where(array('name'=>$book['author']))->find(true);
            $this->db()->insert(Bookurge::table())->value(array('uid'=>$this->uid(),'username'=>$this->userName(),'author_id' => $author['uid'],'bid' => $bookId,'price' => $price,'date' => CDATE,'createdate' => CDATETIME))->q();
            $subject = '[系统消息]您的小说获得一张催更票';
            $content = '您的小说《'.$book['bookname'].'》获得一张'.($price * 10).'字的催更票，如果您在'.date('Y-m-d').'更新达到'.($price * 10).'字，系统会在第二天临晨自动将'.$price.setting('creditname').'打入您的帐号';
            Members::sendMessage($subject, $content, 1, 'admin', $author['uid']);
            
            $data = array(
                'uid' => $this->uid(),
                'username' => $this->userName(),
                'amount' => 1,
                'price' => $price
            );
            PropertyLog::single()->create($property['propertyid'],$data);

            $message[] = '道具使用成功';
            $message[] = '返回'.memberLink().'.'.indexLink();
            $this->showMessage($message);
        }
        else
        {
            throw new iSystemException('非法操作');
        }
    }
}