<?php

namespace app\controller;

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

class GameImproveUserRtp extends BaseController
{
    /**
     * 添加或更新 {"uname":"115","net_income":100,"turnover_multiple":5,"evaluation_period":4,"effective_count":6,"trigger_interval_rounds":300}
     * evaluation_period 1 = 每日 2 = 每周 3 = 每月 4 = 终生 5 = 自定义时间
     * custom_time_end custom_time_start
     */
    public function updateGameImproveUserRtp(){
        $userInfo = $this->getUserInfo();
        $data = Request::param([
            'uname' => "",
            'net_income' => 100, // 设定玩家在游戏内盈利值达到后关闭功能
            'turnover_multiple' => 5, //达到设定流水倍数关闭提升状态
            'evaluation_period' => 4, // 系统控制的触发周期选择
            'effective_count' => 1, //周期内可被系统控制的次数
            'trigger_interval_rounds' => 300, // 每次系统控制间隔局数
            // 'custom_time_start' => '',
            // 'custom_time_end' => '',
        ], 'post', 'trim');
        foreach ($data as $k => $v) {
            if(empty($v)) {
                return json_error([], '参数错误');
            }
        }

        $custom_time_start = Request::post('custom_time_start', '', 'trim');
        $custom_time_end = Request::post('custom_time_end', '', 'trim');
        if($data['evaluation_period'] == 5) {
            if(empty($custom_time_start) || empty($custom_time_end)) {
                return json_error([], '参数错误');
            }
        }

        $account_ids = explode(",", $data['uname']);
        $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));
        }
        // 过滤掉 游戏平台ID和游戏ID不能为空
        if(empty($unameList)) {
            return json_error([], '平台ID不能为空');
        }

        $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'];
            $info = GameImproveUserRtpModel::getImproveUserRtpInfo([
                'app_id' => $userInfo['merchant_id'],
                'player_id' => $user_id,
                'status' => 1
            ]);

            $balanceInfo = $userBalanceList[$user_id] ?? [];
            if(!empty($info)) {
                // 更新
                $info->effective_count = $data['effective_count'];
                $info->evaluation_period = $data['evaluation_period'];
                $info->net_income = $data['net_income'];
                $info->trigger_interval_rounds = $data['trigger_interval_rounds'];
                $info->turnover_multiple = $data['turnover_multiple'];
                $info->custom_time_start = !empty($custom_time_start) ?  strtotime($custom_time_start) : 0;
                $info->custom_time_end = !empty($custom_time_end) ?  strtotime($custom_time_end) : 0;
                $info->round_count = 0;


                if($info->evaluation_period != 5) {
                    $info->round_status = 1;
                    $info->open_status_time = time();
                }else {
                    if(time() >= $info->custom_time_start) {
                        $info->round_status = 1;
                    }
                    if(time() >= $info->custom_time_end) {
                        $info->round_status = 2;
                    }
                    $info->open_status_time = $info->custom_time_start;
                }
                $info->save();
            }else {
                // 添加
                $item =  [
                    'app_id' => $userInfo['merchant_id'],
                    'user_id' => $userInfo['user_id'],
                    'player_id' => $merchantsUserInfo['user_id'],// 玩家id
                    'effective_count' => $data['effective_count'],
                    'evaluation_period' => $data['evaluation_period'],
                    'net_income' => $data['net_income'],
                    'trigger_interval_rounds' => $data['trigger_interval_rounds'],
                    'turnover_multiple' => $data['turnover_multiple'],
                    'custom_time_start' => !empty($custom_time_start) ?  strtotime($custom_time_start) : 0,
                    'custom_time_end' => !empty($custom_time_end) ?  strtotime($custom_time_end) : 0,
                    'old_rtp' => $merchantsUserInfo['rtp'],
                    'control_balance' => CommonUtils::convertBalance( $balanceInfo['balance'], false), // 设置时点控那刻当前余额
                ];
                if($item['evaluation_period'] != 5) {
                    $item['round_status'] = 1;
                    $item['open_status_time'] = time();
                }else {
                    if(time() >= $item['custom_time_start']) {
                        $item['round_status'] = 1;
                    }
                    if(time() >= $item['custom_time_end']) {
                        $item['round_status'] = 2;
                    }
                    $item['open_status_time'] = $item['custom_time_start'];
                }

                GameImproveUserRtpModel::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 getGameImproveUserList()
    {
        // 获取当前用户信息
        $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'),
            // 平台ID筛选
            'uname' => Request::get('uname', '', 'trim'),
            // 玩家ID筛选
            'player_id' => Request::get('user_id', '', 'trim'),
            // 平台昵称
            'nickname' => Request::get('nickname', '', 'trim'),
            'status' => Request::get('status', '', '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['start_time']) && !empty($filters['end_time'])) {
            $controlWhere[] = ['update_time', '>=', strtotime($filters['start_time'] . " 00:00:00")];
            $controlWhere[] = ['update_time', '<=', strtotime($filters['end_time'] . " 23:59:59")];
        }

        if(in_array($filters['status'], ['0','1'])) {
            $controlWhere[] = ['status', '=', $filters['status']];
        }else {
            if(!$is_end) {
                $controlWhere[] = ['status', '=', 1];
            }
        }

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

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

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


        foreach ($results['list'] as $key => $item) {
            $player_id = $item['player_id'];

            $playerInfo = $playerConfig[$player_id] ?? [];
            $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['old_rtp'] = bcdiv($item['old_rtp'], 100, 2) . "%";
            $item['now_rtp'] = bcdiv($playerInfo['rtp'] ?? 0, 100, 2) . "%";

            $item['status_text'] = $item['status'] == 1 ? '生效中' : "已结束";
            $item['evaluation_period_text'] = [
                '1' => '每日',
                '2' => '每周',
                '3' => '每月',
                '4' => '终生',
                '5' => '自定义时间'
            ][$item['evaluation_period']] ?? "";

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

            $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']);
            }

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

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

        }

        return json_success($results);
    }

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

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