<?php

namespace common\models;

use common\helpers\Cache;
use common\helpers\LoggerTool;
use Yii;

/**
 * This is the model class for table "{{%CROWN_LEVEL}}".
 *
 * @property string $ID
 * @property string $LEVEL_NAME 级别名称
 * @property int $ICON_TYPE 图标类型
 * @property int $ICON_NUM 图标个数
 * @property int $RX_PERCENT 图标个数
 * @property string $MIN_LEVEL_ID 上级ID
 * @property string $LEVEL_SCORE 级别分数
 * @property string $UPGRADE_SCORE 升级分数
 * @property string $TOURISM_PERCENT 旅游奖比例
 * @property string $GARAGE_PERCENT 车房奖比例
 * @property int $SORT 排序
 * @property int $CREATED_AT 创建时间
 * @property int $UPDATED_AT 更新时间
 * @property string $CREATE_ADMIN 创建人
 * @property string $UPDATE_ADMIN 更新人
 */
class StarCrownLevel extends \common\components\ActiveRecord
{
    const NO_LEVEL_ID = 'DCBEDD8E0EAD3DF59D81CCC0C2ACAEFF';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%CROWN_LEVEL}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['LEVEL_NAME', 'CREATED_AT', 'CREATE_ADMIN'], 'required'],
            [['SORT', 'CREATED_AT', 'UPDATED_AT', 'ICON_TYPE', 'ICON_NUM'], 'integer'],
            [['LEVEL_SCORE', 'UPGRADE_SCORE', 'TOURISM_PERCENT', 'GARAGE_PERCENT'], 'number'],
            [['ID', 'MIN_LEVEL_ID', 'CREATE_ADMIN', 'UPDATE_ADMIN'], 'string', 'max' => 32],
            [['LEVEL_NAME'], 'string', 'max' => 20],
            [['LEVEL_NAME'], 'unique'],
            [['ID'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'LEVEL_NAME' => '级别名称',
            'SORT' => '排序',
            'CREATED_AT' => '创建时间',
            'UPDATED_AT' => '更新时间',
            'CREATE_ADMIN' => '创建人',
            'UPDATE_ADMIN' => '更新人',
            'ICON_TYPE' => '图标类型',
            'ICON_NUM' => '图标个数',
            'MIN_LEVEL_ID' => '上级ID',
            'LEVEL_SCORE' => '级别分数',
            'UPGRADE_SCORE' => '升级分数',
            'TOURISM_PERCENT' => '旅游奖比例',
            'GARAGE_PERCENT' => '车房奖比例',
        ];
    }

    /**
     * 获取全部级别以数字索引的方式展现
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getAllDataWithNumIndex()
    {
        return static::find()->where('1=1')->orderBy('SORT ASC, CREATED_AT ASC')->indexBy('SORT')->asArray()->all();
    }

    /**
     * 获取全部配置
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getAllData()
    {
        return static::find()->where('1=1')->orderBy('SORT ASC, CREATED_AT ASC')->indexBy('ID')->asArray()->all();
    }

    // 获取级别配置一维度数组,id为键,级别等级为值
    public static function getIdConvertLevelSort()
    {
        $ret = [];
        $allData = static::find()->where('1=1')->orderBy('SORT ASC, CREATED_AT ASC')->indexBy('ID')->asArray()->all();
        foreach($allData as $data) {
            $ret[$data['ID']] = $data['SORT'];
        }
        return $ret;
    }

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

        return $data;
    }

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

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

    /**
     * 通过排序获取级别
     * @param int $sort
     * @return mixed
     */
    public static function getLevelFromSort(int $sort)
    {
        static $crownLevels;
        if(!$crownLevels){
            $crownLevels = self::getFromCache();
            $crownLevels = array_column($crownLevels, null, 'sort');
        }
        return $crownLevels[$sort];
    }

    /**
     * 通过排序获取ID
     * @param int $sort
     * @return mixed
     */
    public static function getIdFromSort(int $sort)
    {
        $level = self::getLevelFromSort($sort);
        return $level['ID'];
    }

    /**
     * 获取默认级别
     * @return mixed
     */
    public static function getDefaultLevelId()
    {
        return self::NO_LEVEL_ID;
    }

    /**
     * 获取星级的排序
     * @param $id
     * @return mixed
     */
    public static function getSortById($id)
    {
        $crownLevels = self::getFromCache();
        return $crownLevels[$id]['SORT'] ?? 0;
    }

    /**
     * 通过ID获取星级名称
     * @param $levelId
     * @return mixed'
     */
    public static function getNameById($levelId)
    {
        return self::findOneAsArray('ID = :ID', [':ID' => $levelId])['LEVEL_NAME'] ?? '';
    }

    /**
     * 奖金参数
     */
    public static function getBonusConfig(){
        $allData = self::getAllData();
        $data = [];
        foreach ($allData as $value) {
            $data[$value['ID']]['label'] = $value['LEVEL_NAME'];
            $data[$value['ID']]['value'] = '【旅游奖】拿奖比例' . $value['TOURISM_PERCENT'] . '%,' . '【车房奖】拿奖比例' . $value['GARAGE_PERCENT'] . '%';
        }
        return $data;
    }

    /**
     * 根据业绩计算星级
     * @param $payLeg
     * @return array|mixed|\yii\db\ActiveRecord
     */
    public static function getStarCrown($payLeg)
    {
        $starCrown = [];
        $allData = self::getAllData();
        // 最大边界值
        $maxData = end($allData);
        if ($payLeg >= $maxData) {
            return $maxData;
        }

        foreach ($allData as $item) {
            if (($payLeg >= $item['LEVEL_SCORE']) && ($payLeg < $item['UPGRADE_SCORE'])) {
                $starCrown = $item;
                break;
            }
        }

        return $starCrown ?: $allData[self::NO_LEVEL_ID];
    }
}
