<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use think\facade\Request;
use app\model\GameBetOrderModel;
use app\model\GameModel;
use app\model\GameCheckBetOrder;
use app\model\GameResultBetOrder;
use app\common\CommonUtils;

/**
 * 游戏订单控制器
 */
class GameOrder extends BaseController
{
    /**
     * 获取订单记录列表
     */
    public function list()
    {
        $userInfo = $this->request->userInfo;
        
        // 获取查询参数
        $page = Request::get('page', 1, 'intval');
        $limit = Request::get('limit', 20, 'intval');
        
        // 筛选条件
        $filters = [
            // 时间筛选
            'start_time' => Request::get('start_time', '', 'trim'),
            'end_time' => Request::get('end_time', '', 'trim'),
            // 游戏筛选
            'game_id' => Request::get('game_id', '', 'trim'),
            // 订单原因筛选
            'order_reason' => Request::get('order_reason', '', 'trim'),
            // 平台ID筛选
            'uname' => Request::get('uname', '', 'trim'),
            // 玩家ID筛选
            'player_id' => Request::get('user_id', '', 'trim'), 
            // 平台昵称
            'nickname' => Request::get('nickname', '', 'trim'),
            // 订单状态筛选
            'order_status' => Request::get('order_status', ''),
            // 订单编号筛选
            'third_order_id' => Request::get('third_order_id', '', 'trim'),
            // 母单号筛选
            'third_gid' => Request::get('third_gid', '', 'trim'),
            // 牌局编号筛选
            'third_round_id' => Request::get('third_round_id', '', 'trim'),
        ];
        
        try {
            // 获取主订单列表
            $result = GameBetOrderModel::getBetOrderList($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 = GameCheckBetOrder::where([ ['third_gid', 'in', $thirdGids] ])->select()->toArray();
                $tempResultList = GameResultBetOrder::where([['third_gid', 'in', $thirdGids] ])->select()->toArray();
                $tempList = array_merge($tempCheckList, $tempResultList);
                foreach ($tempList 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']);

                $children = [];
                if (isset($childOrderList[$thirdGid])) {
                    $item['children'] = [];
                    $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;
            return json_success($result, '获取成功');
        } catch (\Exception $e) {
            print_r($e->getTraceAsString());
            return json_error([], '获取订单记录失败：' . $e->getMessage());
        }
    }
                    
   // 格式化信息
    private function formatItemDataText($item = [])
    {
        $item['amount'] = CommonUtils::convertBalance($item['amount'], false);
        $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_win_amount'] = CommonUtils::convertBalance($item['total_win_amount'], false);
        $item['total_amount'] = CommonUtils::convertBalance($item['total_amount'], false);
        return $item;
    }    
}