package com.hdkj.lt.si.service.remote.impl;

import com.alibaba.fastjson.JSON;
import com.hdkj.lt.base.exception.ExceptionCast;
import com.hdkj.lt.core.rest.config.HttpClientConfig;
import com.hdkj.lt.si.modle.algorithm.IndicatorStatusResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 算法服务远程调用
 *
 * @Description 调用观音阁算法服务 /api/indicators 接口，获取指标计算结果。
 * 算法服务直接返回业务数据（无 code/data 外壳），不继承 AbstractDefaultRemoteCallService。
 */
@Slf4j
@Service
public class AlgorithmRemoteCallServiceImpl {

    @Resource(name = HttpClientConfig.CONN_POOL_REST_TEMPLATE)
    private RestTemplate restTemplate;

    @Value("${remote.algorithm.request-uri}")
    private String requestUri;

    @Value("${remote.algorithm.indicators-uri}")
    private String indicatorsUri;

    @Value("${remote.algorithm.static-grid-uri}")
    private String staticGridUri;

    /**
     * 调用指标计算接口
     *
     * @return 指标计算结果
     */
    public IndicatorStatusResponse queryIndicators() {
        String requestUrl = requestUri.concat(indicatorsUri);
        String requestBody = "{}";
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            headers.set(HttpHeaders.ACCEPT_CHARSET, Charsets.UTF_8.toString());
            HttpEntity<String> httpEntity = new HttpEntity<>(requestBody, headers);

            log.info("调用算法指标接口, requestUrl: {}", requestUrl);
            ResponseEntity<IndicatorStatusResponse> responseEntity = restTemplate.postForEntity(
                    requestUrl, httpEntity, IndicatorStatusResponse.class);

            if (!responseEntity.getStatusCode().is2xxSuccessful() || Objects.isNull(responseEntity.getBody())) {
                String errorMsg = String.format("调用算法指标接口失败, requestUrl: %s, response: %s",
                        requestUrl, JSON.toJSONString(responseEntity));
                log.error(errorMsg);
                ExceptionCast.cast(errorMsg);
            }

            IndicatorStatusResponse result = responseEntity.getBody();
            log.info("调用算法指标接口成功, requestUrl: {}, computeResult: {}",
                    requestUrl, result.getComputeResult());
            return result;
        } catch (Exception e) {
            log.error("调用算法指标接口异常, requestUrl: {}, errorMsg: {}", requestUrl, e.toString());
            ExceptionCast.cast("调用算法指标接口失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 调用静态网架评估接口
     * <p>
     * 算法返回完整 JSON（含 code/message/calculation_result 外壳），此处返回原始字符串，
     * 由 Service 层解析入库。
     *
     * @param requestBodyJson 请求体 JSON（含 county 信息、scope 等）
     * @return 算法返回的完整 JSON 字符串
     */
    public String queryStaticGridIndicators(String requestBodyJson) {
        String requestUrl = requestUri.concat(staticGridUri);
        String requestBody = requestBodyJson != null ? requestBodyJson : "{}";
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            headers.set(HttpHeaders.ACCEPT_CHARSET, Charsets.UTF_8.toString());
            HttpEntity<String> httpEntity = new HttpEntity<>(requestBody, headers);

            log.info("调用算法静态网架评估接口, requestUrl: {}", requestUrl);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(
                    requestUrl, httpEntity, String.class);

            if (!responseEntity.getStatusCode().is2xxSuccessful() || Objects.isNull(responseEntity.getBody())) {
                String errorMsg = String.format("调用算法静态网架评估接口失败, requestUrl: %s, response: %s",
                        requestUrl, JSON.toJSONString(responseEntity));
                log.error(errorMsg);
                ExceptionCast.cast(errorMsg);
            }

            String result = responseEntity.getBody();
            log.info("调用算法静态网架评估接口成功, requestUrl: {}, length: {}", requestUrl, result.length());
            return result;
        } catch (Exception e) {
            log.error("调用算法静态网架评估接口异常, requestUrl: {}, errorMsg: {}", requestUrl, e.toString());
            ExceptionCast.cast("调用算法静态网架评估接口失败: " + e.getMessage());
            return null;
        }
    }
}
