<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\model\MerchantsUserModel;
use think\facade\Request;

class Player extends BaseController
{
    /**
     * 获取玩家列表
     */
    public function list()
    {
        $userInfo = $this->request->userInfo;
        
        // 获取查询参数
        $page = Request::get('page', 1, 'intval');
        $limit = Request::get('limit', 10, 'intval');
        
        // 过滤条件
        $filters = [
            'uname' => Request::get('uname', '', 'trim'),
            'nickname' => Request::get('nickname', '', 'trim'),
            'player_id' => Request::get('user_id', 0, 'intval'),
            'status' => Request::get('status', ''),
            'adjust_status' => Request::get('adjust_status', ''),
            'login_ip' => Request::get('login_ip', '', 'trim'),
            'reg_ip' => Request::get('reg_ip', '', 'trim'),
            'login_time_start' => Request::get('login_time_start', '', 'trim'),
            'login_time_end' => Request::get('login_time_end', '', 'trim'),
            'order' => Request::get('order', 'user_id', 'trim'),
            'sort' => Request::get('sort', 'desc', 'trim'),
        ];
        
        try {
            // 获取玩家列表
            $result = MerchantsUserModel::getPlayerListByMerchant($userInfo['merchant_id'], $page, $limit, $filters);
            
            // 处理列表数据
            foreach ($result['list'] as &$player) {
                $player['status_text'] = MerchantsUserModel::getStatusText($player['status']);
                $player['adjust_status_text'] = MerchantsUserModel::getAdjustStatusText($player['adjust_status']);
                $player['login_time'] = $player['login_time'] ? date('Y-m-d H:i:s', (int)$player['login_time']) : '未登录';
            }
            
            return json_success($result, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取玩家列表失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取玩家详情
     */
    public function detail()
    {
        $userInfo = $this->request->userInfo;
        
        $playerId = Request::get('user_id', 0, 'intval');
        if (!$playerId) {
            return json_error([], '玩家ID不能为空');
        }
        
        try {
            $player = MerchantsUserModel::getPlayerDetail($playerId, $userInfo['merchant_id']);
            if (!$player) {
                return json_error([], '玩家不存在');
            }
            
            // 添加状态文本
            $player['status_text'] = MerchantsUserModel::getStatusText($player['status']);
            $player['adjust_status_text'] = MerchantsUserModel::getAdjustStatusText($player['adjust_status']);
            $player['login_time_text'] = $player['login_time'] ? date('Y-m-d H:i:s', (int)$player['login_time']) : '未登录';
            
            return json_success($player, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取玩家详情失败：' . $e->getMessage());
        }
    }
    
    /**
     * 更新玩家状态
     */
    public function updateStatus()
    {
        $userInfo = $this->request->userInfo;

        print_r($userInfo);
        
        $playerIds = Request::post('user_ids', []);
        $status = Request::post('status', 0, 'intval');
        
        if (empty($playerIds) || !is_array($playerIds)) {
            return json_error([], '请选择要更新的玩家');
        }
        
        if (!in_array($status, [MerchantsUserModel::STATUS_NORMAL, MerchantsUserModel::STATUS_FROZEN])) {
            return json_error([], '状态值无效');
        }
        
        try {
            $result = MerchantsUserModel::updatePlayerStatus($playerIds, $userInfo['merchant_id'], $status);
            if ($result) {
                return json_success([], '状态更新成功');
            } else {
                return json_error([], '状态更新失败');
            }
        } catch (\Exception $e) {
            return json_error([], '更新玩家状态失败：' . $e->getMessage());
        }
    }
    
    /**
     * 更新玩家调控状态
     */
    public function updateAdjustStatus()
    {
        $userInfo = $this->request->userInfo;
        
        $playerIds = Request::post('user_ids', []);
        $adjustStatus = Request::post('adjust_status', 0, 'intval');
        
        if (empty($playerIds) || !is_array($playerIds)) {
            return json_error([], '请选择要更新的玩家');
        }
        
        if (!in_array($adjustStatus, [
            MerchantsUserModel::ADJUST_STATUS_NORMAL,
            MerchantsUserModel::ADJUST_STATUS_WIN,
            MerchantsUserModel::ADJUST_STATUS_LOSE
        ])) {
            return json_error([], '调控状态值无效');
        }
        
        try {
            $result = MerchantsUserModel::updatePlayerAdjustStatus($playerIds, $userInfo['merchant_id'], $adjustStatus);
            if ($result) {
                return json_success([], '调控状态更新成功');
            } else {
                return json_error([], '调控状态更新失败');
            }
        } catch (\Exception $e) {
            return json_error([], '更新玩家调控状态失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取玩家统计信息
     */
    public function statistics()
    {
        $userInfo = $this->request->userInfo;
        
        try {
            $statistics = MerchantsUserModel::getPlayerStatistics($userInfo['merchant_id']);
            return json_success($statistics, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取玩家统计失败：' . $e->getMessage());
        }
    }
        
    /**
     * 导出玩家列表
     */
    public function export()
    {
        $userInfo = $this->request->userInfo;
        
        // 获取所有过滤条件
        $filters = [
            'nickname' => Request::get('nickname', '', 'trim'),
            'player_id' => Request::get('user_id', 0, 'intval'),
            'status' => Request::get('status', ''),
            'adjust_status' => Request::get('adjust_status', ''),
            'login_ip' => Request::get('login_ip', '', 'trim'),
            'reg_ip' => Request::get('reg_ip', '', 'trim'),
            'login_time_start' => Request::get('login_time_start', '', 'trim'),
            'login_time_end' => Request::get('login_time_end', '', 'trim'),
            'order' => Request::get('order', 'player_id', 'trim'),
            'sort' => Request::get('sort', 'desc', 'trim'),
        ];
        
        try {
            // 获取所有数据
            $result = MerchantsUserModel::getPlayerListByMerchant($userInfo['merchant_id'], 1, 100000, $filters);
            
            // 生成CSV数据
            $csvData = "玩家ID,昵称,注册IP,登录IP,余额,今日输赢,历史输赢,今日下注,今日登录次数,历史登录次数,状态,调控状态,最后登录时间,注册时间\n";
            
            foreach ($result['list'] as $player) {
                $csvData .= sprintf(
                    "%d,%s,%s,%s,%.4f,%.4f,%.4f,%.4f,%d,%d,%s,%s,%s,%s\n",
                    $player['user_id'],
                    $player['nickname'],
                    $player['reg_ip'],
                    $player['login_ip'],
                    $player['balance'],
                    $player['today_win_amount'],
                    $player['history_win_amount'],
                    $player['today_bet_amount'],
                    $player['today_login_count'],
                    $player['history_login_count'],
                    MerchantsUserModel::getStatusText($player['status']),
                    MerchantsUserModel::getAdjustStatusText($player['adjust_status']),
                    $player['login_time'] ? date('Y-m-d H:i:s', (int)$player['login_time']) : '未登录',
                    $player['create_time']
                );
            }
            
            // 返回CSV数据
            return response($csvData)
                ->header(['Content-Type' => 'text/csv; charset=utf-8'])
                ->header(['Content-Disposition' => 'attachment; filename="players_' . date('YmdHis') . '.csv"'])
                ->header(['Cache-Control' => 'no-cache, must-revalidate']);
                
        } catch (\Exception $e) {
            return json_error([], '导出玩家列表失败：' . $e->getMessage());
        }
    }
}