<?php

namespace app\controller;

use app\BaseController;
use app\common\CommonUtils;
use app\common\CommonMerchantUserAndBalance;
use app\model\GameModel;
use app\model\MerchantsUserModel;
use app\model\PlayerControlModel;
use app\model\UserModel;
use think\facade\Request;

class PlayerControl extends BaseController
{
    /**
     * 添加或更新 点控设置
     * {"account_ids":["115"],"game_ids":[1],"rtp":9900,"max_win_multi":500,"auto_cancel_rtp":100,"agent_id":6027,"win_pro":-1}
     */
    public function updatePlayerControl()
    {
        $userInfo = $this->request->userInfo;
        $data = Request::param([
            'account_ids' => "",
            'game_ids' => "",
            'rtp' => 0,
            'max_win_multi' => 0,
            'auto_cancel_rtp' => 0
        ]);

        // 判断RTP
        if(empty($data['rtp'])) {
            return json_error([], 'RTP错误');
        }

        $account_ids = $data['account_ids'] ?? "";
        $game_ids = $data['game_ids'] ?? "";
        // 游戏平台ID和游戏ID不能为空
        if(empty($account_ids) || empty($game_ids)) {
            return json_error([], '平台ID和游戏ID不能为空');
        }


        $account_ids = explode(",", $account_ids);
        $game_ids = explode(",", $game_ids);

        $unameList = [];
        $emptyUnameList = [];
        foreach ($account_ids as $account_id) {
            $account_id = trim($account_id);
            if(!empty($account_id) && preg_match("/^[1-9]\d*$/", $account_id)) {
                $unameList[] = $account_id;
            }else {
                $emptyUnameList[] = $account_id;
            }
        }
        if(!empty($emptyUnameList)) {
            return json_error([], '不存在玩家：' . implode(",", $emptyUnameList));
        }

        $gameList = [];
        foreach ($game_ids as $game_id) {
            $game_id = trim($game_id);
            if(!empty($game_id)) {
                $gameList[] = $game_id;
            }
        }

        // 过滤掉 游戏平台ID和游戏ID不能为空
        if(empty($unameList) || empty($gameList)) {
            return json_error([], '平台ID和游戏ID不能为空');
        }

        $allGameList = GameModel::getGames($userInfo['merchant_id']);
        $gameIds = array_column($allGameList, 'game_id');
        $emptyIds = [];
        foreach ($gameList as $gameId) {
            if(!in_array($gameId, $gameIds)) {
                $emptyIds[] = $gameId;
            }
        }
        if(!empty($emptyIds)) {
            return json_error([], "不存在游戏：" . implode(", ", $emptyIds));
        }


        $merchantsUserList = MerchantsUserModel::getPlayerListByIds($userInfo['merchant_id'], [
            ['uname', 'in', $unameList]
        ]);

        $merchantsUserList = array_column($merchantsUserList, null, 'uname');

        $merchantsUserIds = array_column($merchantsUserList, 'user_id');
        $userBalanceList = CommonMerchantUserAndBalance::getMerchantUserBalance($merchantsUserIds);
        $userBalanceList = array_column($userBalanceList, null, 'user_id');

        foreach ($account_ids as $accountId) {
            $merchantsUserInfo = $merchantsUserList[$accountId] ?? [];
            if(empty($merchantsUserInfo)) {
                continue;
            }

            $user_id = $merchantsUserInfo['user_id'];
            $rtpGameLIst = CommonMerchantUserAndBalance::getMerchantUserGameRtpWinBetInfo([
                ['user_id', '=' , $user_id],
                ['game_id', 'in', $gameIds],
            ], ['rtp','game_id']);

            $gameRtp = [];
            foreach ($rtpGameLIst as $item) {
                $gameRtp[$item['game_id']] = $item['rtp'];
            }


            foreach ($game_ids as $gameId) {
                $old_rtp = $gameRtp[$gameId] ?? 0;

                $info = PlayerControlModel::getPlayerControlInfo([
                    'app_id' => $userInfo['merchant_id'],
                    'player_id' => $user_id,
                    'game_id' => $gameId,
                    'status' => 1
                ]);

                // if(!empty($info) && $info->status == 0) {
                //     $info = null;
                // }

                $balanceInfo = $userBalanceList[$user_id] ?? [];
                if(!empty($info)) {
                    // 需要更新
                    $info->control_rpt = bcmul( $data['rtp'], 100);
                    $info->auto_cancel_rtp = bcmul($data['auto_cancel_rtp'], 100);
                    $info->max_win_multi = $data['max_win_multi'];
                    $info->old_rtp = $old_rtp;
                    $info->save();
                }else {
                    $item =  [
                        'app_id' => $userInfo['merchant_id'],
                        'user_id' => $userInfo['user_id'],
                        'player_id' => $merchantsUserInfo['user_id'],// 玩家id
                        'game_id' => $gameId,
                        'old_rtp' => $old_rtp,
                        'control_rpt' => bcmul( $data['rtp'], 100),
                        'auto_cancel_rtp' => bcmul($data['auto_cancel_rtp'], 100), // 达到RTP值取消
                        'max_win_multi' => $data['max_win_multi'], // 最高倍数
                        'control_balance' => CommonUtils::convertBalance( $balanceInfo['balance'], false), // 设置时点控那刻当前余额
                    ];
                    PlayerControlModel::create($item);
                }
            }
        }
        return json_success([],'操作成功');
    }

    /**
     * 获取点控列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPlayerControlList()
    {
        // 获取当前用户信息
        $userInfo = $this->getUserInfo();

        // 获取查询参数
        $page = Request::get('page', 1, 'intval');
        $limit = Request::get('limit', 10, 'intval');

        // 过滤条件
        // 筛选条件
        $filters = [
            // 时间筛选
            'start_time' => Request::get('start_time', '', 'trim'),
            'end_time' => Request::get('end_time', '', 'trim'),
            // 游戏筛选
            'game_id' => Request::get('game_id', '', 'trim'),
            // 平台ID筛选
            'uname' => Request::get('uname', '', 'trim'),
            // 玩家ID筛选
            'player_id' => Request::get('user_id', '', 'trim'),
            // 平台昵称
            'nickname' => Request::get('nickname', '', 'trim'),
        ];

        $is_end = Request::get('is_end_time', 0);


        $controlWhere = [];
        $controlWhere[] = ['user_id', '=', $userInfo['user_id']];


        $where = [];
        $isFindUserId = false;
        // 平台ID筛选
        if (!empty($filters['uname'])) {
            $where[] = ['uname', '=', $filters['uname']];
            $isFindUserId = true;
        }
        // 平台昵称筛选
        if (!empty($filters['nickname'])) {
            $where[] = ['nickname', 'like', '%' . $filters['nickname'] . '%'];
            $isFindUserId = true;
        }
        // 玩家id筛选
        if (!empty($filters['player_id'])) {
            $where[] = ['user_id', 'like', '%' . $filters['player_id'] . '%'];
            $isFindUserId = true;
        }
        if($isFindUserId) {
            $merchantsUserIds = MerchantsUserModel::getPlayerListByIds($userInfo['merchant_id'], $where, ['user_id']);
            $controlWhere[] = ['user_id', 'in', array_column($merchantsUserIds, 'user_id')];
        }

        if(!empty($filters['game_id'])) {
            $controlWhere[] = ['game_id', 'in', explode(",", $filters['game_id'])];
        }

        if(!empty($filters['start_time']) && !empty($filters['end_time'])) {

            $controlWhere[] = [$is_end ? 'end_time' : 'update_time', '>=', strtotime($filters['start_time'] . " 00:00:00")];
            $controlWhere[] = [$is_end ? 'end_time' :'update_time', '<=', strtotime($filters['end_time'] . " 23:59:59")];
        }

        $controlWhere[] = ['status', '=',  $is_end ? 0 : 1];

        $results = PlayerControlModel::getPlayerControlList($userInfo['merchant_id'], $page, $limit, $controlWhere);

        $allGameList = GameModel::getGames($userInfo['merchant_id'], [], ['id', 'game_id', 'title', 'game_platform']);
        $gameConfig = array_column($allGameList, null, 'game_id');

        $player_ids = array_column($results['list'],  'player_id');

        $playerConfig = CommonMerchantUserAndBalance::getMerchantUser($player_ids, ['user_id','uname','nickname']);
        $playerConfig = array_column($playerConfig, null, 'user_id');


        $userListBalance = CommonMerchantUserAndBalance::getMerchantUserBalance($player_ids);
        $userBalanceConfig = [];
        foreach ($userListBalance as $item) {
            $userBalanceConfig[$item['user_id']] = $item['balance'];
        }

        $rtpUserList = [];
        foreach ($results['list'] as $item) {
            $player_id = $item['player_id'];
            if(empty($rtpUserList[$player_id])) {
                $rtpUserList[$player_id] = [];
            }
            $rtpUserList[$player_id][] = $item['game_id'];
        }
        $rtpConfigList = [];
        foreach ($rtpUserList as $player_id => $gameIds) {
            $temp = CommonMerchantUserAndBalance::getMerchantUserGameRtpWinBetInfo([
                ['user_id', '=' , $player_id],
                ['game_id', 'in', $gameIds],
            ], ['rtp','game_id']);
            foreach ($temp as $item) {
                $game_id = $item['game_id'];
                $rtp = $item['rtp'];
                $key = "{$player_id}_{$game_id}";
                $rtpConfigList[$key] = $rtp;
            }
        }


        foreach ($results['list'] as $key => $item) {
            $game_id = $item['game_id'];
            $player_id = $item['player_id'];
            $one_key = "{$player_id}_{$game_id}";
            $gameInfo = $gameConfig[$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($gameInfo['game_platform']);
            $item['balance'] = CommonUtils::convertBalance($userBalanceConfig[$player_id] ?? 0, false);
            $item['bet_amount'] = CommonUtils::convertBalance($item['bet_amount'] ?? 0, false);
            $item['total_win_amount'] = CommonUtils::convertBalance($item['total_win_amount'] ?? 0, false);
            $item['control_rpt'] = bcdiv($item['control_rpt'], 100, 2) . "%";
            $item['old_rtp'] = bcdiv($item['old_rtp'], 100, 2) . "%";
            $item['now_rtp'] = bcdiv($rtpConfigList[$one_key] ?? 0, 100, 2) . "%";

            if(!empty($item['auto_cancel_rtp'])) {
                $item['auto_cancel_rtp'] = bcdiv($item['auto_cancel_rtp'], 100, 2) . "%";
            }

            $playerInfo = $playerConfig[$player_id] ?? [];
            $item['uname'] = $playerInfo['uname'] ?? '';
            $item['nickname'] = $playerInfo['nickname'] ?? '';
            $adminInfo = UserModel::find($item['user_id']);
            $item['admin_name'] = "";
            if(!empty($adminInfo)) {
                $item['admin_name'] = $adminInfo['nick_name'] ?? '';
            }

            if(!empty($item['end_time'])) {
                $item['end_time'] = date('Y-m-d H:i:s', $item['end_time']);
            }

            $results['list'][$key] = $item;
        }

        return json_success($results);

    }


    /**
     * 取消点控设置
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancelPlayerControlInfo()
    {
        $userInfo = $this->getUserInfo();
        $control_id = Request::post('control_id','', 'trim');
        if(empty($control_id)) {
            return json_error([], '参数错误');
        }
        $info = PlayerControlModel::where(['control_id' => $control_id, 'user_id' => $userInfo['user_id']])->find();
        if(!empty($info)) {
            $info->end_time = time();
            $info->status = 0;
            $info->save();
        }
        return json_success([],'操作成功');
    }

    /**
     * 一键取消全部点控
     * @return \think\response\Json
     */
    public function cancelAllPlayerControlInfo()
    {
        $userInfo = $this->getUserInfo();
        PlayerControlModel::where(['user_id' => $userInfo['user_id'], 'status' => 1])->save(['status' => 0, 'end_time' => time()]);
        return json_success([],'操作成功');
    }

}