<?php

namespace app\service\game;

use addons\webman\model\Game;
use addons\webman\model\GamePlatform;
use addons\webman\model\Player;
use addons\webman\model\PlayerGamePlatform;
use addons\webman\model\PlayerWalletTransfer;
use app\exception\GameException;
use DateTime;
use DateTimeZone;
use Exception;
use Illuminate\Support\Str;
use support\Log;
use support\Response;

class MarioClubServiceInterface extends GameServiceFactory implements GameServiceInterface
{
    public $method = 'POST';
    private $apiDomain;
    private $appId;
    private $appSecret;
    public $loginId;

    public $gameType = [
        '2' => 'Casino',
        '5' => 'Fishing',
        '8' => 'Bingo',
        '1' => 'Slot',
    ];

    public $localGameType = [
        'FISHING' => '4',//捕鱼
        'SLOT' => '1',//斯洛
        '1' => '1',
        '4' => '4',
    ];

    public $failCode = [
        'S200' => '重復請求',
        'F0001' => '無效的簽名',
        'F0002' => '無效的SN',
        'F0003' => '無效的參數',
        'F0004' => '無效的貨幣',
        'F0005' => '玩家已存在',
        'F0006' => '玩家不存在',
        'F0007' => '會員不存在',
        'F0008' => '執行失敗',
        'F0009' => '無效的方法',
        'F0010' => '無效的用戶狀態',
        'F0011' => '玩家狀態無需更新',
        'F0012' => '超出數據範圍',
        'F0013' => '無匹配數據',
        'F0014' => '登入位置被禁止',
        'F0015' => '分數不足夠',
        'F0016' => '不支持禮碼',
        'F0017' => '交易流水號不得重複',
        'F0018' => '系統繁忙',
        'F0019' => '日期時間各式錯誤',
        'F0020' => '超出時間限制範圍（開始時間與結束時間之間不能大於120分鐘）',
        'F0021' => '執行取消',
        'M0001' => '系統維護',
        'M0002' => '系統錯誤',
    ];

    /**
     * @param Player|null $player
     * @param $type
     * @throws Exception
     */
    public function __construct($type, Player $player = null)
    {
        $config = config('game_platform.' . $type);
        $this->appId = $config['app_id'];
        $this->apiDomain = $config['api_domain'];
        $this->appSecret = $config['app_secret'];
        $this->platform = GamePlatform::query()->where('name', $type)->first();
        if (!empty($player)) {
            $this->player = $player;
            $this->getLoginId();
        }
    }

    /**
     * 生成签名
     * @param $time
     * @return string
     */
    public function createSign($time): string
    {
        return md5($this->appId.$time.$this->appSecret);
    }

    /**
     * 更新游戏列表
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function getSimpleGameList()
    {
        $time = time();
        $params = [
            'api_id' => $this->appId,
            'timestamp' => $time,
        ];
        $params['sign'] = $this->createSign($time);
        $result = doFormCurl($this->apiDomain.'/getGames',$params);
        if ($result['code'] == 0 && !empty($result['gameList'])) {
            foreach ($result['gameList'] as $game) {
                Game::query()->updateOrCreate(
                    [
                        'platform_id' => $this->platform->id,
                        'game_code' => $game['gameCode'],
                    ],
                    [
                        'platform_game_type' => $game['gameType'],
                        'game_type' => $this->localGameType[$game['gameType']] ?? '',
                        'name' => $game['gameName'],
                        'game_image' => $game['gameIconUrl']
                    ]
                );
            }
        }else{
            throw new GameException($result['Message'], 0);
        }
        return $result;
    }

    /**
     * 获取游戏列表
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function getGamesList()
    {
        $time = time();
        $params = [
            'api_id' => $this->appId,
            'timestamp' => $time,
        ];
        $params['sign'] = $this->createSign($time);
        $result = doFormCurl($this->apiDomain.'/getGames',$params);
        if ($result['code'] == 0 && !empty($result['gameList'])) {
            return $result;
        }else{
            throw new GameException($result['Message'], 0);
        }
    }

    /**
     * 获取玩家ID
     * @throws Exception
     */
    protected function getLoginId()
    {
        /** @var PlayerGamePlatform $playerGamePlatform */
        $playerGamePlatform = PlayerGamePlatform::query()->where('platform_id', $this->platform->id)->where('player_id',$this->player->id)->first();
        if (!empty($playerGamePlatform)) {
            return $this->loginId = $playerGamePlatform->player_code;
        }
        return $this->createPlayer([
            'uuid' => $this->player->uuid,
            'name' => $this->player->name,
        ]);
    }

    /**
     * 创建玩家
     * @param array $data
     * @return array|mixed|Response
     * @throws GameException|Exception
     */
    public function createPlayer(array $data = [])
    {
        $time = time();
        $params = [
            'api_id' => $this->appId,
            'timestamp' => $time,
            'user_id' => $data['uuid'],
        ];
        $params['sign'] = $this->createSign($time);
        $result = doFormCurl($this->apiDomain.'/api/acc/created',$params);

        if ($result['code'] != 0) {
            Log::error($result['msg'], ['res' => $result]);
            throw new GameException($result['msg'], 0);
        }
        $playerGamePlatform = new PlayerGamePlatform();
        $playerGamePlatform->player_id = $this->player->id;
        $playerGamePlatform->platform_id = $this->platform->id;
        $playerGamePlatform->player_name = $data['name'];
        $playerGamePlatform->player_code = $data['uuid'];
        $playerGamePlatform->save();
        $this->loginId = $playerGamePlatform->player_code;
        return $result;
    }

    /**
     * 获取玩家
     * @return array|mixed|Response
     * @throws GameException|Exception
     */
    public function getPlayer()
    {
        $time = time();
        $params = [
            'api_id' => $this->appId,
            'timestamp' => $time,
            'user_id' => $this->loginId,
            'language' => 'en',
        ];
        $params['sign'] = $this->createSign($time);
        $result = doFormCurl($this->apiDomain.'/api/acc/gameLogIn',$params);
        if ($result['code'] != 0) {
            throw new GameException($result['msg'], 0);
        }
        return $result;
    }

    /**
     * 玩家进入游戏
     * @param array $data
     * @return string
     * @throws GameException|\think\Exception
     */
    public function login(array $data = []): string
    {
        $time = time();
        $params = [
            'api_id' => $this->appId,
            'timestamp' => $time,
            'user_id' => $this->loginId,
            'game_code' => $data['gameCode'],
            'language' => 'en',
        ];
        $params['sign'] = $this->createSign($time);
        $result = doFormCurl($this->apiDomain.'/api/acc/gameLogIn',$params);
        if ($result['code'] == 0 && !empty($result['gameUrl'])) {
            $link = $result['gameUrl'];
        }else{
            throw new GameException($result['msg'], 0);
        }
        return $link;
    }

    /**
     * 获取玩家游戏平台余额
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function getBalance()
    {
        $time = time();
        $params = [
            'api_id' => $this->appId,
            'timestamp' => $time,
            'user_id' => $this->loginId,
        ];
        $params['sign'] = $this->createSign($time);
        $result = doFormCurl($this->apiDomain.'/api/acc/getBalance',$params);
        if ($result['code'] != 0) {
            throw new GameException('MarioClub System Error,Please contact the administrator', 0);
        }
        return $result['balance'];
    }

    /**
     * 玩家钱包转入游戏平台
     * @return array|mixed|null
     * @throws GameException|\think\Exception
     */
    public function balanceTransferOut()
    {
        return $this->setBalanceTransfer(PlayerWalletTransfer::TYPE_OUT, $this->player->wallet->money);
    }

    /**
     * 游戏平台转入玩家钱包
     * @return array|mixed|null
     * @throws GameException|\think\Exception
     */
    public function balanceTransferIn()
    {
        $balance = $this->getBalance();
        if($balance == 0){
            // 记录玩家钱包转出转入记录
            $this->createWalletTransfer(PlayerWalletTransfer::TYPE_IN, 0, 0);
            return true;
        }
        return $this->setBalanceTransfer(PlayerWalletTransfer::TYPE_IN, $balance);
    }

    /**
     *  轉帳進出額度
     * @param $type
     * @param float $amount
     * @param float $reward
     * @return array|mixed|null
     * @throws GameException|\think\Exception
     */
    protected function setBalanceTransfer($type, float $amount = 0, float $reward = 0)
    {
        if ($type == 1) {
            $action = 'deposit';
        } else {
            $action = 'withdraw';
        }
        $time = time();
        $params = [
            'api_id' => $this->appId,
            'timestamp' => $time,
            'user_id' => $this->loginId,
            'amount' => $amount,
            'action' => $action,
        ];
        $params['sign'] = $this->createSign($time);
        $result = doFormCurl($this->apiDomain.'/api/acc/updateBalance',$params);
        if ($result['code'] != 0) {
            throw new GameException($result['msg'], 0);
        }
        // 记录玩家钱包转出转入记录
        $this->createWalletTransfer($type, $amount, $reward, $result['transId'] ?? '');
        return $result;
    }

    /**
     * 查询额度转移纪录
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function getTransferList(string $startTime = '', string $endTime = '', int $page = 1, int $pageSize = 10)
    {
        $time = time();
        $params = [
            'api_id' => $this->appId,
            'timestamp' => $time,
            'user_id' => $this->loginId,
            'date_from' => date('d/m/Y', strtotime($startTime)),
            'date_to' => date('d/m/Y', strtotime($endTime)),
        ];
        $params['sign'] = $this->createSign($time);
        $result = doFormCurl($this->apiDomain.'/api/acc/getTransactionLog',$params);
        if ($result['code'] != 0) {
            throw new GameException($result['msg'], 0);
        }
        return $result['walletLogDTO'];
    }

    /**
     * 查询游戏纪录
     * @param string $startTime
     * @param string $endTime
     * @return array
     * @throws GameException
     * @throws \think\Exception
     */
    public function getGameRecordList(string $startTime = '', string $endTime = ''): array
    {
        $time = time();
        $params = [
            'api_id' => $this->appId,
            'timestamp' => $time,
            'date_from' => $startTime,
            'date_to' => $endTime,
        ];
        $params['sign'] = $this->createSign($time);
        $result = doFormCurl($this->apiDomain.'/api/acc/getGameLog',$params);
        if ($result['code'] != 0) {
            throw new GameException($result['msg'], 0);
        }
        return $result['userGameLogDTO'];
    }

    /**
     * 查询玩家游戏记录
     * @return array
     */
    public function handleOrderHistories(): array
    {
        try {
            $list = [];
            $startTime = date('d/m/Y H:i:s', strtotime('-3 minutes'));
            $endTime = date('d/m/Y H:i:s', strtotime('-2 minutes'));
            $data = $this->getGameRecordList($startTime, $endTime);
            if (!empty($data)) {
                foreach ($data as $item) {
                    $list[] = [
                        'uuid' => $item['loginId'],
                        'platform_id' => $this->platform->id,
                        'game_code' => $item['gameCode'],
                        'bet' => $item['betAmount'],
                        'win' => bcadd($item['betAmount'], $item['winAmount'], 2),
                        'order_no' => $item['logId'],
                        'original_data' => json_encode($item,JSON_UNESCAPED_UNICODE),
                        'platform_action_at' => date('Y-m-d H:i:s', $item['createdDate']/1000),
                        'game_type' => $item['gameTypeId'],
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];

                }
            }
        } catch (Exception $e) {
            return [];
        }

        return $list;
    }

}