<?php

namespace app\service\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\Response;

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

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

    public $localGameType = [
        '2' => '2',//赌场
        '5' => '4',//捕鱼
        '8' => '8',//宾果
        '1' => '1',//斯洛
    ];

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

    /**
     * 生成请求url
     * @return string
     */
    public function createUrl(): string
    {
        return $this->apiDomain;
    }

    //生成签名
    public function createSign($params): string
    {
        $str = '';
        foreach ($params as $v) {
            $str .= $v;
        }
        return md5($str);
    }

    /**
     * 生成请求数据
     * @param $postData
     * @param $method
     * @return array
     */
    function buildParams($postData, $method): array
    {
        return array(
            "jsonrpc" => "2.0",
            "method" => $method,
            "params" => $postData,
            "id" => $this->player->uuid ?? uniqid()
        );
    }

    /**
     * 获取下载地址
     * @throws GameException|\think\Exception
     */
    public function getDownload()
    {
        $params = [
            'random' => $this->player->uuid ?? uniqid(),
            'sn' => $this->sn,
            'secretCode' => $this->appSecret,
        ];
        $params['digest'] = $this->createSign($params);
        $params['agentLoginId'] = $this->appId;
        $postData = $this->buildParams($params, 'open.mega.app.url.download');
        $result = doCurl($this->apiDomain,$postData);
        if(!empty($result['result'])){
            return $result['result'];
        }else{
            throw new GameException($result['error']['message'], 0);
        }
    }

    /**
     * 更新游戏列表
     * @return false
     */
    public function getSimpleGameList(): bool
    {
        return false;
    }

    /**
     * 获取玩家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)) {
            $this->password = $playerGamePlatform->player_password;
            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 = [
            'random' => $data['uuid'] ?? uniqid(),
            'sn' => $this->sn,
            'secretCode' => $this->appSecret,
        ];
        $params['digest'] = $this->createSign($params);
        $params['agentLoginId'] = $this->appId;
        $params['nickname'] = $data['name'];
        $postData = $this->buildParams($params, 'open.mega.user.create');
        $result = doCurl($this->apiDomain,$postData);
        if (!empty($result['result']) && empty($result['error'])) {
            $playerGamePlatform = new PlayerGamePlatform();
            $playerGamePlatform->player_id = $this->player->id;
            $playerGamePlatform->platform_id = $this->platform->id;
            $playerGamePlatform->player_name = $data['name'];
            $playerGamePlatform->player_code = $result['result']['loginId'];
            $playerGamePlatform->player_password = uniqid();
            $playerGamePlatform->save();
            $this->loginId = $playerGamePlatform->player_code;
            $this->password = $playerGamePlatform->player_password;
            return $result;
        }else{
            throw new GameException($result['error']['message'], 0);
        }
    }

    /**
     * 获取玩家信息
     * @return array|mixed|Response
     * @throws GameException|Exception
     */
    public function getPlayer()
    {
        $params = [
            'random' => $this->player->uuid ?? uniqid(),
            'sn' => $this->sn,
            'loginId' => $this->loginId,
            'secretCode' => $this->appSecret,
        ];
        $params['digest'] = $this->createSign($params);
        $postData = $this->buildParams($params, 'open.mega.user.get');
        $result = doCurl($this->apiDomain,$postData);
        if (!empty($result['result']) && empty($result['error'])) {
            return $result;
        }else{
            throw new GameException($result['error']['message'], 0);
        }
    }

    /**
     * 玩家进入游戏
     * @param array $data
     * @return array
     * @throws GameException
     * @throws \think\Exception
     */
    public function login(array $data = []): array
    {
        return ['url' => $this->getDownload(), 'account' => $this->loginId, 'password' => $this->password];
    }

    /**
     * 获取玩家游戏平台余额
     * @throws GameException|\think\Exception
     */
    public function getBalance()
    {
        $params = [
            'random' => $this->player->uuid ?? uniqid(),
            'sn' => $this->sn,
            'loginId' => $this->loginId,
            'secretCode' => $this->appSecret,
        ];
        $params['digest'] = $this->createSign($params);
        $postData = $this->buildParams($params, 'open.mega.balance.get');
        $result = doCurl($this->apiDomain,$postData);
        if (empty($result['error'])) {
            return $result['result'];
        }else{
            throw new GameException('MeGa888 System Error,Please contact the administrator', 0);
        }
    }

    /**
     * 玩家钱包转入游戏平台
     * @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()
    {
        if($this->getBalance() == 0){
            // 记录玩家钱包转出转入记录
            $this->createWalletTransfer(PlayerWalletTransfer::TYPE_IN, 0, 0);
            return true;
        }
        return $this->autoTransfer();
    }

    /**
     *  轉帳進出額度
     * @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)
    {
        $params = [
            'random' => $this->player->uuid ?? uniqid(),
            'sn' => $this->sn,
            'loginId' => $this->loginId,
            'amount' => $amount,
            'secretCode' => $this->appSecret,
        ];
        $params['digest'] = $this->createSign($params);
        $postData = $this->buildParams($params, 'open.mega.balance.transfer');
        $result = doCurl($this->apiDomain,$postData);
        if (!empty($result['error'])) {
            throw new GameException($result['error']['message'], 0);
        }
        // 记录玩家钱包转出转入记录
        $this->createWalletTransfer($type, $amount, $reward);
        return $result;
    }

    /**
     *  自动下分
     * @return array|mixed|null
     * @throws GameException|\think\Exception
     */
    public function autoTransfer()
    {
        $params = [
            'random' => $this->player->uuid ?? uniqid(),
            'sn' => $this->sn,
            'loginId' => $this->loginId,
            'secretCode' => $this->appSecret,
        ];
        $params['digest'] = $this->createSign($params);
        $postData = $this->buildParams($params, 'open.mega.balance.auto.transfer.out');
        $result = doCurl($this->apiDomain,$postData);
        if (!empty($result['error'])) {
            throw new GameException($result['error']['message'], 0);
        }
        // 记录玩家钱包转出转入记录
        $this->createWalletTransfer(PlayerWalletTransfer::TYPE_IN, $result['result'], 0);
        return $result;
    }

    /**
     * 查询额度转移纪录
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function getTransferList(string $startTime = '', string $endTime = '', int $page = 1, int $pageSize = 15)
    {
        $params = [
            'random' => $this->player->uuid ?? uniqid(),
            'sn' => $this->sn,
            'secretCode' => $this->appSecret,
        ];
        $params['digest'] = $this->createSign($params);
        $params['loginId'] = $this->loginId;
        $params['agentLoginId'] = $this->appId;
        $params['startTime'] = $startTime;
        $params['endTime'] = $endTime;
        $params['timeZone'] = 1;
        $postData = $this->buildParams($params, 'open.mega.balance.transfer.query');
        $result = doCurl($this->apiDomain,$postData);
        if (!empty($result['error'])) {
            throw new GameException($result['error']['message'], 0);
        }
        return $result;
    }

    /**
     * 查询玩家游戏记录
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function getUserGameRecord(string $startTime = '', string $endTime = '')
    {
        $params = [
            'random' => $this->player->uuid ?? uniqid(),
            'sn' => $this->sn,
            'loginId' => $this->loginId,
            'secretCode' => $this->appSecret,
        ];
        $params['digest'] = $this->createSign($params);
        $params['startTime'] = $startTime;
        $params['endTime'] = $endTime;
        $params['timeZone'] = 1;
        $postData = $this->buildParams($params, 'open.mega.player.game.log.url.get');
        $result = doCurl($this->apiDomain,$postData);
        if (!empty($result['error'])) {
            throw new GameException($result['error']['message'], 0);
        }
        return $result['result'];
    }

    /**
     * 查询全部玩家账单
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function getReportRecord(string $startTime = '', string $endTime = '')
    {
        $params = [
            'random' => $this->player->uuid ?? uniqid(),
            'sn' => $this->sn,
            'agentLoginId' => $this->appId,
            'secretCode' => $this->appSecret,
        ];
        $params['digest'] = $this->createSign($params);
        $params['startTime'] = $startTime;
        $params['endTime'] = $endTime;
        $params['timeZone'] = 1;
        $params['type'] = 1;
        $postData = $this->buildParams($params, 'open.mega.player.total.report');
        $result = doCurl($this->apiDomain,$postData);
        if (!empty($result['error'])) {
            throw new GameException($result['error']['message'], 0);
        }
        return $result['result'];
    }

    /**
     * 获取电子游戏注单分页列表
     * @return array|mixed|Response
     * @throws GameException|\think\Exception
     */
    public function getGameOrderById(string $startTime = '', string $endTime = '')
    {
        $params = [
            'random' => $this->player->uuid ?? uniqid(),
            'sn' => $this->sn,
            'loginId' => $this->loginId,
            'secretCode' => $this->appSecret,
        ];
        $params['digest'] = $this->createSign($params);
        $params['startTime'] = $startTime;
        $params['endTime'] = $endTime;
        $params['timeZone'] = 1;
        $postData = $this->buildParams($params, 'open.mega.game.order.page');
        $result = doCurl($this->apiDomain,$postData);
        if (!empty($result['error'])) {
            throw new GameException($result['error']['message'], 0);
        }
        return $result;
    }

    /**
     * 查询玩家游戏记录
     * @return array
     */
    public function handleOrderHistories(): array
    {
        try {
            $list = [];
            $startTime = date('Y-m-d');
            $endTime = date('Y-m-d');
            $data = $this->getReportRecord($startTime, $endTime);
            if (!empty($data)) {
                foreach ($data as $item) {
                    $list[] = [
                        'player_code' => $item['loginId'],
                        'platform_id' => $this->platform->id,
                        'game_code' => 'MeGa888',
                        'bet' => $item['bet'],
                        'win' => $item['win'],
                        'order_no' => $item['userId'].date('Ymd'),
                        'original_data' => json_encode($item,JSON_UNESCAPED_UNICODE),
                        'platform_action_at' => $startTime,
                        'game_type' => 1,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];

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

        return $list;
    }
}