<?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();
        $uid = S::gp('uid', 'P', 2);
        if (!$uid)
        {
            throw new iSystemException('请输入用户UID');
        }

        $property = $this->getController()->getProp('jixiong');
        $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(), 'jixiong')))
        {
            $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);

        $cache = $this->cache()->get('PIG_'.$uid);
        if (false === $cache)
        {
            $message[] = '不是兄弟无能，只怪凶手太狡猾，让他跑了！';
        }
        else
        {
            $useUid = array_pop(explode('|', $cache));
            $appendMessage = '';
            $useUserName = userName($useUid);
            if ($useUserName)
            {
                if (1 == rand(1, 5))
                {
                    // TODO 重构
                    $pigList = array(1,2,3,4,5,6);
                    $pigId = $pigList[rand(1, count($pigList) - 1)];
                    $this->cache()->set('PIG_'.$useUid, $pigId.'.gif|'.$useUid, 7200);
                    $appendMessage = '凶手作恶多端，遭受天谴，变成了猪头！';
                }
                $message[] = '天网恢恢，疏而不漏！'.$appendMessage.'没错，凶手就是-----------------'.ilink('点开自己看', url('system', array('s'=>'member','uid'=>$useUid)));
            }
        }
        $this->showMessage($message);
    }
}