<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * 结束一场拍卖
 *
 * @author yzxh24
 */
class CompleteAction extends BaseAction
{
    public function run()
    {
        $id = intval($_GET['id']);
        if(Yii::app()->request->isPostRequest)
		{
            set_time_limit(0);
            $sale = Sale::model()->findByPk($id);
            if ($sale->win_uid)
            {
                return false;
            }
			$criteria = new CDbCriteria();
            $criteria->addCondition('sale_id='.$id);
            $criteria->select = 'SUM(amount) AS userAmount,COUNT(1) AS count,uid,username';
            $criteria->group = 'uid';
            $criteria->order = 'userAmount DESC';
            $criteria->limit = 1;
            $win = SaleJoin::model()->find($criteria);
            $winUid = $win->uid;
            $winUserName = $win->username;
            $winAmount = $win->userAmount;

            $sale->win_uid = $winUid;
            $sale->win_username = $winUserName;
            $sale->win_amount = $winAmount;
            $sale->save();
            
            $subject = '[系统消息]您获得'.setting('webname').'竞拍的胜利';
            $message = '恭喜您获得《'.$sale->subject.'》竞拍的胜利，请尽快联系admin';
            Messages::model()->create($subject,$message,$winUid);
            
            // 返还未中用户积分
            $criteria->limit = -1;
            $criteria->offset = -1;
            $criteria->addCondition('uid<>'.$winUid);
            $users = SaleJoin::model()->findAll($criteria);
            if (!empty($users))
            {
                foreach ($users as $user)
                {
                    $credit = ceil($user->userAmount * 0.8);
                    Member::model()->updateCounters(array('extcredits1'=>$credit),'uid='.$user->uid);
                    $subject = '[系统消息]'.setting('webname').'竞拍结果';
                    $message = '此次竞拍您未能获胜，退还'.$credit.setting('creditname');
                    Messages::model()->create($subject,$message,$user->uid);
                }
            }

            if(!isset($_GET['ajax']))
            {
				$this->getController()->redirect(array('list'));
            }
		}
		else
        {
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
        }
    }
}
