<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\model\GameBetGameModel;
use app\model\GameBetOrderModel;
use app\model\GameStatisModel;
use app\common\CommonUtils;
use app\model\GameModel;
use think\facade\Request;

class GameStatis extends BaseController
{    
    /**
     * 获取游戏每日数据列表
     */
    public function Daily()
    {
        $userInfo = $this->request->userInfo;
        
        // 获取查询参数
        $page = Request::get('page', 1, 'intval');
        $limit = Request::get('limit', 10, 'intval');

        // 筛选条件
        $filters = [
            // 时间筛选
            'start_time' => Request::get('start_time', date('Y-m-d', strtotime('-7 days')), 'trim'),
            'end_time' => Request::get('end_time', date('Y-m-d'), 'trim'),
            'game_id' => Request::get('game_id', '', 'trim'),
        ];
        
        try {
            // 获取游戏每日数据
            $result = GameStatisModel::getGameDailyList(
                $userInfo['merchant_id'],
                $page, 
                $limit,
                $filters,
            );

            // 获取游戏信息信息
            $game_ids = array_unique(array_column($result['list'], 'game_id'));
            $tempGameList = GameModel::where([['merchant_id', '=', $userInfo['merchant_id']], ['game_id', 'in', $game_ids]])
                                        ->field(['game_id','title','image', 'game_platform'])
                                        ->select()
                                        ->toArray();
            $gameList = [];
            foreach ($tempGameList as $game) {
                $game_id = $game['game_id'];
                $gameList[$game_id] = $game;
            }            
            
            // 格式化数据
            foreach ($result['list'] as &$item) {
                $game_id = $item['game_id'];
                $gameInfo = $gameList[$game_id] ?? [];
                if (!empty($gameInfo))
                {
                    $gameImages = CommonUtils::getGameDefaultImage($gameInfo);
                }
                $item['game_image_url'] = $gameImages['image_url'] ?? '';
                $item['game_title'] = $gameInfo['title'] ?? '';
                $item['game_type_text'] = CommonUtils::getGameTypeConfig($gameInfo['game_platform']);
                $item['game_profit'] = CommonUtils::convertBalance($item['game_profit'], false);
                $item['bet_amount'] = CommonUtils::convertBalance($item['bet_amount'], false);
                $item['commission_amount'] = CommonUtils::convertBalance($item['game_profit'] * 0.08, false);
                $item['platform_fee'] = CommonUtils::convertBalance($item['bet_amount'] * 0.08, false);
                $item['buy_free_bet'] = $item['buy_free_bet_count'] ?? 0;
            }
            
            return json_success($result, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取游戏每日数据失败：' . $e->getMessage());
        }
    }   
    
    /**
     * 游戏输赢汇总
     */
    public function Summary()
    {
        $userInfo = $this->request->userInfo;
        
        // 获取查询参数
        $page = Request::get('page', 1, 'intval');
        $limit = Request::get('limit', 10, 'intval');
        
        // 筛选条件
        $filters = [
            'start_date' => Request::get('start_date', date('Y-m-d'), 'trim'),
            'end_date' => Request::get('end_date', date('Y-m-d'), 'trim'),
            'game_id' => Request::get('game_id', '', 'trim'),
        ];
        
        try {
            // 获取游戏汇总数据
            $result = GameStatisModel::getGameSummary(
                $userInfo['merchant_id'],
                $page, 
                $limit,
                $filters
            );
            
            // 获取游戏信息
            if (!empty($result['list'])) {
                $game_ids = array_unique(array_column($result['list'], 'game_id'));
                $tempGameList = GameModel::where([
                    ['merchant_id', '=', $userInfo['merchant_id']], 
                    ['game_id', 'in', $game_ids]
                ])
                ->field(['game_id','title','image', 'game_platform', 'rtp'])
                ->select()
                ->toArray();
                
                $gameList = [];
                foreach ($tempGameList as $game) {
                    $game_id = $game['game_id'];
                    $gameList[$game_id] = $game;
                }
                
                // 格式化数据
                foreach ($result['list'] as &$item) {
                    $game_id = $item['game_id'];
                    $gameInfo = $gameList[$game_id] ?? [];
                    
                    // 游戏信息
                    $item['game_title'] = $gameInfo['title'] ?? '未知游戏';
                    $item['game_platform'] = CommonUtils::getGameTypeConfig($gameInfo['game_platform']);
                    $item['rtp'] = $gameInfo['rtp'] ?? '';

                    // 计算游戏RTP
                    $item['game_rtp'] = $item['total_bet'] > 0 ? bcdiv($item['total_score'], $item['total_bet'], 4) * 100 : 0;                    
                    
                    // 格式化数据
                    $item['game_id'] = (int) $item['game_id'];
                    $item['buy_game_amount'] = (int) $item['buy_game_amount'];
                    $item['total_bet'] = CommonUtils::convertBalance($item['total_bet'], false);
                    $item['total_win'] = CommonUtils::convertBalance($item['total_win'], false);
                    $item['total_score'] = CommonUtils::convertBalance($item['total_score'], false);
                    
                    // 计算历史游戏RTP
                    if (isset($result['history'][$game_id])) {
                        $history = $result['history'][$game_id];
                        $item['history_rtp'] = (float) bcdiv($history['total_score'], $history['total_bet'], 4) * 100;
                    } else {
                        $item['history_rtp'] = 0;
                    }
                }
            }
            
            // 计算汇总数据
            $summary = [
                'total_bet' => CommonUtils::convertBalance($result['summary']['total_bet'], false), 
                'total_bet_count' => $result['summary']['total_bet_count'], 
                'total_win' => CommonUtils::convertBalance($result['summary']['total_win'], false),
                'total_user_count' => $result['summary']['total_user_count'], 
            ];
            
            return json_success([
                'list' => $result['list'],
                'total' => $result['total'],
                'page' => $page,
                'limit' => $limit,
                'summary' => $summary
            ], '获取成功');
            
        } catch (\Exception $e) {
            return json_error([], '获取游戏汇总数据失败：' . $e->getMessage());
        }
    }
    
    /**
     * 档位押注数据
     */
    public function BetLevel()
    {
        $userInfo = $this->request->userInfo;
        
        // 获取查询参数
        $page = Request::get('page', 1, 'intval');
        $limit = Request::get('limit', 10, 'intval');
        
        // 筛选条件
        $filters = [
            'start_date' => Request::get('start_date', date('Y-m-d'), 'trim'),
            'end_date' => Request::get('end_date', date('Y-m-d'), 'trim'),
            'game_id' => Request::get('game_id', '', 'trim'),
        ];
        
        try {
            // 获取档位押注数据
            $result = GameStatisModel::getBetLevelData(
                $userInfo['merchant_id'],
                $page, 
                $limit,
                $filters
            );
            
            // 获取游戏信息
            if (!empty($result['list'])) {
                $game_ids = array_unique(array_column($result['list'], 'game_id'));
                $tempGameList = GameModel::where([
                    ['merchant_id', '=', $userInfo['merchant_id']], 
                    ['game_id', 'in', $game_ids]
                ])
                ->field(['game_id','title', 'game_platform'])
                ->select()
                ->toArray();
                
                $gameList = [];
                foreach ($tempGameList as $game) {
                    $game_id = $game['game_id'];
                    $gameList[$game_id] = $game;
                }
                
                // 格式化数据
                foreach ($result['list'] as &$item) {
                    $game_id = $item['game_id'];
                    $gameInfo = $gameList[$game_id] ?? [];
                    
                    // 游戏信息
                    $item['game_title'] = $gameInfo['title'] ?? '未知游戏';
                    $item['game_platform'] = CommonUtils::getGameTypeConfig($gameInfo['game_platform']);
                    
                    // 游戏RTP
                    $item['game_rtp'] = bcmul(bcdiv($item['total_score'], $item['total_bet'], 4), "100", 2);

                     $item['bet'] = CommonUtils::convertBalance($item['bet'], false);
                    $item['total_bet_rate'] = bcmul(bcdiv($item['total_bet'], $result['total_stats']['total_bet_all'], 4), "100", 2);
                    $item['total_bet'] = CommonUtils::convertBalance($item['total_bet'], false);
                    $item['bet_count_rate'] = bcmul(bcdiv((string)$item['bet_count'], (string)$result['total_stats']['total_count_all'], 4), "100", 2);
                    $item['bet_count'] = ($item['bet_count']);
                    
                    // 游戏输赢
                    $item['total_win'] = CommonUtils::convertBalance($item['total_win'], false);
                    // 游戏返奖
                    $item['total_score'] = CommonUtils::convertBalance($item['total_score'], false);                    
                }
            }
            
            return json_success([
                'list' => $result['list'],
                'total' => $result['total'],
                'page' => $page,
                'limit' => $limit
            ], '获取成功');
            
        } catch (\Exception $e) {
            return json_error([], '获取档位押注数据失败：' . $e->getMessage());
        }
    }
}