<?php

namespace common\models;

use common\helpers\Cache;
use Yii;

/**
 * This is the model class for table "{{%DEC_ROLE}}".
 *
 * @property string $ID
 * @property string $ROLE_NAME 名称
 * @property string $FW_BONUS_PERCENT 店补比例
 * @property string $SORT 排序
 * @property int $CREATED_AT 创建时间
 * @property int $UPDATED_AT 更新时间
 * @property string $UPDATER 更新人
 * @property string $ADM_NAME 操作人
 */
class DecRole extends \common\components\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%DEC_ROLE}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ROLE_NAME', 'ADM_NAME'], 'required'],
            [['FW_BONUS_PERCENT'], 'number'],
            [['SORT', 'CREATED_AT', 'UPDATED_AT'], 'integer'],
            [['ID'], 'string', 'max' => 32],
            [['ROLE_NAME'], 'string', 'max' => 255],
            [['UPDATER', 'ADM_NAME'], 'string', 'max' => 16],
            [['ID'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'ROLE_NAME' => '名称',
            'FW_BONUS_PERCENT' => '推荐奖比例',
            'SORT' => '排序',
            'CREATED_AT' => '创建时间',
            'UPDATED_AT' => '更新时间',
            'UPDATER' => '更新人',
            'ADM_NAME' => '操作人',
        ];
    }

    /**
     * 获取所有数据
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getAllData(){
        return static::find()->where('1=1')->indexBy('ID')->asArray()->all();
    }

    /**
     * 通过会员ID获取报单中心级别ID
     * @param $userId
     * @return mixed
     */
    public static function getRoleIdFromUserId($userId){
        $data = User::findOneAsArray('ID=:ID', [':ID'=>$userId], 'DEC_ROLE_ID');
        return $data['DEC_ROLE_ID'];
    }

    /**
     * 通过会员ID获得报单中心级别名称
     * @param $userId
     * @return string
     */
    public static function getRoleNameFromUserId($userId){
        $roleId = self::getRoleIdFromUserId($userId);
        if($roleId){
            $role = self::findOneAsArray('ID=:ID', [':ID'=>$roleId]);
            return $role ? $role['ROLE_NAME'] : '';
        } else {
            return null;
        }
    }

    /**
     * 报单级别名称
     * @param $roleId
     * @return string
     */
    public static function getRoleNameId($roleId){
        $role = self::findOneAsArray('ID=:ID', [':ID'=>$roleId]);
        return $role ? $role['ROLE_NAME'] : '';
    }

    /**
     *  更新缓存
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function updateToCache(){
        // 获取配置
        $data = static::find()->where('1=1')->orderBy('SORT ASC')->asArray()->indexBy('ID')->all();
        Yii::$app->cache->set(Cache::DEC_ROLE_CONFIG_KEY, $data);
        return $data;
    }
}
