<?php

namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\libs\logging\operate\AdminOperate;
use common\models\DealType;
use yii\base\Exception;

/**
 * 点位绑定表单
 */
class DealTypeForm extends Model {
    public $id;
    public $typeName;
    public $isEnable;
    public $createRemark;
    public $sort;

    private $_model;

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'typeName', 'createRemark', 'sort', 'isEnable'], 'trim'],
            [['id', 'typeName', 'sort'], 'required'],
            [['typeName'], 'unique', 'on' => 'update', 'targetClass' => DealType::class, 'targetAttribute' => 'TYPE_NAME', 'when' => function ($model) {
                return $model->isAttributeChanged('TYPE_NAME');
            }],
            [['id'], 'initModel'],
            [['sort'], 'isSort'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'add' => ['typeName', 'createRemark','sort', 'isEnable'],
            'edit' => ['id', 'typeName', 'createRemark','sort', 'isEnable'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'typeName' => '类型名称',
            'isEnable' => '是否启用',
            'createRemark' => '创建备注',
            'sort' => '排序',
        ];
    }

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

    /**
     * 排序需大于等于1
     * @param $attributes
     */
    public function isSort($attributes) {
        if ($this->scenario == 'add' && $this->sort < 1) {
            $this->addError($attributes, '排序请填写大于等于1的数字');
        }
        if ($this->scenario == 'edit') {
            if ($this->_model->IS_PRESET != 1 && $this->sort < 1) {
                $this->addError($attributes, '排序请填写大于等于1的数字');
            }
        }
    }

    /**
     * 添加
     * @return DealType|null
     * @throws \yii\db\Exception
     */
    public function add() {
        if (!$this->validate()) {
            return null;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 添加会员合作点位
            $model = new DealType();
            $model->TYPE_NAME = $this->typeName;
            $model->IS_ENABLE = $this->isEnable ? $this->isEnable : 0;
            $model->IS_PRESET = 0;
            $model->CREATE_ADMIN = \Yii::$app->user->id;
            $model->CREATE_REMARK = $this->createRemark;
            $model->CREATED_AT = Date::nowTime();
            $model->SORT_ORDER = $this->sort;
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('add', $e->getMessage());
            return null;
        }

        // 记录日志
        $this->adminOperateLogger->afterInsert($model)->clean()->save([
            'optType' => '添加交易类型',
            'remark' => $model->CREATE_REMARK,
        ]);

        return $model;
    }

    /**
     * 修改操作
     * @return null
     * @throws \yii\db\Exception
     */
    public function edit() {
        if (!$this->validate()) {
            return null;
        }
        // 记录日志
        $this->adminOperateLogger->beforeUpdate($this->_model);
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model = $this->_model;
            $model->TYPE_NAME = $this->typeName;
            if($model->IS_PRESET!=1) {
                $model->IS_ENABLE = $this->isEnable ? $this->isEnable : 0;
                $model->IS_PRESET = 0;
                $model->CREATE_REMARK = $this->createRemark;
                $model->SORT_ORDER = $this->sort;
            }
            $model->UPDATE_ADMIN = \Yii::$app->user->id;
            $model->UPDATED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        // 记录日志
        $this->adminOperateLogger->afterUpdate($model)->clean()->save([
            'optType' => '修改交易类型',
            'remark' => $model->CREATE_REMARK,
        ]);
        return $model;
    }

    /**
     * 删除
     * @param $selected
     */
    public static function delete($selected) {
    }
}
