<?php

namespace App\Http\Controllers;

use App\Models\UsdtC2c;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class BinanceController extends Controller
{
    public function getMaxUsdtLak()
    {
        $url = 'https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search';

        $response = Http::post($url, [
            'asset' => 'USDT',
            'fiat' => 'LAK',
            'tradeType' => 'SELL',
            'page' => 1,
            'rows' => 20,
            'merchantCheck' => true
        ]);

        if (!$response->ok()) {
            return response()->json(['error' => '请求失败'], 500);
        }

        $ads = $response->json('data');
        $maxPrice = collect($ads)->max(fn ($item) => (float) $item['adv']['price']);

        return response()->json([
            'max_price' => $maxPrice
        ]);
    }

    public function getUsdtLakForAmount()
    {
        $url = 'https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search';

        $amount = 20000000; // 查询200万LAK的卖价

        $response = Http::post($url, [
            'asset' => 'USDT',
            'fiat' => 'LAK',
            'tradeType' => 'SELL',
            'page' => 1,
            'rows' => 20,
            'merchantCheck' => true,
            'transAmount' => $amount
        ]);

        if (!$response->ok()) {
            return response()->json(['error' => '请求失败'], 500);
        }

        $ads = $response->json('data');

        if (empty($ads)) {
            return response()->json(['message' => '找不到符合条件的卖单']);
        }

        // 按照价格升序排列，取最便宜的那个
        // $sorted = collect($ads)->sortBy(fn ($item) => (float) $item['adv']['price']);
        $sorted = collect($ads)->sortByDesc(fn ($item) => (float) $item['adv']['price']); 
        $best = $sorted->first();

        // dd($best);

        return response()->json([
            'price' => $best['adv']['price'],
            'availableQuantity' => $best['adv']['surplusAmount'],
            'minAmount' => $best['adv']['minSingleTransAmount'],
            'maxAmount' => $best['adv']['maxSingleTransAmount'],
            'nickName' => $best['advertiser']['nickName']
        ]);
    }

    public function savePrice()
    {
        $url = 'https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search';

        // 1. 获取最高价（不限制金额）
        $respAll = Http::post($url, [
            'asset' => 'USDT',
            'fiat' => 'LAK',
            'tradeType' => 'SELL',
            'page' => 1,
            'rows' => 20,
            'merchantCheck' => true
        ]);

        // 2. 获取 200 万成交价
        $resp200 = Http::post($url, [
            'asset' => 'USDT',
            'fiat' => 'LAK',
            'tradeType' => 'SELL',
            'page' => 1,
            'rows' => 20,
            'merchantCheck' => true,
            'transAmount' => 2000000
        ]);

        if (!$respAll->ok() || !$resp200->ok()) {
            return response()->json(['error' => 'Binance 请求失败'], 500);
        }

        $adsAll = $respAll->json('data');
        $ads200 = $resp200->json('data');

        $highestPrice = collect($adsAll)->max(fn($item) => (float) $item['adv']['price']);
        $priceFor200M = collect($ads200)->sortByDesc(fn($item) => (float) $item['adv']['price'])->first()['adv']['price'] ?? null;

        // 写入一行资料
        UsdtC2c::create([
            'Highest' => $highestPrice,
            'Million' => $priceFor200M,
        ]);

        return response()->json([
            'status' => '写入成功',
            'Highest' => $highestPrice,
            'Million' => $priceFor200M
        ]);
    }

}
