<?php
declare (strict_types = 1);

namespace app\controller;

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

class TrendStatis extends BaseController
{    
    /**
     * 在线走势
     */
    public function Online()
    {
        $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'])->select()->toArray();
            $gameList = [];
            foreach ($tempGameList as $item) {
                $game_id = $item['game_id'];
                $gameList[$game_id] = $item;
            }            
            
            // 格式化数据
            foreach ($result['list'] as &$item) {
                $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'] = 0;
                $item['game_title'] = $gameList[$item['game_id']]['title'] ?? '';
            }
            
            return json_success($result, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取游戏每日数据失败：' . $e->getMessage());
        }
    }  
    
    /**
     * 游戏走势
     */
    public function Game() {

    }

    /**
     * 输赢走势
     */
    public function Win() {
        $userInfo = $this->request->userInfo;
        
        // 获取查询参数
        $filters = [
            'date' => Request::get('date', '', 'trim'),
            'game_id' => Request::get('game_id', '', 'trim'),
            'currency' => Request::get('currency', 'USDT', 'trim')
        ];
        
        try {
            // 获取输赢走势数据
            $result = TrendStatisModel::getWinLoseTrend($userInfo['merchant_id'],$filters);
            for ($i = 0; $i < 24; $i++) {
                $list[] = ['hour' => $i, 'total_win' => 0];
            }
            if ($result) {
                $result = array_column($result, null, 'hour');
                foreach ($list as &$item) {  
                    if (isset($result[$item['hour']])) {
                        $item['total_win'] = (float)$result[$item['hour']]['total_win'];
                    }
                }
            }
                        
            usort($list, function ($a, $b) {
                return (int)$a['hour'] < (int)$b['hour'] ? -1 : 1;                
            });
            return json_success($list, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取输赢走势失败：' . $e->getMessage());
        }
    }
    
    /**
     * 返奖倍数走势
     */
    public function PrizeMultiple() {
        $userInfo = $this->request->userInfo;
        
        // 获取查询参数
        $filters = [
            'date' => Request::get('date', '', 'trim'),
            'game_id' => Request::get('game_id', '', 'trim'),
        ];
        
        try {
            // 获取输赢走势数据
            $result = TrendStatisModel::getMultipleTrend(
                $userInfo['merchant_id'],
                $filters
            );

            for ($i = 0; $i < 24; $i++) {
                $list[] = ['hour' => $i, 'total_win' => 0];
            }  
            if ($result) {
                $result = array_column($result, null, 'hour');
                foreach ($list as &$item) {  
                    if (isset($result[$item['hour']])) {
                        $item['total_multiple'] = (float)$result[$item['hour']]['total_multiple'];
                    }
                }
            }                      
                        
            usort($list, function ($a, $b) {
                return (int)$a['hour'] < (int)$b['hour'] ? -1 : 1;                
            });
            return json_success($list, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取返奖倍数走势失败：' . $e->getMessage());
        }
    }

    /**
     * 商户每日走势
     */
    public function MerchantDaily() {
        $userInfo = $this->request->userInfo;
        
        // 筛选条件
        $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 = TrendStatisModel::getMerchantDailyTrend(
                $userInfo['merchant_id'],
                $filters
            );
            for ($i = strtotime($filters['start_time']); $i <= strtotime($filters['end_time']); $i += 86400) {
                $list[] = [
                    'date' => intval(date('Ymd', $i)), 
                    'total_win' => 0,
                    'total_bet' => 0,
                    'bet_count' => 0,
                    'bet_users' => 0,
                    'rtp' => 0,
                ];
            }              

            if ($result) {
                $result = array_column($result, null, 'date');
                foreach ($list as &$item) { 
                    if (isset($result[$item['date']])) {
                        $rowData = $result[$item['date']];
                        $item['total_win'] = (float)$rowData['total_win'];
                        $item['total_bet'] = (float)$rowData['total_bet'];
                        $item['bet_count'] = (int) $rowData['bet_count'];
                        $item['bet_users'] = (int) $rowData['bet_users'];
                        $item['rtp'] = calculateRTP($rowData['total_win'], $rowData['total_bet']);
                    }
                }
            }            
            
            usort($list, function ($a, $b) {
                return (int)$a['date'] < (int)$b['date'] ? -1 : 1;                
            });
            return json_success($list, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取商户每日走势失败：' . $e->getMessage());
        }
    }
    
}