<?php

namespace common\models;

use common\components\Model;
use common\helpers\Form;
use common\libs\logging\operate\AdminOperate;
use common\models\DeclarationLevel;
use common\models\StarCrownLevel;

/**
 * Login form
 */
class StarCrownLevelForm extends Model
{

    public function init()
    {
        parent::init();
        $this->adminOperateLogger = new AdminOperate([
            'fetchClass' => StarCrownLevel::class,
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [];
    }

    /**
     * 更新星级奖金
     * @return bool
     * @throws \yii\db\Exception
     */
    public function updateBonus()
    {
        $beforeData = StarCrownLevel::getBonusConfig();
        $this->adminOperateLogger->saveBeforeContent=$beforeData;

        $postData = \Yii::$app->request->post('data');
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            foreach ($postData as $value) {
                $crownLevelModel = StarCrownLevel::findOne(['ID' => $value['ID']]);
                if ($crownLevelModel) {
                    $crownLevelModel->TOURISM_PERCENT = $value['TOURISM_PERCENT'];
                    $crownLevelModel->GARAGE_PERCENT = $value['GARAGE_PERCENT'];
                    if (!$crownLevelModel->save()) {
                        throw new \Exception(Form::formatErrorsForApi($crownLevelModel->getErrors()));
                    }
                }
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->addError('updateBonus', $e->getMessage());
            return null;
        }

        $afterData = StarCrownLevel::getBonusConfig();
        $this->adminOperateLogger->saveAfterContent = $afterData;
        unset($beforeData,$afterData);

        $this->adminOperateLogger->clean()->save([
            'optType' => '更新星级奖金配置',
        ]);
        return true;
    }
}
