<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

namespace app\adminapi\lists\user;

use app\adminapi\lists\BaseAdminDataLists;
use app\common\model\User;
use app\common\model\UserLevel;

/**
 * 会员等级列表
 * Class UserLevelLists
 * @package app\adminapi\lists\user
 */
class UserLevelLists extends BaseAdminDataLists
{

    /**
     * @notes 会员等级列表
     * @return array
     */
    public function lists(): array
    {
        // 1. 获取等级定义
        $lists = UserLevel::field('id,name,rank,image,discount,experience')
            ->limit($this->limitOffset, $this->limitLength)
            ->order('rank', 'asc')
            ->select();

        // 2. 统计逻辑：由于数据库中的 user.level 字段可能因为之前的 Bug 导致不准确，
        // 这里采用实时积分统计法，确保后台看到的各等级人数是 100% 真实的。
        $allUsers = User::field('id,user_integral,level')->select();
        $levelThresholds = UserLevel::order('experience asc, rank asc')->select()->toArray();
        
        $realLevelCounts = [];
        foreach ($allUsers as $u) {
            $matchedLevelId = $levelThresholds[0]['id'] ?? 0;
            $integral = (int)$u->user_integral;
            
            foreach ($levelThresholds as $lt) {
                if ($integral >= (int)$lt['experience']) {
                    $matchedLevelId = $lt['id'];
                } else {
                    break;
                }
            }
            
            if (!isset($realLevelCounts[$matchedLevelId])) {
                $realLevelCounts[$matchedLevelId] = 0;
            }
            $realLevelCounts[$matchedLevelId]++;
        }

        // 3. 组装数据
        foreach ($lists as $level) {
            if($level->discount > 0){
                $level->discount = floatval($level->discount).'折';
            }else{
                $level->discount = '无';
            }
            // 使用校准后的真实人数
            $level->num = $realLevelCounts[$level->id] ?? 0;
        }

        return $lists->toArray();
    }

    /**
     * @notes 会员等级总数
     * @return int
     */
    public function count(): int
    {
        return UserLevel::count();
    }
}