<?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 Exception;
use support\Log;
use support\Response;

class NextSpinServiceInterface extends GameServiceFactory implements GameServiceInterface
{
    public $method = 'POST';
    private $apiDomain;
    private $domain;
    private $appId;
    private $appSecret;
    private $path = [
        'ListGames' => 'ListGames',//获取游戏列表
        'createPlayer' => '/UserInfo/CreatePlayer',
        'getPlayer' => '/UserInfo/GetPlayer',
        'getGameList' => '/Game/GetGameList',
        'getSimpleGameList' => '/Game/GetSimpleGameList',
        'getLoginH5' => '/UserInfo/GetLoginH5',
        'setPlayerStatus' => '/UserInfo/SetPlayerStatus',
        'getBalance' => '/Account/GetBalance',
        'setBalanceTransfer' => '/Account/SetBalanceTransfer',
        'getGameRecordByTime' => '/Game/GetGameRecordByTime',
        'getGameRecord' => '/Game/GetGameRecord',
        'removeRecords' => '/Game/RemoveRecords',
    ];

    public $successCode = 'S100';

    public $loginId;

    public $gameType = [
        'AD' => 'Casino',
        'SM' => 'Fishing',
    ];
    
    public $localGameType = [
        'AD' => '2',
        'SM' => '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' => '系統錯誤',
    ];

    private $lang = [
        'zh-CN' => 'zh_ch',
        'en' => 'en_us',
        'zh_tc' => 'zh_tc',
        'th_th' => 'th_th',
        'Ma_my' => 'Ma_my',
        'vi_nam' => 'vi_nam',
        'Fi_fi' => 'Fi_fi',
        'Kr_ko' => 'Kr_ko',
        'Hi_hi' => 'Hi_hi',
        'My_mar' => 'My_mar',
        'Br_po' => 'Br_po',
        'cam_dia' => 'cam_dia', // 柬埔寨语
    ];

    /**
     * @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->domain = $config['domain'];
        $this->appSecret = $config['app_secret'];
        $this->platform = GamePlatform::query()->where('name', $type)->first();
        if (!empty($player)) {
            $this->player = $player;
            $this->getLoginId();
        }
    }

    public function httpRequest($url,$api,$method = 'POST',$fields)
    {
        $fields = json_encode(["merchantCode"=> "ZCH6747",
        	"serialNo"=>"20240722224255982841"]);
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_POSTFIELDS => $fields,
            CURLOPT_HTTPHEADER => [
                "API: $api",
                "Accept: */*",
                "Accept-Encoding: gzip, deflate, br",
                "Connection: keep-alive",
                "Content-Type: application/json",
                "DataType: JSON",
                "User-Agent: PostmanRuntime-ApipostRuntime/1.1.0"
            ],
        ]);
        $response = curl_exec($curl);
        curl_close($curl);
        $data = json_decode($response,true);
        return $data;
    }

    /**
     * 更新游戏列表
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function getSimpleGameList()
    {
        $api = 'getGames';
        $method = 'POST';
        $serialNo = createOrderNo();
        $fields = json_encode([
            "merchantCode" => $this->appId,
        	"serialNo" => $serialNo
        ]);

        $result = $this->httpRequest($this->apiDomain,$api,$method,$fields);
		if (isset($result['games']) && $result['code'] == 0) {
			foreach ($result['games'] as $game) {
                Game::query()->updateOrCreate(
                    [
                        'platform_id' => $this->platform->id,
                        'game_code' => $game['gameCode'],
                    ],
                    [
                        'platform_game_type' => $game['category'],
                        'game_type' => $this->localGameType[$game['category']],
                        'name' => $game['gameName'],
                    ]
                );
            }
		}else{
            throw new GameException($result['msg'], 0);
        }
        return $result;
    }
    
    /**
     * 获取游戏列表
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function getGamesList()
    {
        $api = 'getGames';
        $method = 'POST';
        $serialNo = createOrderNo();
        $fields = json_encode([
            "merchantCode" => $this->appId,
        	"serialNo" => $serialNo
        ]);

        $result = $this->httpRequest($this->apiDomain,$api,$method,$fields);
		if (isset($result['games']) && $result['code'] == 0) {
			return $result['games'];
		}else{
            throw new GameException($result['msg'], 0);
        }
    }
    
    /**
     * 玩游戏
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function playGame()
    {
        $params = [
            'Method' => 'PLAY',
            'Username' => $this->player->name,
            'RequestID' => createOrderNo(),
            'Amount' => $amount,
            'Timestamp' => time(),
        ];
        $signature = $this->createSign($params);

        $result = doCurl($this->createUrl($signature), $params);
		if (isset($result['Token'])) {
            return $forwardUrl = $this->domain."?token=".$result['Token']."&game=1jeqx59c7ztqg&mobile=false";
        }else{
            throw new GameException($result['Message'], 0);
        }
    }

    /**
     * @throws Exception
     */
    protected function getLoginId()
    {
        /** @var PlayerGamePlatform $playerGamePlatform */
        $playerGamePlatform = $this->player->playerGamePlatform->where('platform_id', $this->platform->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 = [])
    {
        $params = [
            'ID' => createOrderNo(),
            'Method' => 'CreatePlayer',
            'SN' => $this->appId,
            'PlayerCode' => $data['uuid'],
        ];
        $params['Signature'] = $this->createSign($params);
        $params['PlayerName'] = $data['uuid'];
        $res = doCurl($this->createUrl('createPlayer'), $params);
        if ($res['code'] != $this->successCode) {
            throw new GameException($this->failCode[$res['code']], 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 $res;
    }

    /**
     * 创建玩家
     * @return array|mixed|Response
     * @throws GameException|Exception
     */
    public function getPlayer()
    {
        $params = [
            'ID' => createOrderNo(),
            'Method' => 'GetPlayer',
            'SN' => $this->appId,
            'LoginId' => $this->loginId,
        ];
        $params['Signature'] = $this->createSign($params);
        $data = doCurl($this->createUrl('getPlayer'), $params);
        if ($data['code'] != $this->successCode) {
            throw new GameException($this->failCode[$data['code']], 0);
        }

        return $data;
    }

    /**
     * 获取游戏摘要MD5 (id+method+sn+APlSecretKey)
     * @param array $data
     * @return string
     * @throws GameException|\think\Exception
     */
    public function login(array $data = []): string
    {
        $params = [
            'ID' => createOrderNo(),
            'Method' => 'GetLoginH5',
            'SN' => $this->appId,
            'LoginId' => $this->loginId,
        ];
        $params['Signature'] = $this->createSign($params);
        $res = doCurl($this->createUrl('getLoginH5'), $params);
        if ($res['code'] != $this->successCode) {
            Log::error($this->failCode[$res['code']], ['res' => $res]);
            throw new GameException($this->failCode[$res['code']], 0);
        }
        $responseH5 = [
            'Language' => $this->lang[$data['lang']] ?? 'ch',
            "GameId" => $data['gameCode'],
            'CallbackAddress' => $data['callBackUrl'] ?? '',
            "AppType" => $data['appType'] ?? 1,
            "DeviceType" => 1,
        ];
        $jsonString = json_encode($responseH5);
        $parametersValue = base64_encode($jsonString);
        $link = $this->domain . '/linkgame' . ($res['data']['loginUrl'] ?? '') . '&' . $parametersValue;
        if (!empty($data['gameCode'])) {
            $link .= '&' . $data['gameCode'];
        }
        return $link;
    }

    /**
     * 設置登入玩家狀態。當玩家處於禁用狀態，該玩家無法在平台進行任何操作，如果玩家在遊戲進行中該玩家將會自動退出遊戲。
     * 簽名密鑰方式    Md5(Id+Method+SN+LoginId+APISecretKey)
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function setPlayerStatus($status)
    {
        $params = [
            'ID' => createOrderNo(),
            'Method' => 'GetSimpleGameList',
            'SN' => $this->appId,
            'LoginId' => $this->loginId,
        ];
        $params['Signature'] = $this->createSign($params);
        $params['Status'] = $status;
        $data = doCurl($this->createUrl('setPlayerStatus'), $params);
        if ($data['code'] != $this->successCode) {
            throw new GameException($this->failCode[$data['code']], 0);
        }

        return $data;
    }

    /**
     * 獲取玩家餘額信息
     * 簽名密鑰方式 MD5 (Id+Method+SN+LoginId+APISecretKey)
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function getBalance()
    {
        $params = [
            'ID' => createOrderNo(),
            'Method' => 'GetBalance',
            'SN' => $this->appId,
            'LoginId' => $this->loginId,
        ];
        $params['Signature'] = $this->createSign($params);
        $data = doCurl($this->createUrl('getBalance'), $params);
        if ($data['code'] != $this->successCode) {
            throw new GameException($this->failCode[$data['code']], 0);
        }

        return $data;
    }

    /**
     * 玩家钱包转入游戏平台
     * @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();
        return $this->setBalanceTransfer(PlayerWalletTransfer::TYPE_IN, !empty($balance['data']['result']) ? -$balance['data']['result'] : 0, !empty($balance['data']['reward']) ? -$balance['data']['reward'] : 0);
    }

    /**
     *  轉帳進出額度
     *  簽名密鑰方式 MD5 (Id+Method+SN+LoginId+APISecretKey)
     * @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 ($amount == 0 && $reward == 0) {
            throw new GameException('转出/入金额错误', 0);
        }
        $params = [
            'ID' => createOrderNo(),
            'Method' => 'SetBalanceTransfer',
            'SN' => $this->appId,
            'LoginId' => $this->loginId,
        ];
        $params['Signature'] = $this->createSign($params);
        $params['Amount'] = $amount;
        $params['Reward'] = $reward;
        $res = doCurl($this->createUrl('setBalanceTransfer'), $params);
        if ($res['code'] != $this->successCode) {
            throw new GameException($this->failCode[$res['code']], 0);
        }
        // 记录玩家钱包转出转入记录
        $this->createWalletTransfer($type, $amount, $reward, $res['data']['refId'] ?? '');

        return $res;
    }

    /**
     * 依據時間獲取遊戲紀錄
     * MD5 (Id+Method+SN+StartTime+EndTime+APISecretKey)
     * @param int $pageIndex
     * @param string $startTime
     * @param string $endTime
     * @return array|mixed|null
     * @throws GameException|\think\Exception
     */
    public function getGameRecordByTime(int $pageIndex = 1, string $startTime = '', string $endTime = '')
    {
        $params = [
            'ID' => createOrderNo(),
            'Method' => 'GetGameRecordByTime',
            'SN' => $this->appId,
            'StartTime' => $startTime,
            'EndTime' => $endTime,
        ];
        $pageSize = 500;
        $params['Signature'] = $this->createSign($params);
        $params['PageSize'] = $pageSize;
        $params['PageIndex'] = $pageIndex;
        $res = doCurl($this->createUrl('getGameRecordByTime'), $params);
        if ($res['code'] != $this->successCode) {
            throw new GameException($this->failCode[$res['code']], 0);
        }

        return $res;
    }

    /**
     * 獲取玩家遊戲歷史紀錄
     * MD5 (Id+Method+SN+APISecretKey)
     * @return array|mixed|null
     * @throws GameException|\think\Exception
     */
    public function getGameRecord()
    {
        $params = [
            'ID' => createOrderNo(),
            'Method' => 'GetGameRecord',
            'SN' => $this->appId,
        ];
        $params['Signature'] = $this->createSign($params);
        $res = doCurl($this->createUrl('getGameRecord'), $params);
        if ($res['code'] != $this->successCode) {
            throw new GameException($this->failCode[$res['code']], 0);
        }

        return $res;
    }

    /**
     * 刪除遊戲紀錄
     * MD5 (Id+Method+SN+IdsToBeRemoved+APISecretKey)
     * @return array|mixed|null
     * @throws GameException|\think\Exception
     */
    public function removeRecords($idsToBeRemoved)
    {
        $params = [
            'ID' => createOrderNo(),
            'Method' => 'RemoveRecords',
            'SN' => $this->appId,
            'IdsToBeRemoved' => implode(',', $idsToBeRemoved),
        ];
        $params['Signature'] = $this->createSign($params);
        $res = doCurl($this->createUrl('removeRecords'), $params);
        if ($res['code'] != $this->successCode) {
            throw new GameException($this->failCode[$res['code']], 0);
        }

        return $res;
    }
}