<?php
declare (strict_types = 1);

namespace app\controller;

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

class Game extends BaseController
{
    /**
     * 获取游戏列表
     */
    public function list()
    {
        // 获取当前用户信息
        $userInfo = $this->getUserInfo();
        
        // 获取查询参数
        $page = Request::get('page', 1, 'intval');
        $limit = Request::get('limit', 10, 'intval');
        
        // 过滤条件
        $filters = [
            'title' => Request::get('title', '', 'trim'),
            'game_id' => Request::get('game_id', 0, 'intval'),
            'game_platform' => Request::get('game_platform', ''),
            'status' => Request::get('status', ''),
            'order' => Request::get('order', 'id', 'trim'),
            'sort' => Request::get('sort', 'desc', 'trim'),
        ];
        
        try {
            // 获取游戏列表
            $result = GameModel::getGameList($userInfo['merchant_id'], $page, $limit, $filters);
            
            // 处理列表数据
            foreach ($result['list'] as &$game) {
                $game['status_text'] = GameModel::getStatusText($game['status']);
                $game['rtp_type_text'] = GameModel::getRtpTypeText($game['rtp_type']);
                $game['game_type_text'] = GameModel::getPlatFormText($game['game_platform']);                

                $gameImages = CommonUtils::getGameDefaultImage($game);
                $game['game_image_url'] = $gameImages['image_url'] ?? '';
                $game['image_en_url'] = $gameImages['image_en_url'] ?? '';
                $game['game_title'] = $game['title'] ?? '';
            }
            
            return json_success($result, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取游戏列表失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取游戏详情
     */
    public function detail()
    {
        // 获取当前用户信息
        $userInfo = $this->getUserInfo();
        
        $id = Request::get('id', 0, 'intval');
        if (!$id) {
            return json_error([], '游戏ID不能为空');
        }
        
        try {
            $game = GameModel::getGameDetail($userInfo['merchant_id'], ['id' => $id]);
            if (!$game) {
                return json_error([], '游戏不存在');
            }
            
            $game['status_text'] = GameModel::getStatusText($game['status']);
            $game['rtp_type_text'] = GameModel::getRtpTypeText($game['rtp_type']);
            $game['game_type_text'] = GameModel::getPlatFormText($game['game_platform']);                

            return json_success($game, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取游戏详情失败：' . $e->getMessage());
        }
    }
            
    /**
     * 更新游戏
     */
    public function update()
    {
        // 获取当前用户信息
        $userInfo = $this->getUserInfo();
        
        $id = Request::post('id', 0, 'intval');
        if (!$id) {
            return json_error([], '游戏ID不能为空');
        }
        
        // 检查游戏是否存在且属于当前商户
        $game = GameModel::getGameDetail($userInfo['merchant_id'], ['id' => $id]);
        if (!$game) {
            return json_error([], '游戏不存在');
        }
        
        // 获取请求中提供的所有可更新字段
        $requestData = Request::post();
        $allowedFields = [
            'rtp', 'rtp_type', 'free_game_status', 'bet_max_level', 'terminal_spin',
            'max_multiple_count', 'deposit_list', 'default_deposit', 'default_deposit_level', 'min_deposit',
        ];
        $updateData = [];
        
        // 只处理请求中存在且允许更新的字段
        foreach ($allowedFields as $field) {
            if (array_key_exists($field, $requestData)) {
                // 转换数值类型
                if (in_array($field, ['rtp_type', 'free_game_status', 'bet_max_level', 'terminal_spin', 'max_multiple_count', 'default_deposit_level'])) {
                    $updateData[$field] = intval($requestData[$field]);
                } elseif (in_array($field, ['rtp', 'default_deposit', 'min_deposit'])) {
                    $updateData[$field] = floatval($requestData[$field]);
                } else {
                    $updateData[$field] = $requestData[$field];
                }
            }
        }
        
        if (empty($updateData)) {
            return json_error([], '没有要更新的数据');
        }
        
        // 使用验证器进行字段验证
        $validate = new GameValidate();
        
        // 只验证传入的字段
        if (!$validate->only(array_keys($updateData))->check($updateData)) {
            return json_error([], $validate->getError());
        }
        
        try {
            GameModel::updateGame($userInfo['merchant_id'], $id, $updateData);
            return json_success([], '更新游戏成功');
        } catch (\Exception $e) {
            return json_error([], '更新游戏失败：' . $e->getMessage());
        }
    }
    
    /**
     * 更新游戏状态
     */
    public function updateStatus()
    {
        // 获取当前用户信息
        $userInfo = $this->getUserInfo();
        
        $ids = Request::post('ids', []);
        $status = Request::post('status', 0, 'intval');
        
        if (empty($ids) || !is_array($ids)) {
            return json_error([], '请选择要更新的游戏');
        }
        
        if (!in_array($status, array_keys(GameModel::STATUS))) {
            return json_error([], '状态值无效');
        }
        
        try {
            $result = GameModel::updateGameStatus($userInfo['merchant_id'], $ids, $status);
            if ($result) {
                return json_success([], '状态更新成功');
            } else {
                return json_error([], '状态更新失败');
            }
        } catch (\Exception $e) {
            return json_error([], '更新游戏状态失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取游戏平台列表
     */
    public function getPlatforms()
    {
        try {
            $platforms = GameModel::getAllPlatforms();
            return json_success($platforms, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取游戏平台失败：' . $e->getMessage());
        }
    }

    /**
     * 获取所有游戏
     */
    public function getGames()
    {
        $userInfo = $this->getUserInfo();

        try {
            $platforms = GameModel::getGames($userInfo['merchant_id']);
            return json_success($platforms, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取游戏平台失败：' . $e->getMessage());
        }
    }
    

    /**
     * 导出游戏列表
     */
    public function export()
    {
        // 获取当前用户信息
        $userInfo = $this->getUserInfo();
        
        // 获取所有过滤条件
        $filters = [
            'title' => Request::get('title', '', 'trim'),
            'game_id' => Request::get('game_id', 0, 'intval'),
            'game_platform' => Request::get('game_platform', ''),
            'status' => Request::get('status', ''),
            'order' => Request::get('order', 'id', 'trim'),
            'sort' => Request::get('sort', 'desc', 'trim'),
        ];
        
        try {
            // 获取所有数据
            $result = GameModel::getGameList($userInfo['merchant_id'], 1, 100000, $filters);
            
            // 生成CSV数据
            $csvData = "ID,游戏ID,游戏平台,中文名称,英文名称,RTP,RTP类型,免费游戏,下注线数,最高倍数,默认押注,最低押注,止损止赢,状态,创建时间\n";
            
            foreach ($result['list'] as $game) {
                $csvData .= sprintf(
                    "%d,%d,%s,%s,%s,%.2f,%s,%s,%d,%d,%.2f,%.2f,%s,%s,%s\n",
                    $game['id'],
                    $game['game_id'],
                    GameModel::getPlatFormText($game['game_platform']),
                    $game['title'],
                    $game['title_en'],
                    $game['rtp'],
                    GameModel::getRtpTypeText($game['rtp_type']),
                    $game['free_game_status'] ? '开启' : '关闭',
                    $game['bet_line_count'],
                    $game['max_multiple_count'],
                    $game['default_deposit'],
                    $game['min_deposit'],
                    $game['terminal_spin'] ? '开启' : '关闭',
                    GameModel::getStatusText($game['status']),
                    $game['create_time'],
                );
            }
            
            // 返回CSV数据
            return response($csvData)
                ->header(['Content-Type' => 'text/csv; charset=utf-8'])
                ->header(['Content-Disposition' => 'attachment; filename="games_' . date('YmdHis') . '.csv"'])
                ->header(['Cache-Control' => 'no-cache, must-revalidate']);
                
        } catch (\Exception $e) {
            return json_error([], '导出游戏列表失败：' . $e->getMessage());
        }
    }
}