<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class BuyAction extends BaseAction
{
    public function run()
    {
        if (isset($_POST['num']))
        {
            $this->getController()->isLogin();
            
            $num = S::gp('num', 'P', 2);
            if ($num < 1)
            {
                throw new iSystemException('购买的数量必须大于0');
            }
            
            $property = $this->getController()->getProp('frecommend');
            if ($property['higher'] < $num)
            {
                throw new iSystemException('一次最多只能购买' . $property['higher'] . '张');
            }
            if ($property['nums'] < 1)
            {
                throw new iSystemException('今天的已经卖完，请明天赶早^_^');
            }
            
            $money = $num * $property['price'];
            $this->getController()->hasMoney($this->uid(),$this->userName(),$money);

            iCredits::single($this->uid(), $this->userName())->consume($money);
            if (false !== ($prop = $this->getController()->hasPropMemberLog($this->uid(), 'frecommend')))
            {
                $option = unserialize($prop['option']);
                $option['amount'] += $num;
                $this->getController()->updatePropMemberLog($this->uid(), $this->userName(), $property['propertyid'], serialize($option));
            }
            else
            {
                $this->getController()->createPropMemberLog($this->uid(),$this->userName(), $property['propertyid'], serialize(array('class'=>1,'amount'=>$num)));
            }
            $this->db()->query('UPDATE `'.Property::table()."` SET `nums` = `nums` - $num WHERE `module` = 'frecommend'");

            $data = array(
                'uid' => $this->uid(),
                'username' => $this->userName(),
                'amount' => $num,
                'price' => $money,
            );
            PropertyLog::single()->create($property['propertyid'],$data);

            $message[] = '购买成功，您现在可以给推荐自己的书会了<br/>';
            $message[] = '返回'.ilink('继续购买', url('system',array('s'=>'props','c'=>'frecommend'))).'.'.memberLink().'.'.indexLink();
            $this->showMessage($message);
        }
        else
        {
            throw new iSystemException('非法操作');
        }
    }
}