<?php
namespace common\models\forms;

use common\components\Model;
use common\helpers\Date;
use common\models\Config;
use yii\db\Exception;

/**
 * Login form
 */
class ConfigBonusForm extends Model
{
    public $retailPoolPercent;
    public $retailPercent;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['retailPoolPercent', 'retailPercent'], 'required'],
            [['retailPoolPercent', 'retailPercent'], 'number', 'max'=>100, 'min'=>0],
        ];
    }

    public function attributeLabels()
    {
        return [
            'retailPoolPercent' => '进入零售池比例',
            'retailPercent' => '零售奖比例',
        ];
    }

    /**
     * 更新配置
     * @return bool|null
     * @throws Exception
     */
    public function update(){
        if(!$this->validate()){
            return null;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try{
            if(!Config::updateAll(['VALUE'=>$this->retailPoolPercent, 'UPDATED_AT'=>Date::nowTime()], "CONFIG_NAME='retailPoolPercent'")){
                throw new Exception('进入零售池比例更新失败');
            }
            if(!Config::updateAll(['VALUE'=>$this->retailPercent, 'UPDATED_AT'=>Date::nowTime()], "CONFIG_NAME='retailPercent'")){
                throw new Exception('零售奖比例更新失败');
            }
            $transaction->commit();
        } catch (Exception $e){
            $transaction->rollBack();
            $this->addError('retailPoolPercent', $e->getMessage());
            return null;
        }
        return true;

    }
}
