<?php

namespace common\models;

use common\helpers\Cache;
use Yii;

/**
 * This is the model class for table "{{%DECLARATION_LEVEL}}".
 *
 * @property string $ID
 * @property string $LEVEL_NAME 级别名称
 * @property string $PERF 累计业绩
 * @property string $QY_PERCENT 区域津贴百分比
 * @property string $QY_TOUCH_CAP 对碰封顶
 * @property string $QY_BIG_CAP 大区封顶
 * @property int $FX_MIN_DEEP 复销奖拿奖最小层数
 * @property int $FX_MAX_DEEP 复销奖拿奖最大层数
 * @property string $FX_PERCENT 复销奖百分比
 * @property int $IS_ADJUST_GIFT 是否可调整礼包
 * @property int $IS_DEC 是否可以报单
 * @property int $SORT 级别排序
 * @property string $CREATE_ADMIN 创建人
 * @property string $UPDATE_ADMIN 更新人
 * @property int $CREATED_AT 创建时间
 * @property int $UPDATED_AT 更新时间
 * @property int $GL_ODD_DEEP_ONE 奇数代数（推荐1人）
 * @property int $GL_ODD_DEEP_TWO 奇数代数（推荐2人）
 * @property int $GL_ODD_DEEP_THREE 奇数代数（推荐3人）
 * @property int $INCOME_CAP 收入封顶
 */
class DeclarationLevel extends \common\components\ActiveRecord
{
    const YIN_ZUAN_LEVEL_ID = '67ABCCE20A9F5553E055736AECE8677A'; //'67ABCB8C1F7D5519E055736AECE8644D';
    const JIN_ZUAN_LEVEL_ID = '67ABCCE20A9F5553E055736AECE8644D';
    const VIP_LEVEL_ID      = '67ABCE0ECE705575E055736AECE8644D';

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['LEVEL_NAME', 'CREATE_ADMIN', 'CREATED_AT'], 'required'],
            [['PERF', 'QY_PERCENT', 'QY_TOUCH_CAP', 'QY_BIG_CAP', 'FX_PERCENT', 'GL_ODD_DEEP_ONE', 'GL_ODD_DEEP_TWO', 'GL_ODD_DEEP_THREE', 'INCOME_CAP'], 'number'],
            [['FX_MIN_DEEP', 'FX_MAX_DEEP', 'IS_ADJUST_GIFT', 'IS_DEC', 'SORT', 'CREATED_AT', 'UPDATED_AT'], 'integer'],
            [['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' => '级别名称',
            'PERF' => '累计业绩',
            'QY_PERCENT' => '区域津贴百分比',
            'QY_TOUCH_CAP' => '对碰封顶',
            'QY_BIG_CAP' => '大区封顶',
            'FX_MIN_DEEP' => '复销奖拿奖最小层数',
            'FX_MAX_DEEP' => '复销奖拿奖最大层数',
            'FX_PERCENT' => '复销奖百分比',
            'IS_ADJUST_GIFT' => '是否可调整礼包',
            'IS_DEC' => '是否可以报单',
            'SORT' => '级别排序',
            'CREATE_ADMIN' => '创建人',
            'UPDATE_ADMIN' => '更新人',
            'CREATED_AT' => '创建时间',
            'UPDATED_AT' => '更新时间',
            'GL_ODD_DEEP_ONE' => '奇数代数（推荐1人）',
            'GL_ODD_DEEP_TWO' => '奇数代数（推荐2人）',
            'GL_ODD_DEEP_THREE' => '奇数代数（推荐3人）',
            'INCOME_CAP' => '收入封顶',
        ];
    }

    /**
     * 从缓存获取信息
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getFromCache(){
        $data = Yii::$app->cache->get(Cache::DEC_LEVEL_CONFIG_KEY);
        Yii::$app->cache->delete(Cache::DEC_LEVEL_CONFIG_KEY);
        if(!$data){
            // 获取信息
            $data = static::find()->where('1=1')->orderBy('PERF ASC, CREATED_AT ASC')->indexBy('ID')->asArray()->all();
            Yii::$app->cache->set(Cache::DEC_LEVEL_CONFIG_KEY, $data);
        }
        // i18n转换
        foreach ($data as &$item) {
            $item['LEVEL_NAME'] = Yii::t('ctx', $item['LANGUAGE_KEY']);
        }

        return $data;
    }

    // 获取最大的业绩信息
    public static function getMaxDecPref() {
        $data = static::find()
        ->where('1=1')
        ->orderBy('PERF DESC')
        ->indexBy('ID')
        ->asArray()
        ->one();

        return $data;
    }

    // 获取下一级业绩数据
    public static function getNextDecPref($perf) {
        $data = static::find()
        ->where('PERF>:PERF',
            [
                'PERF'=>$perf,

            ]
        )
        ->orderBy('PERF ASC')
        ->indexBy('ID')
        ->asArray()
        ->one();

        return $data;
    }

    public static function getNextAll($perf){
        $data = static::find()
        ->where('PERF>:PERF',
            [
                'PERF'=>$perf,

            ]
        )
        ->indexBy('ID')
        ->orderBy('SORT ASC')
        ->asArray()
        ->all();

        return $data;
    }

    /**
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getAllData(){
        $records = static::find()->where('1=1')->indexBy('ID')->orderBy('SORT ASC')->asArray()->all();
        foreach ($records as &$record) {
            $record['LEVEL_NAME'] = Yii::t('ctx', $record['LANGUAGE_KEY']);
        }

        return $records;
    }

    public static function getData(){
        $records = static::find()->where('STATUS=1')->orderBy('SORT ASC')->asArray()->all();

        foreach ($records as &$record) {
            $record['LEVEL_NAME'] = Yii::t('ctx', $record['LANGUAGE_KEY']);
        }

        return $records;
    }

    public static function getNextDecLv($decLvID)
    {
        $result = [];
        $decLv = static::find()->where('1=1')->indexBy('ID')->orderBy('SORT ASC')->asArray()->all();
        $current = $decLv[$decLvID]['SORT'] ?? '';
        foreach ($decLv as $id => $item) {
            if ($item['SORT'] == $current + 1) {
                $result = $item;
                break;
            }
        }

        return $result;
    }

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

    /**
     * 通过排序获取级别
     * @param int $sort
     * @return mixed|\yii\db\ActiveRecord
     */
    public static function getLevelFromSort(int $sort){
        $empLevels = self::getFromCache();
        foreach($empLevels as $level){
            if($level['SORT'] == $sort){
                return $level;
            }
        }
        return [];
    }

    /**
     * 通过排序获取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::YIN_ZUAN_LEVEL_ID;
    }

    /**
     * 通过pv获取对应的报单级别
     * @param $pv
     * @return mixed
     */
    public static function getLevelIdFromPv($pv){
        $levelConfig = self::getFromCache();
        $result = self::getDefaultLevelId();
        foreach($levelConfig as $level){
            if($pv >= $level){
                $result = $level['ID'];
            }
        }
        return $result;
    }

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

    /**
     * 通过会员ID获得报单级别名称
     * @param $userId
     * @return string
     */
    public static function getLevelNameFromUserId($userId){
        $levelId = self::getLevelIdFromUserId($userId);
        $level = self::findOneAsArray('ID=:ID', [':ID'=>$levelId]);
        return $level ? $level['LEVEL_NAME'] : '';
    }

    /**
     * 通过ID获取报单级别名称
     * @param $levelId
     * @return mixed
     */
    public static function getNameById($levelId){
        $data = self::findOneAsArray('ID=:ID', [':ID'=>$levelId]);
        return $data['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['QY_PERCENT'].'%,奖金封顶'.$value['QY_TOUCH_CAP'].'元/碰,大区封顶'.$value['QY_BIG_CAP'].'积分；【复销奖】最小层数'.$value['FX_MIN_DEEP'].',最大层数'.$value['FX_MAX_DEEP'].',拿奖比例'.$value['FX_PERCENT'].'%';
        }
        return $data;
    }
}
