<?php
declare (strict_types = 1);

namespace app\controller;

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

/**
 * 游戏记录控制器
 */
class GameRecord extends BaseController
{
    /**
     * 获取游戏记录列表
     */
    public function list()
    {
        $userInfo = $this->request->userInfo;
        
        // 获取查询参数
        $page = Request::get('page', 1, 'intval');
        $limit = Request::get('limit', 20, 'intval');
        $compress = Request::get('compress', 0, 'intval');

        // 筛选条件
        $filters = [
            // 时间筛选
            'start_time' => Request::get('start_time', '', 'trim'),
            'end_time' => Request::get('end_time', '', 'trim'),
            // 游戏筛选
            'game_id' => Request::get('game_id', '', 'trim'),
            // 牌局编号筛选
            'third_round_id' => Request::get('third_round_id', '', 'trim'),
            // 平台ID筛选
            'uname' => Request::get('uname', '', 'trim'),
            // 玩家ID筛选
            'player_id' => Request::get('user_id', '', 'trim'), 
            // 平台昵称
            'nickname' => Request::get('nickname', '', 'trim'),
            // 游戏玩法类型筛选
            'bet_game_play_type' => Request::get('bet_game_play_type', '', 'trim'),
        ];
        
        try {
            // 获取游戏记录列表
            $result = GameBetGameModel::getBetGameList($userInfo['merchant_id'], $page, $limit, $filters);
            
            if (empty($result['list'])) {
                return json_success($result, '获取成功');
            }
            
            
            // 获取游戏信息信息
            $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;
            }
            
            // 获取母单号列表
            $thirdGids = array_unique(array_column($result['list'], 'third_gid'));

            $childOrderList = [];
            if (count($thirdGids) > 0) {
                $tempCheckList = GameBetGameModel::where([ ['third_gid', 'in', $thirdGids], ['action_type','=',2] ])->withoutField('result')->select()->toArray();
                foreach ($tempCheckList as $item) {
                    if(!isset($childOrderList[$item['third_gid']])) {
                        $childOrderList[$item['third_gid']] = [];
                    }
                    $item = $this->formatItemDataText($item);
                    $item['id'] = 'm_' . $item['id'];
                    $childOrderList[$item['third_gid']][] = $item;
                }
            }
            
            // 格式化数据并添加子订单
            $newDataList = [];
            foreach ($result['list'] as $item) {
                $item = $this->formatItemDataText($item);
                $thirdGid = $item['third_gid'];
                $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($item['game_type']);
                $item['c_count'] = count($childOrderList[$thirdGid] ?? []);
                $item['view_layout_url'] = $GLOBALS['gameGameLayoutDomain'] . "/{$game_id}.html?sid={$thirdGid}&pf=1&lang=zh&api=".Request::host()."%2Fgame_record%2Flayout";

                $children = [];
                if (isset($childOrderList[$thirdGid])) {
                    $childList = $childOrderList[$thirdGid];
                    foreach ($childList as $citem) {
                        $citem['game_type_text'] = $item['game_type_text'];
                        $citem['game_image_url'] = $item['game_image_url'];
                        $citem['game_title'] = $item['game_title'];
                        $children[] = $citem;
                    }
                }

                $newDataList[] = $item;
                $newDataList = array_merge($newDataList, $children);
            }
            
            $result['list'] = $newDataList;
            if ($compress == 1)
            {
                $return = [
                    'state' => 1,
                    'code' => 0,
                    'data' => $result,
                    'message' => "获取成功"
                ];
                return base64_encode(gzcompress(json_encode($return)));
            }

            return json_success($result, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取游戏记录失败：' . $e->getMessage());
        }
    }
    
    public function layout()
    {
        $game_id = Request::param('gid', '');
        $sid = Request::param('sid', '');
        if (empty($game_id) || empty($sid)) {
            return CommonUtils::gameJsonError();
        }

        $model = new GameBetGameModel();
        $wheres = [
            ['game_id', '=', $game_id],
            ['third_round_id', '=', $sid],
            ['action_type', '=', 1],
        ];

        $bet_game_info = $model->where($wheres)->find();
        if (empty($bet_game_info)) {
            return CommonUtils::gameJsonError();
        }
        $bet_game_info = $bet_game_info->toArray();
        $dataList = [$bet_game_info];

        $result = json_decode($bet_game_info['result'],true);
        $ge = [];
        foreach ($result as $key => $res) {
            $ge = array_merge($ge, $res['ge']);
        }
        $ge = array_values(array_unique($ge));
        array_map(function ($value) {
            return $value * 1;
        }, $ge);

        $thirdGidList = array_column($dataList, 'third_gid');
        $newFilter = [
            ['third_gid', 'in',  $thirdGidList],
            ['action_type','=', 2],
        ];
        $tempDataList = $model->where($newFilter)->select()->toArray();
        $childDataConfig = [];
        foreach ($tempDataList as $item) {
            $third_gid = $item['third_gid'];
            if(!isset($childDataConfig[$third_gid])) {
                $childDataConfig[$third_gid]= [];
            }
            $childDataConfig[$third_gid][] = $item;
        }

        $newDataList = [];
        foreach ($dataList as $item) {
            $third_gid = $item['third_gid'];
            $result = json_decode($item['result'], true);
            $ge = [];
            foreach ($result as $key => $res) {
                $ge = array_merge($ge, $res['ge']);
            }
            $ge = array_values( array_unique($ge));
            array_map(function ($value) {
                return $value * 1;
            }, $ge);

            $childData = $childDataConfig[$third_gid] ?? [];
            if (!empty($result) && count($result) > 0){
                $firstResult = $result[0];
                $tempItem = array_merge($item, [
                    'result' => json_encode($firstResult),
                ]);
                array_unshift($childData, $tempItem);
            }

            $mgcc = 0;
            $bd = [];
            foreach ($childData as $index => $citem) {
                $result = json_decode($citem['result'], true);
                $result['cs'] *= 1;
                $result['ml'] *= 1;

                if($result['nst'] == 4) {
                    $mgcc += 1;
                }

                $bd[] = [
                    'bl' => CommonUtils::convertBalance( $citem['balance_amount'], false),
                    'bt' => strtotime($citem['create_time']) * 1000,
                    'tba' => CommonUtils::convertBalance( $citem['bet'], false),
                    'twla' => CommonUtils::convertBalance( $citem['win_amount'], false),
                    'tid' => $citem['third_round_id'],
                    'gd' =>  array_merge(CommonUtils::formatResultData($result, false), [
                        'bl' => CommonUtils::convertBalance( $item['balance_amount'], false),
                        'blb' => CommonUtils::convertBalance( $item['prev_amount'], false),
                        'blab' => CommonUtils::convertBalance( $item['next_amount'], false),
                        'irs' => $result['irs'] ?? null,
                        'sid' => $citem['third_round_id'],
                        'psid' => $item['third_round_id'],
                    ])
                ];
            }

            $newDataList[] = [
                'bd' => $bd,
                'bt' => strtotime($item['create_time']) * 1000,
                'cc' => '',
                'fscc' => 0,
                'ge' => $ge,
                'gid' => $item['game_id'],
                'gtba' => CommonUtils::convertBalance( $item['bet'], false),
                'gtwla' => CommonUtils::convertBalance( $item['total_win_amount'], false),
                'mgcc' => $mgcc,
                'tid' => $third_gid
            ];
        }
        return CommonUtils::gameJsonSuccess([
            'bh' => $newDataList[0]
        ]);
    }
    
   // 格式化信息
    private function formatItemDataText($item = [])
    {
        $item['bet'] = CommonUtils::convertBalance($item['bet'], false);
        $item['prev_amount'] = CommonUtils::convertBalance($item['prev_amount'], false);
        $item['next_amount'] = CommonUtils::convertBalance($item['next_amount'], false);
        $item['total_amount']  = COmmonUtils::convertBalance($item['total_amount'], false);
        $item['win_amount']  = COmmonUtils::convertBalance($item['win_amount'], false);
        $item['total_win_amount']  = COmmonUtils::convertBalance($item['total_win_amount'], false);
        $item['res_multiple'] = $item['res_multiple'] / 100;
        $item['bet_game_play_type'] = CommonUtils::getGamePlayType($item['bet_game_play_type']);
        return $item;
    }    
}