<?php

namespace common\models\forms;

use backendApi\modules\v1\models\Admin;
use common\components\Model;
use common\helpers\Date;
use common\models\RegType;

/**
 * Login form
 */
class RegTypeForm extends Model {
    public $id;
    public $typeName;          // 类型名称
    public $isPact;        // 是否协议
    public $monthAmount;       // 月提现
    public $yearAmount;            // 年提现
    public $remark;               // 备注

    private $_model;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'typeName', 'isPact', 'monthAmount', 'yearAmount', 'remark'], 'trim'],
            [['id', 'isPact', 'monthAmount', 'yearAmount'], 'required'],
            [['id'], 'initModel'],
            [['isPact'], 'isPact'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'edit' => ['id', 'isPact', 'monthAmount', 'yearAmount', 'remark'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'typeName' => '会员编号',
            'isPact' => '是否启用注册协议',
            'monthAmount' => '达到月提现金额更改应注册类型',
            'yearAmount' => '达到年提现金额更改应注册类型',
            'remark' => '备注',
        ];
    }

    /**
     * 初始化model
     * @param $attributes
     */
    public function initModel($attributes) {
        $this->_model = RegType::findOne(['ID' => $this->id]);
        if (!$this->_model) {
            $this->addError($attributes, 'The data does not exist'); // 数据不存在
        }
    }

    /**
     * 是否开启协议判断
     * @param $attributes
     */
    public function isPact($attributes) {
        if (!in_array($this->isPact, [0, 1])) {
            $this->addError($attributes, '错误的是否开启协议');
        }
    }

    /**
     * 编辑
     */
    public function edit() {
        if (!$this->validate()) {
            return null;
        }
        if ($this->scenario == 'edit') {
            $model = RegType::findOne(['ID' => $this->id]);
            $model->IS_PACT = $this->isPact;
            $model->MONTH_LIMIT_AMOUNT = $this->monthAmount;
            $model->YEAR_LIMIT_AMOUNT = $this->yearAmount;
            $model->REMARK = $this->remark;
            $model->UPDATE_ADMIN = Admin::getAdminNameById(\Yii::$app->user->id);
            $model->UPDATED_AT = Date::nowTime();
        } else {
            $this->addError('id', '提交场景不存在');
            return null;
        }
        if ($model->save()) {
            return $model;
        } else {
            $this->addErrors($model->getErrors());
            return null;
        }
    }
}
