<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class BuyAction extends BaseAction
{
    public function run()
    {
        $this->getController()->isLogin();
        $price = S::gp('price', 'G', 2);
        $property = $this->getController()->getProp('recommend');

        $option = unserialize($property['option']);
        $priceList = array_keys($option);
        if (!in_array($price, $priceList))
        {
            throw new iSystemException('非法参数');
        }

        $buy = $option[$price];
        if ($buy['num'] < 1)
        {
            throw new iSystemException('今天的' . $buy['time'] . '秒的疯狂推荐票已经卖完，请明天赶早^_^');
        }

        $this->getController()->hasMoney($this->uid(),$this->userName(),$price);
        if (false !== ($prop = $this->getController()->hasPropMemberLog($this->uid(), 'recommend')))
        {
            $userProp = unserialize($prop['option']);
            if ($userProp['time'])
            {
                throw new iSystemException('您当前已经有一张' . $property['propertyname'] . '，必须用完以后再购买');
            }
            $userProp['time'] += $buy['time'];
            $this->getController()->updatePropMemberLog($this->uid(), $this->userName(), $property['propertyid'], serialize($userProp));
        }
        else
        {
            $this->getController()->createPropMemberLog($this->uid(),$this->userName(), $property['propertyid'], serialize(array('class'=>3,'time'=>$buy['time'])));
        }
        iCredits::single($this->uid(), $this->userName())->consume($price);

        $buy['num'] = $buy['num'] - 1;
        $option[$price] = $buy;
        $option = serialize($option);
        $this->db()->query('UPDATE `'.Property::table()."` SET `option` = '$option' WHERE `module` = 'recommend'");

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

        $message[] = '购买成功，您现在可以把票投给自己喜欢的书了,马上去狂荐一下吧!';
        $message[] = ilink('继续购买',url('system',array('s'=>'props','c'=>'recommend'))).'.'.memberLink().'.'.indexLink();
        $this->showMessage($message);
    }
}