<?php

namespace app\controller;

use app\BaseController;
use app\model\MerchantStatisModel;
use app\common\CommonUtils;
use app\model\GameBetGameModel;
use app\model\MerchantsUserModel;
use app\model\PlayerLoginLogModel;
use think\facade\Request;

class Overview extends BaseController
{
    /**
     * 仪表盘 - 获取概览统计数据
     */
    public function Dashboard()
    {
        $userInfo = $this->getUserInfo();
        
        try {
            // 获取昨、今日时间范围
            $today = date('Y-m-d');
            $filtter = [
                'start_time' => date('Y-m-d', strtotime('yesterday')),
                'end_time' => date('Y-m-d', strtotime('tomorrow')),
            ];       
            $merchantId = $userInfo['merchant_id'];
            
            // 获取昨、今日游戏相关统计
            $dailySummary = GameBetGameModel::getGameDailySummary($merchantId, $filtter);
            // 获取玩家统计数据
            $playerSummary = MerchantsUserModel::getPlayerStatistics($merchantId, $filtter);
            $tempPlayerData = [];
            if ($playerSummary) {
                foreach ($playerSummary as $key => $row) {
                    foreach ($row as $date => $item) {
                        $date = $date == $today ? 'today' : 'yesterday';
                        $tempPlayerData[$key][$date] = $item;
                    }
                }                
            }

            if ($dailySummary) {
                foreach ($dailySummary as $row) {

                    $date = $row['date'] == $today ? 'today' : 'yesterday';
                    $row['commission'] = (float)bcmul($row['game_profit'], $GLOBALS['CommissionRate'], 2);
                    $row['bet_amount'] = (float)$row['bet_amount'];
                    $row['game_profit'] = (float)$row['game_profit'];
                    $row['register_users'] = CommonUtils::convertToInt($tempPlayerData['register'][$date]['count'] ?? 0);
                    $row['login_users'] = CommonUtils::convertToInt($tempPlayerData['login'][$date]['count'] ?? 0);
                    $row['online_users'] = CommonUtils::convertToInt($tempPlayerData['login'][$date]['count'] ?? 0);
                    $row['buy_free_bet_count'] = CommonUtils::convertToInt($row['buy_free_bet_count']);
                    $dashboardData[$date] = $row;
                }
            }
                      
            // 在线人数、登录数据
            $dashboardData['online_data'] = PlayerLoginLogModel::getLoginHourCount($merchantId, $filtter);;
            $dashboardData['login_data'] = $dashboardData['online_data'];

            return json_success($dashboardData, '获取成功');
            
        } catch (\Exception $e) {
            return json_error([], '获取仪表盘数据失败' . $e->getMessage());
        }
    }

    /**
     * 结算报表 - 按日期查询投注数据
     */
    public function SettlementReport() 
    {
        $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'),
        ];
        
        try {
            // 获取商户每日数据
            $result = MerchantStatisModel::getMerchantDailyList(
                $userInfo['merchant_id'],
                $page,
                $limit,
                $filters,                
            );
            
            // 格式化数据
            foreach ($result['list'] as &$item) {
                $item['game_profit'] = (float)$item['game_profit'];
                $item['game_profit_usdt'] = $item['game_profit'];
                $item['bet_amount'] = (float)$item['bet_amount'];
                $item['bet_amount_usdt'] = (int)$item['bet_amount'];
                $item['platform_fee'] = (float)bcmul($item['bet_amount'], $GLOBALS['CommissionRate'], 2);
                $item['platform_fee_usdt'] = $item['platform_fee'];
                $item['buy_free_bet_count'] = (int)$item['buy_free_bet_count'];
                $item['total_winning_score'] = (float)$item['total_winning_score'];
                $item['region'] = '';
            }
            
            return json_success($result, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取商户每日数据失败：' . $e->getMessage());
        }
    }

    /**
     * 导出结算报表
     */
    public function exportSettlement() {
        ;
    }
}