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

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

/**
 * Login form
 */
class AdminRoleForm extends Model
{
    public $id;
    public $roleName;
    public $remark;
    public $permission;
    public $columnPermission;

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'roleName', 'permission', 'columnPermission'], 'trim'],
            [['id', 'roleName', 'permission'], 'required'],
            [['roleName'], 'unique', 'on' => 'update', 'targetClass' => AdminRole::class, 'targetAttribute' => 'ROLE_NAME', 'when' => function ($model) {
                return $model->isAttributeChanged('ROLE_NAME');
            }],
            [['id'], 'exist', 'targetClass' => AdminRole::class, 'targetAttribute' => 'ID'],
            [['roleName', 'remark'], 'trim'],
        ];
    }

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

    public function attributeLabels()
    {
        return [
            'roleName' => '角色名称',
            'remark' => '备注',
        ];
    }

    /**
     * 添加角色
     * @return AdminRole|null
     */
    public function add(){
        if(!$this->validate()){
            return null;
        }
        $model = new AdminRole();
        $model->ROLE_NAME = $this->roleName;
        $model->REMARK = $this->remark;
        $model->CREATE_ADMIN = \Yii::$app->user->id;
        $model->CREATED_AT = Date::nowTime();
        if(!$model->save()){
            $this->addErrors($model->getErrors());
            return null;
        }
        $this->adminOperateLogger->afterInsert($model)->clean()->save([
            'optType' => '添加管理员角色',
        ]);
        return $model;
    }

    /**
     * 编辑角色
     * @return null|static
     */
    public function edit(){
        if(!$this->validate()){
            return null;
        }
        $model = AdminRole::findOne(['ID'=>$this->id]);
        $this->adminOperateLogger->beforeUpdate($model);
        $model->ROLE_NAME = $this->roleName;
        $model->REMARK = $this->remark;
        $model->UPDATE_ADMIN = \Yii::$app->user->id;
        $model->UPDATED_AT = Date::nowTime();
        if(!$model->save()){
            $this->addErrors($model->getErrors());
            return null;
        }
        $this->adminOperateLogger->afterUpdate($model)->clean()->save([
            'optType' => '编辑管理员角色',
        ]);
        return $model;
    }

    /**
     * 设置管理员角色权限
     * @return null|static
     */
    public function permission(){
        if(!$this->validate()){
            return null;
        }
        $model = AdminRole::findOne(['ID'=>$this->id]);
        $this->adminOperateLogger->beforeUpdate($model);
        //$model->PERMISSION = Json::encode($this->permission);
        $model->UPDATE_ADMIN = \Yii::$app->user->id;
        $model->UPDATED_AT = Date::nowTime();
        if(!$model->save()){
            $this->addErrors($model->getErrors());
            return null;
        }
        // 把权限写入文件中
        $path = \Yii::getAlias('@common/runtime/permission/').$model->ID;
        file_put_contents($path, Json::encode($this->permission));

        $this->adminOperateLogger->afterUpdate($model)->clean()->save([
            'optType' => '设置管理员角色权限',
        ]);
        return $model;
    }

    /**
     * 列表字段权限
     * @return AdminRole|null
     */
    public function columnPermission(){
        if(!$this->validate()){
            return null;
        }
        $model = AdminRole::findOne(['ID'=>$this->id]);
        $this->adminOperateLogger->beforeUpdate($model);
        $model->COLUMN_PERMISSION = base64_encode(Json::encode($this->columnPermission));
        $model->UPDATE_ADMIN = \Yii::$app->user->id;
        $model->UPDATED_AT = Date::nowTime();
        if(!$model->save()){
            $this->addErrors($model->getErrors());
            return null;
        }
        $this->adminOperateLogger->afterUpdate($model)->clean()->save([
            'optType' => '设置管理员角色列表字段权限',
        ]);
        return $model;
    }



    /**
     * 删除管理员角色前
     * @param $selected
     * @throws \Exception
     */
    public function beforeDelete($selected) {
        $this->adminOperateLogger->setIsBatch(true)->beforeDelete($selected, 'ID');
        foreach ($selected as $id) {
            if(Admin::find()->where('ROLE_ID=:ROLE_ID',[':ROLE_ID'=>$id])->exists()){
                throw new \Exception(\Yii::t('ctx', 'adminUnderSelectedRoleCannotDeleted'));
            }
        }
    }

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