<?php

/**
 * This is the model class for table "sale".
 */
class Sale extends BaseActiveRecord
{
	/**
	 * The followings are the available columns in table 'sale':
	 * @var integer $id
	 * @var string $subject
	 * @var string $content
	 * @var string $createdate
	 * @var string $updatedate
	 * @var string $begin
	 * @var string $end
	 * @var integer $amount
	 * @var integer $win_uid
	 * @var string $win_username
	 * @var integer $win_amount
	 * @var integer $least
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return Sale the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'ig_sale';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('subject, content, createdate, begin, end', 'required'),
			array('amount, win_uid, win_amount, least', 'numerical', 'integerOnly'=>true),
			array('subject', 'length', 'max'=>100),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, subject, content, createdate, updatedate, begin, end, amount, win_uid, win_username, win_amount, least', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

    /**
     * 可用行为列表
     * @return array
     */
    public function behaviors()
    {
        return array(
			'CreateAt' => array(
				'class' => 'application.models.behaviors.CreateAtBehavior',
			),
            'UpdateAt' => array(
                'class' => 'application.models.behaviors.UpdateAtBehavior',
            )
        );
    }

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'subject' => '主题',
			'content' => '说明',
			'createdate' => '创建时间',
			'updatedate' => '修改时间',
			'begin' => '开始',
			'end' => '结束',
			'amount' => '总金额',
			'win_uid' => '获胜者UID',
			'win_username' => '获胜者名',
			'win_amount' => '获胜金额',
			'least' => '每次最低金额',
		);
	}

    public function beforeSave()
    {
        parent::beforeSave();
        if (!$this->isNewRecord)
        {
            // 如果带了uid且uid存在，则自动填充用户名
            if (!empty($this->win_uid))
            {
                $member = Member::model()->findByPk($this->win_uid);
                if (!empty($member))
                {
                    $this->win_username = $member->username;
                }
            }
        }

        return true;
    }
}