<?php
namespace app\common\service;

use app\admin\model\Config as ConfigModel;
use app\admin\model\Game;
use app\admin\model\Provider;
use think\Exception;

class JK8Services
{
    private $domain = '';
    private $accessId = '';
    private $token = '';

    public function __construct()
    {
        $config = ConfigModel::where('group', 'jdk_api')->column('value', 'name');
        $this->domain = $config['api_url'];
        $this->accessId = $config['access_id'];
        $this->token = $config['token'];
    }

    /**
     * 构建请求参数
     * @param string $method
     * @param array $params
     * @return array
     */
    public function createParam(string $method, array $params): array
    {
        return [
            'module'      => $method,
            'accessId'    => $this->accessId,
            'accessToken' => $this->token,
            ...$params,
        ];
    }

    /**
     * 用户注册
     * @param string $username
     * @param string $nickname
     * @param string $referrerCode
     * @return string
     * @throws Exception
     */
    public function register(string $username, string $nickname, string $referrerCode): string
    {
        $params = $this->createParam('/member/register', [
            'username' => $username,
            // 'name'     => $nickname,
            'referrerCode'     => $referrerCode,
        ]);
        $result = doCurl($this->domain, $params);
        if (($result['status'] ?? '') === 'ERROR') {
            throw new Exception($result['data']['message'] ?? 'Remote API Error');
        }
        return $result['data']['id'];
    }

    /**
     * 用户注册
     * @param int|null $userId
     * @return string
     * @throws Exception
     */
    public function getAllUsers(int $userId = null): string
    {
        $params = $this->createParam('/users/getAllUsers', [
            'id' => $userId,
        ]);
        $result = doCurl($this->domain, $params);
        if (($result['status'] ?? '') === 'ERROR') {
            throw new Exception($result['data']['message'] ?? 'Remote API Error');
        }
        return $result['data']['users'][0]['username'] ?? '';
    }
    /**
     * 获取促销列表
     * @param string $userId
     * @return array|mixed|null
     * @throws Exception
     */
    public function getPromotionList(string $userId): mixed
    {
        $params = $this->createParam('/users/getPromotionList', [
            'userId' => $userId,
        ]);
        $result = doCurl($this->domain, $params);
        if (($result['status'] ?? '') === 'ERROR') {
            throw new Exception($result['data']['message'] ?? 'Remote API Error');
        }
        return $result;
    }

    /**
     * 转账
     * @param string $username
     * @param float $amount
     * @return array|mixed|null
     * @throws Exception
     */
    public function setScore(string $username, float $amount): mixed
    {
        $params = $this->createParam('/member/setScore', [
            'username' => $username,
            'amount' => $amount
        ]);
        $result = doCurl($this->domain, $params);
        if (($result['status'] ?? '') === 'ERROR') {
            throw new Exception($result['data']['message'] ?? 'Remote API Error');
        }
        return $result['data']['transactionId'];
    }

    /**
     * 获取厂商列表
     * @return array|mixed|null
     * @throws Exception
     */
    public function getGameCategory(): mixed
    {
        $params = $this->createParam('/games/getGameCategory', []);
        $result = doCurl($this->domain, $params);
        if (($result['status'] ?? '') === 'ERROR') {
            throw new Exception($result['data']['message'] ?? 'Remote API Error');
        }
        foreach ($result['data'] as $item) {
            if (!empty($item['sites']) && is_array($item['sites'])) {
                foreach ($item['sites'] as $siteItem) {
                    if (isset($siteItem['hasGameList']) && $siteItem['hasGameList'] === false) {
                        continue;
                    }
                    if (!empty($siteItem['site'])) {
                        $allSites[] = $siteItem['site'];
                    }
                }
            }
        }
        $uniqueSites = array_values(array_unique($allSites));

        $insertData = [];
        foreach ($uniqueSites as $site) {
            $insertData[] = ['site' => $site, 'create_time' => time()];
        }
        if ($insertData) {
            $p = new Provider;
            $p->saveAll($insertData);
        }
        return $insertData;
    }
    /**
     * 获取游戏列表
     * @return array|mixed|null
     * @throws Exception
     */
    public function getGameList(): mixed
    {
        $data = [];
        $sites = Provider::column('site');
        foreach ($sites as $site) {
            $post['site'] = $site;
            $params = $this->createParam('/games/getGameList', $post);
            $result = doCurl($this->domain, $params);
            if (($result['status'] ?? '') === 'ERROR') {
                throw new Exception($result['data']['message'] ?? 'Remote API Error');
            }
            foreach ($result['data'] as $game) {
                $data['provider_site'] = $site;
                $data['game_code'] = $game['GameCode'] ?? '';
                $data['game_name'] = $game['GameName'] ?? '';
                $data['game_type'] = ltrim(strstr($game['GameType'], '-'), '-') ?? '';
                $data['image_url'] = $game['GameImageUrl'] ?? '';
                $data['create_time'] = time();
                $insert[] = $data;
            }
        }
        if ($insert) {
            $g = new Game;
            $g->saveAll($insert);
        }
        return $insert;
    }
}
