<?php
namespace backendApi\modules\v1\models;

use common\components\Model;
use common\helpers\Date;
use common\libs\logging\operate\AdminOperate;

/**
 * Login form
 */
class AdminForm extends Model
{
    public $id;
    public $adminName;
    public $realName;
    public $remark;
    public $isEnable;
    public $isModifyPassword;
    public $bindIp;
    public $oldPassword;
    public $password;
    public $surePassword;
    public $roleId;

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'adminName', 'realName', 'oldPassword', 'password', 'surePassword', 'roleId', 'remark', 'isEnable', 'isModifyPassword', 'bindIp'], 'trim'],
            [['id', 'adminName', 'realName', 'roleId'], 'required'],
            [['password', 'surePassword'], 'required', 'on'=>['add', 'changePassword', 'noLoginModifyPassword']],
            [['adminName', 'oldPassword'], 'required', 'on'=>['noLoginModifyPassword']],
            [['adminName'], 'unique', 'targetClass'=>Admin::class, 'targetAttribute'=>'ADMIN_NAME', 'on'=>['add']],
            ['surePassword', 'compare', 'compareAttribute'=>'password', 'message' => '两次密码必须一致'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'add' => ['adminName', 'realName', 'password', 'surePassword', 'roleId', 'remark', 'isEnable', 'isModifyPassword', 'bindIp'],
            'edit' => ['id', 'password', 'surePassword', 'roleId', 'realName', 'remark', 'isEnable', 'isModifyPassword', 'bindIp'],
            'changePassword' => ['password', 'surePassword'],
            'noLoginModifyPassword' => ['adminName', 'oldPassword', 'password', 'surePassword'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'adminName' => '管理员用户名',
            'realName' => '管理员会员姓名',
            'remark' => '备注',
            'isEnable' => '是否启用',
            'isModifyPassword' => '是否修改密码',
            'bindIp' => '绑定IP',
            'oldPassword' => '原密码',
            'password' => '密码',
            'surePassword' => '确认密码',
            'roleId' => '角色',
        ];
    }

    /**
     * 添加
     * @return Admin|null
     * @throws \yii\base\Exception
     */
    public function edit(){
        if(!$this->validate()){
            return null;
        }

        if($this->scenario == 'add'){
            $model = new Admin();
            $model->ADMIN_NAME = strtolower($this->adminName);
            $model->REAL_NAME = $this->realName;
            $model->ROLE_ID = $this->roleId;
            $model->REMARK = $this->remark;
            $model->IS_ENABLE = $this->isEnable ? $this->isEnable : 0;
            $model->IS_MODIFY_PASSWORD = $this->isModifyPassword ? $this->isModifyPassword : 0;
            $model->BIND_IP = $this->bindIp;
            $model->CREATE_ADMIN = \Yii::$app->user->id;
            $model->CREATED_AT = Date::nowTime();
        } elseif($this->scenario == 'edit') {
            $model = Admin::findOne(['ID'=>$this->id]);
            $this->adminOperateLogger->beforeUpdate($model);
            $model->REAL_NAME = $this->realName;
            $model->ROLE_ID = $this->roleId;
            $model->REMARK = $this->remark;
            $model->IS_ENABLE = $this->isEnable ? $this->isEnable : 0;
            $model->IS_MODIFY_PASSWORD = $this->isModifyPassword ? $this->isModifyPassword : 0;
            $model->BIND_IP = $this->bindIp;
            $model->UPDATE_ADMIN = \Yii::$app->user->id;
            $model->UPDATED_AT = Date::nowTime();
        } elseif($this->scenario == 'changePassword') {
            $model = Admin::findOne(['ID'=>\Yii::$app->user->id]);
        } elseif($this->scenario == 'noLoginModifyPassword') {
            $model =  Admin::findOne(["ADMIN_NAME"=>$this->adminName]);
            if( !$model ) {
                $this->addError('noLoginModifyPassword', '不存在的用户名');
                return null;
            }
            if( $this->oldPassword === $this->password ) {
                $this->addError('noLoginModifyPassword', '登录密码没有发生改变');
                return null;
            }
            if ( !$model->validatePassword($this->oldPassword) ) {
                $this->addError('noLoginModifyPassword', '原登录密码错误');
                return null;
            }
            $model->IS_MODIFY_PASSWORD = 0;
        }else {
            $this->addError('id', '提交场景不存在');
            return null;
        }

        // 给密码进行加密 ，如果需要添加验证密码安全验证时 ，可以在这个地方加
        if($this->password){
            if ($this->scenario == 'changePassword' || $this->scenario == 'noLoginModifyPassword'){
                // 进行规则的判断
                $message = $model->verificationPassword($this->password,$this->scenario,$model);
                if ( $message['code'] != 200 ){
                    $this->addError($message['type'], $message['message']);
                    return null;
                }
            }

            $model->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($this->password);
        }

        // 执行修改或添加 , 如果执行不成功就在这里报出错误
        if(!$model->save()){
            $this->addErrors($model->getErrors());
            return null;
        }

        // 执行完成后根据对应的类型写入日志
        if($this->scenario == 'add'){
            $this->adminOperateLogger->afterInsert($model)->clean()->save([
                'optType' => '添加管理员',
                'userName' => $model->ADMIN_NAME,
                'remark' => $this->remark,
            ]);
        } elseif($this->scenario == 'edit') {
            $this->adminOperateLogger->afterUpdate($model);
            $this->adminOperateLogger->clean()->save([
                'optType' => '编辑管理员',
                'userName' => $model->ADMIN_NAME,
                'remark' => $this->remark,
            ]);
        } elseif($this->scenario == 'noLoginModifyPassword') {
            $this->adminOperateLogger->clean()->save([
                'optType' => '不登录重置密码',
                'userName' => $model->ADMIN_NAME,
                'adminName' => $model->ADMIN_NAME,
                'remark' => '不登录重置密码',
            ]);
        }else{
            $this->adminOperateLogger->clean()->save([
                'optType' => '重置密码',
                'userName' => Admin::getAdminNameById(\Yii::$app->user->id),
                'remark' => $this->remark,
            ]);
        }

        return $model;
    }

    /**
     * 删除管理员前
     * @param $selected
     * @throws \Exception
     */
    public function beforeDelete($selected) {
        foreach ($selected as $value){
            if($value==\Yii::$app->user->id){
                throw new \Exception('无法删除自己');
            }
        }
        $this->adminOperateLogger->setIsBatch(true)->beforeDelete($selected, 'ID');
    }

    /**
     * 删除管理员
     * @param $selected
     */
    public function delete($selected) {
        $this->adminOperateLogger->clean()->save([
            'optType' => '删除管理员',
        ]);
    }
}
