<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class JoinAction extends BaseAction
{
    public function run()
    {
        isLogin();
        
        if (empty($_POST['credit']))
        {
            throw new iSystemException('非法操作');
        }
        
        $iorange = $this->iorange();
        $id = S::gp('id', 'G', 2);
        $sale = $this->db()->select()->from(Sales::table())->where('id='.$id)->find(true);
        if (empty($sale))
        {
            throw new iSystemException('不存在的拍卖');
        }

        $credit = S::gp('credit', 'P', 2);
        if (!$iorange['user']['verify'])
        {
            throw new iSystemException('非验证会员不能参与');
        }
        if (0 > $credit)
        {
            throw new iSystemException('出价数必须大于0');
        }
        if (strtotime($sale['end']) < CTIME)
        {
            throw new iSystemException('本次抢拍已经结束');
        }
        try
        {
            Members::single()->hasMoney($this->uid(), $credit);
        }
        catch (NotEnoughMoneyException $exce)
        {
            throw new iSystemException('您当前'.setting('creditname').'不足'.$credit.',不能进行抢拍');
        }
        if ($credit < $sale['least'])
        {
            throw new iSystemException('当前抢拍每次参与'.setting('creditname').'最低不能小于'.$sale['least']);
        }

        $data = array(
            'uid' => $this->uid(),
            'username' => $this->userName(),
            'sale_id' => $id,
            'amount' => $credit,
            'createdate' => CDATETIME,
        );
        $this->db()->insert(SaleJoins::table())->value($data)->q();
        $this->db()->update(Sales::table())->incrField(array('amount'=>$credit))->where('id='.$id)->q();
        iCredits::single($this->uid(), $this->userName())->consume($credit);

        $message[] = '抢拍投注成功';
        $message[] = '返回'.ilink('抢拍页面',url('system',array('s'=>'sale','a'=>'detail','id'=>$id))).'.'.ilink('继续投注', url('system',array('s'=>'sale','a'=>'detail','id'=>$id)));
        $this->showMessage($message);
    }
}