<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "{{%admin_role}}".
 *
 * @property string $id
 * @property string $name
 * @property string $access
 * @property integer $super
 */
class AdminRole extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%admin_role}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['access'], 'safe'],
            [['super'], 'integer'],
            [['name'], 'string', 'max' => 30],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '角色名称',
            'access' => '角色权限',
            'super' => 'Super',
        ];
    }
    public function beforeSave($insert)
    {
        $timestamp = time();
        if (parent::beforeSave($insert)) {
            $this->access = serialize($this->access);
            if($insert) {
                $this->super = 0;
            }
            return true;
        } else {
            return false;
        }
    }
    public static function getall(){
        return self::find()->select(['name','id'])->asArray()->indexBy('id')->column();
    }
    public static function getCache($id=0){
        $cache = Yii::$app->cache;
        $data = $cache->get('sys_role_access');
        if ($data === false) {
            $data = self::find()->select(['access','super','id'])->asArray()->indexBy('id')->all();
            $cache->set('sys_role_access', $data);
        }
        if($id>0){
            return $data[$id];
        }
        return $data;
    }
    public function afterSave($insert, $changedAttributes){
        parent::afterSave($insert, $changedAttributes);
        $cache = Yii::$app->cache;
        $cache->delete('sys_role_access');
        return true;
    }
    public function afterDelete(){
        parent::afterDelete();
        $cache = Yii::$app->cache;
        $cache->delete('sys_role_access');
        return true;
    }
}
