<?php
// 文件路径: app/UserAgentCommission.php

namespace App\Game;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

class AgentCommission extends Model
{
    protected $table = 'webgame.AgentCommission';
    protected $fillable = ['Level', 'BRL', 'USD','MXN','RUB','EUR', 'Rate'];
    protected $connection='mysql';

    private static $_commissionData=null;
    // 缓存提成数据
    public static function cacheCommissionData()
    {
        self::$_commissionData = self::all()->keyBy('Level')->toArray();
        foreach (self::$_commissionData as $k => &$v) {
            $v['BRL'] = $v[env('CONFIG_24680_CURRENCY')];
        }
        Redis::set('UserAgentCommission', json_encode(self::$_commissionData));
    }

    // 获取缓存中的提成数据
    public static function getCommissionData()
    {
        if(self::$_commissionData)return self::$_commissionData;
        $commissionData = Redis::get('UserAgentCommission');
        if ($commissionData) {
            self::$_commissionData=json_decode($commissionData, true);
            return self::$_commissionData;
        } else {
            self::cacheCommissionData();
            return self::getCommissionData();
        }
    }

    // 根据业绩获取对应的 level 和 rate
    public static function getLevelAndRate($performance,$DefaultCurrency=null)
    {
        $commissionData = self::getCommissionData();
        if(!$DefaultCurrency)$DefaultCurrency=env('CONFIG_24680_CURRENCY');
        //判断是否存在于数据表中的货币
        if(!in_array($DefaultCurrency,array_keys($commissionData['1']))){
            $DefaultCurrency='USD';
        }
        $lastData=$commissionData[1];
        foreach ($commissionData as $data) {
            if ($performance < $data[$DefaultCurrency]) {
                return ['level' => $lastData['Level'], 'rate' => $lastData['Rate']];
            }
            $lastData=$data;
        }

        // 如果业绩超出表中最大值，返回最高级别
        return ['level' => end($commissionData)['Level'], 'rate' => end($commissionData)['Rate']];
    }

    // 监听模型的保存和删除事件
    protected static function boot()
    {
        parent::boot();

        static::saved(function ($model) {
            self::cacheCommissionData();
        });

        static::deleted(function ($model) {
            self::cacheCommissionData();
        });
    }
}

