<?php

namespace app\command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use support\Db;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;


class GetcoinBitget extends Command
{
    protected $source = 'bitget';
    protected static $defaultName = 'getcoin:bitget';
    protected static $defaultDescription = 'getcoin bitget';
    private string $apiKey;
    private string $secretKey;
    private string $passphrase;
    private string $baseUrl;
    /**
     * @return void
     */

    protected function configure()
    {
        $config=Db::table('apisetting')->where('source', $this->source)->first();
        $this->apiKey = $config->api;
        $this->secretKey = $config->apikey;
        $this->passphrase = $config->passphrase;
        $this->baseUrl = 'https://'.$config->domain;
        $this->addArgument('name', InputArgument::OPTIONAL, 'Name description');
    }
    protected function config()
    {
        return ;
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $output->writeln($this->source.' Getcoin Now Running');


        $response = $this->sendRequest('GET', '/api/v2/earn/savings/product', [
            'filter' => 'available',
        ]);
        if(isset($response)&&isset($response->code)&&$response->code=='00000'&&isset($response->data)){
            $bakdata = [];
            foreach($response->data as $data){
                if($data->periodType!='flexible' || $data->productLevel!='normal'){
                    continue;
                }
                $apyValues = array_map(function($item) {
                    return floatval($item->currentApy);
                }, $data->apyList);  
                if($data->status=='in_progress'){
                    $available=1;
                }else{
                    $available=0;
                }
                $bakdata[]=[
                    'token'=>strtoupper($data->coin),
                    'type'=>'earn',
                    'subtype'=>'flexible',
                    'source'=>'bitget',
                    'rate'=>max($apyValues),
                    'min_rate'=>min($apyValues),
                    'update'=>date('Y-m-d H:i:s'),
                    'available' => $available,
                ];
            }
            Db::table('coininfo')->upsert(
                $bakdata,                // 插入的数据
                ['token', 'type','subtype','source'],  // 复合唯一标识列（user_id 和 product_id 组合）
                ['rate','min_rate','update','available']      // 如果记录存在，更新的字段
            );
        }else{
            $output->writeln('<error>Request API Error</error>');
            return self::SUCCESS;
        }
        $output->writeln('OK');
        return self::SUCCESS;
    }
    private function generateSignature($timestamp, $method, $requestPath, $queryString = '', $body = null)
    {
        $method = strtoupper($method);

        $preHash = $timestamp . $method . $requestPath;
        if ($queryString) {
            $preHash .= '?' . $queryString;
        }
        if($body){
            $preHash .= $body;
        }
        return base64_encode(hash_hmac('sha256', $preHash, $this->secretKey, true));
    }
    private function sendRequest($method, $requestPath, $queryParams = null, $bodyParams = null)
    {
        $timestamp = (int)microtime(true) * 1000;



        $queryString = http_build_query($queryParams);
        $body = !empty($bodyParams) ? json_encode($bodyParams) : '';

        $signature = $this->generateSignature($timestamp, $method, $requestPath, $queryString, $body);
        // 构建请求头
        $headers = [
            'access-key' => $this->apiKey,
            'access-sign' => $signature,
            'access-timestamp' => $timestamp,
            'access-passphrase' => $this->passphrase,
            'content-type' => 'application/json',
            'locale' => 'zh-CN',
        ];
       /** 
        $headers = array(
            'ACCESS-KEY: '.$this->apiKey,
            'ACCESS-SIGN: '.$signature,
            'ACCESS-TIMESTAMP: '.$timestamp,
            'ACCESS-PASSPHRASE: '.$this->passphrase,
            'Content-type: application/json',
            'locale: zh-CN',
        );*/
        // 构建完整 URL
        $url = $this->baseUrl . $requestPath;

        if ($queryString) {
            $url .= '?' . $queryString;
        }
   
        $client = new Client();
            // 发送同步请求
            $response = $client->request($method, $this->baseUrl . $requestPath, [
                'headers' => $headers,
                'query' => $queryParams, // 用于 GET 请求的查询参数
                'json' => $bodyParams,   // 用于 POST 请求的 JSON 数据
            ]);

            
                return json_decode($response->getBody()); // 解析响应
        /** 
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_STDERR, fopen('php://stderr', 'w'));
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;*/

    }

}
