package com.bizzan.bitrade.controller.system;

import com.bizzan.bitrade.controller.common.BaseAdminController;
import com.bizzan.bitrade.util.MessageResult;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/spot")
@Slf4j
public class AdminSpotController extends BaseAdminController {

    @Autowired
    @Qualifier("plainRestTemplate")
    private RestTemplate restTemplate;

    @Value("${spot.api.url}")
    private String spotUrl;

    @PostMapping("/order/page")
    public MessageResult orderPage(@RequestBody Map<String, Object> req) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(req, headers);
            String result = restTemplate.postForObject(buildSpotUrl("/admin/order/page"), entity, String.class);
            return success(parseData(result));
        } catch (Exception e) {
            log.error("查询订单失败", e);
            return error("查询订单失败: " + e.getMessage());
        }
    }

    @PostMapping("/trade/page")
    public MessageResult tradePage(@RequestBody Map<String, Object> req) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(req, headers);
            String result = restTemplate.postForObject(buildSpotUrl("/admin/trade/page"), entity, String.class);
            return success(parseData(result));
        } catch (Exception e) {
            log.error("查询成交记录失败", e);
            return error("查询成交记录失败: " + e.getMessage());
        }
    }

    @GetMapping("/symbol/all")
    public MessageResult allSymbols() {
        try {
            String result = restTemplate.getForObject(buildSpotUrl("/config/admin/symbol/list"), String.class);
            return success(parseSymbolList(result));
        } catch (Exception e) {
            log.error("获取交易对列表失败", e);
            return error("获取交易对列表失败: " + e.getMessage());
        }
    }

    private String buildSpotUrl(String path) {
        String base = spotUrl == null ? "" : spotUrl.trim();
        if (base.length() == 0 || base.contains("@spot.api.url@")) {
            throw new IllegalStateException("spot.api.url 未配置，请配置为 http://host:port/v1");
        }
        if (!base.startsWith("http://") && !base.startsWith("https://")) {
            throw new IllegalStateException("spot.api.url 必须是绝对地址，请检查配置：" + base);
        }
        while (base.endsWith("/")) {
            base = base.substring(0, base.length() - 1);
        }
        return base + path;
    }

    private Object parseData(String json) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
            JsonNode node = mapper.readTree(json);
            if (node.has("data")) {
                String dataStr = node.get("data").toString();
                return mapper.readValue(dataStr, Object.class);
            }
            return json;
        } catch (Exception e) {
            return json;
        }
    }

    private List<Map<String, String>> parseSymbolList(String json) {
        List<Map<String, String>> symbols = new ArrayList<>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readTree(json);
            JsonNode dataNode = node.has("data") ? node.get("data") : node;
            if (dataNode != null && dataNode.isArray()) {
                for (JsonNode item : dataNode) {
                    String symbol = extractSymbol(item);
                    if (symbol.length() == 0) {
                        continue;
                    }
                    Map<String, String> option = new LinkedHashMap<>();
                    option.put("symbol", symbol);
                    symbols.add(option);
                }
            }
        } catch (Exception e) {
            log.warn("解析交易对列表失败", e);
        }
        return symbols;
    }

    private String extractSymbol(JsonNode item) {
        if (item == null || item.isNull()) {
            return "";
        }
        if (item.isTextual()) {
            return item.asText().trim();
        }
        JsonNode symbolNode = item.get("symbol");
        if (symbolNode == null || symbolNode.isNull()) {
            return "";
        }
        if (symbolNode.isTextual()) {
            return symbolNode.asText().trim();
        }
        JsonNode nestedSymbolNode = symbolNode.get("symbol");
        if (nestedSymbolNode != null && nestedSymbolNode.isTextual()) {
            return nestedSymbolNode.asText().trim();
        }
        return "";
    }
}
