<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class UseAction extends BaseAction
{
    public function run()
    {
        $this->getController()->isLogin();
        if (!isset($_POST['uid']))
        {
            throw new iSystemException('非法操作');
        }

        $uid = S::gp('uid', 'P', 2);
        $t = S::gp('t', 'P', 2);
        if (!in_array($t, array(1,2,3,4,5,6)))
        {
            throw new iSystemException('不存在的猪头样式');
        }
        
        $property = $this->getController()->getProp('pig');
        $price = $property['price'];

        try
        {
            Members::single()->hasMoney($this->uid(), $price);
            $member = Members::single()->getOne($uid);
        }
        catch (NotEnoughMoneyException $exce)
        {
            throw new iSystemException($exce->getMessage());
        }
        catch (MemberNotExistsException $exce)
        {
            throw new iSystemException($exce->getMessage());
        }

        iCredits::single($this->uid(), $this->userName())->consume($price);

        if (false === ($prop = $this->getController()->hasPropMemberLog($this->uid(), 'pig')))
        {
            $this->getController()->createPropMemberLog($this->uid(),$this->userName(), $property['propertyid'], serialize(array('class'=>1)));
        }

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

        $this->cache()->set('PIG_'.$uid, $t.'.gif|'.$this->uid(), 7200);
        
        $message[] = '你是一名虔诚的书友，神满足了你的愿望，赶紧去'.ilink('看看', url('system', array('s'=>'member','uid'=>$uid))).'吧';
        $this->showMessage($message);
    }
}