<?php

namespace backendApi\modules\v1\models;

use common\helpers\Cache;
use common\helpers\Tool;
use Yii;
use yii\helpers\Json;
use common\libs\logging\operate\valueType\Config as ValueTypeConfig;

/**
 * This is the model class for table "{{%ADMIN_ROLE}}".
 *
 * @property string $ID
 * @property string $ROLE_NAME 角色名
 * @property string $REMARK 描述
 * @property string $PERMISSION 权限
 * @property string $COLUMN_PERMISSION 列表字段权限
 * @property int $DONT_DEL 不可删除
 * @property string $CREATE_ADMIN 创建管理员
 * @property string $UPDATE_ADMIN 更新管理员
 * @property int $CREATED_AT 创建时间
 * @property int $UPDATED_AT 更新时间
 */
class AdminRole extends \common\components\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%ADMIN_ROLE}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ROLE_NAME', 'CREATED_AT'], 'required'],
            [['DONT_DEL', 'CREATED_AT', 'UPDATED_AT'], 'integer'],
            [['ID', 'CREATE_ADMIN', 'UPDATE_ADMIN'], 'string', 'max' => 32],
            [['ROLE_NAME', 'REMARK'], 'string', 'max' => 255],
            [['COLUMN_PERMISSION'], 'string'],
            [['ROLE_NAME'], 'unique'],
            [['ID'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'ROLE_NAME' => '角色名',
            'REMARK' => '描述',
            'PERMISSION' => '权限',
            'COLUMN_PERMISSION' => '列表字段权限',
            'DONT_DEL' => '不可删除',
            'CREATE_ADMIN' => '创建管理员',
            'UPDATE_ADMIN' => '更新管理员',
            'CREATED_AT' => '创建时间',
            'UPDATED_AT' => '更新时间',
        ];
    }

    /**
     * 获取全部配置，把育成津贴奖金比例解成数组
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getAllData(){
        $allData = static::find()->where('1=1')->orderBy('CREATED_AT ASC')->indexBy('ID')->asArray()->all();
        foreach($allData as $key=>$data){
            // 暂时先从文件中取内容
            $permissionPath = \Yii::getAlias('@common/runtime/permission/').$data['ID'];
            if(!file_exists($permissionPath)){
                $allData[$key]['PERMISSION'] = null;
            } else {
                $permission = file_get_contents($permissionPath);
                $allData[$key]['PERMISSION'] = Json::decode($permission);
            }
            $columnPermission = is_resource($data['COLUMN_PERMISSION']) ? stream_get_contents($data['COLUMN_PERMISSION']) : null;
            $allData[$key]['COLUMN_PERMISSION'] = $columnPermission ? Json::decode(base64_decode($columnPermission)) : null;
        }
        return $allData;
    }

    /**
     * 从缓存获取信息
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getFromCache(){
        $data = Yii::$app->cache->get(Cache::ADMIN_ROLE_KEY);
        if(!$data){
            // 获取信息
            $data = self::getAllData();
            Yii::$app->cache->set(Cache::ADMIN_ROLE_KEY, $data);
        }
        return $data;
    }

    /**
     *  更新缓存
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function updateToCache(){
        // 获取配置
        $data = self::getAllData();
        Yii::$app->cache->set(Cache::ADMIN_ROLE_KEY, $data);
        return $data;
    }

    /**
     * 操作日志记录条件
     * @return array
     */
    public function attrLabelsWithLogType(){
        return [
            'ROLE_NAME' => '角色名称',
            'REMARK' => '描述',
            'PERMISSION' => '权限',
            'COLUMN_PERMISSION' => [
                'label' => '列表字段权限',
                'type' => function($data){
                    $value = $data['value'];
                    $columnPermission = is_resource($value) ? stream_get_contents($value) : null;
                    return $columnPermission ? Json::decode(base64_decode($columnPermission)) : null;
                },
            ],
            'CREATE_ADMIN' => [
                'label' => '创建人',
                'type' => function($data){
                    $value = $data['value'];
                    $result = Admin::findOneAsArray('ID=:ID', [':ID'=>$value], 'ADMIN_NAME');
                    return $result['ADMIN_NAME'];
                },
            ],
            'UPDATE_ADMIN' => [
                'label' => '修改人',
                'type' => function($data){
                    $value = $data['value'];
                    $result = Admin::findOneAsArray('ID=:ID', [':ID'=>$value], 'ADMIN_NAME');
                    return $result['ADMIN_NAME'];
                },
            ],
            'CREATED_AT' => [
                'label' => '创建时间',
                'type' => ValueTypeConfig::DATE_TIME_TYPE,
            ],
            'UPDATED_AT' => [
                'label' => '修改时间',
                'type' => ValueTypeConfig::DATE_TIME_TYPE,
            ],
        ];
    }

    /**
     * 获取全部可供设置权限的列表的字段列
     * @return array
     */
    public static function getAllRoleColumn(){
        // 遍历/Volumes/HDD/www/www.anran.leo/backendApi/modules/v1/models/lists/user/目录下的所有文件
        $allColumns = [];
        $dirPath = __DIR__.'/lists';
        $nameSpace = '\backendApi\modules\v1\models\lists\\';
        $allListClassFiles = Tool::dirFiles($dirPath);
        foreach($allListClassFiles as $classDir => $classFiles){
            if(is_array($classFiles)){
                foreach($classFiles as $classFile){
                    $pathInfo = pathinfo($classFile);
                    $className = $nameSpace.$classDir.'\\'.$pathInfo['filename'];
                    $listModuleArr = explode('\\', $className);
                    $listModuleArrCount = count($listModuleArr);
                    $listModule = $listModuleArr[$listModuleArrCount-2].'/'.$listModuleArr[$listModuleArrCount-1];
                    $listObj = new $className;
                    $allColumns[] = [
                        'listClass' => $listModule,
                        'listName' => $listObj->getListName(),
                        'columns' => $listObj->getAllColumnHeaderName(),
                    ];
                }
            }
        }
        return $allColumns;
    }
}
