<?php

namespace common\models\forms;

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

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

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

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

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

        $postData = \Yii::$app->request->post('data');
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            foreach ($postData as $value) {
                $decLevelModel = DeclarationLevel::findOne(['ID' => $value['ID']]);
                if ($decLevelModel) {
                    $decLevelModel->QY_PERCENT = $value['QY_PERCENT'];
                    $decLevelModel->QY_TOUCH_CAP = $value['QY_TOUCH_CAP'];
                    $decLevelModel->QY_BIG_CAP = $value['QY_BIG_CAP'];
                    $decLevelModel->FX_MIN_DEEP = $value['FX_MIN_DEEP'];
                    $decLevelModel->FX_MAX_DEEP = $value['FX_MAX_DEEP'];
                    $decLevelModel->FX_PERCENT = $value['FX_PERCENT'];
                    $decLevelModel->GL_ODD_DEEP_ONE = $value['GL_ODD_DEEP_ONE'];
                    $decLevelModel->GL_ODD_DEEP_TWO = $value['GL_ODD_DEEP_TWO'];
                    $decLevelModel->GL_ODD_DEEP_THREE = $value['GL_ODD_DEEP_THREE'];
                    $decLevelModel->INCOME_CAP = $value['INCOME_CAP'];
                    if (!$decLevelModel->save()) {
                        throw new \Exception(Form::formatErrorsForApi($decLevelModel->getErrors()));
                    }
                }
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->addError('updateBonus', $e->getMessage());
            return null;
        }

        $afterData = DeclarationLevel::getBonusConfig();
        $this->adminOperateLogger->saveAfterContent=$afterData;
        unset($beforeData,$afterData);
        $this->adminOperateLogger->clean()->save([
            'optType' => '更新级别奖金配置',
        ]);
        return true;
    }
}
