package com.ruoyi.loanpricing.service;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.loanpricing.domain.vo.HistoryLoanContractVO;
import java.net.URI;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

@Service
@Slf4j
public class LoanRateHistoryService
{
    private final RestTemplate restTemplate;

    @Value("${loan-rate-history.url}")
    private String historyUrl;

    @Value("${loan-pricing-external.app-code:}")
    private String appCode;

    public LoanRateHistoryService()
    {
        this(new RestTemplate());
    }

    LoanRateHistoryService(RestTemplate restTemplate)
    {
        this.restTemplate = restTemplate;
    }

    LoanRateHistoryService(RestTemplate restTemplate, String historyUrl)
    {
        this(restTemplate, historyUrl, null);
    }

    LoanRateHistoryService(RestTemplate restTemplate, String historyUrl, String appCode)
    {
        this.restTemplate = restTemplate;
        this.historyUrl = historyUrl;
        this.appCode = appCode;
    }

    public List<HistoryLoanContractVO> query(String custIsn)
    {
        String normalizedCustIsn = StringUtils.trimWhitespace(custIsn);
        if (!StringUtils.hasText(normalizedCustIsn))
        {
            throw new ServiceException("客户内码不能为空");
        }
        URI uri = buildGetParamUri(historyUrl, "cust_isn", normalizedCustIsn);
        Map<String, String> requestParams = buildRequestParamLog("cust_isn", normalizedCustIsn);
        HistoryLoanContractResponse response = restTemplate.getForObject(uri, HistoryLoanContractResponse.class);
        log.info("后端外部接口调用完成\n请求URL：{}\n请求参数：\n{}\n返回参数：\n{}",
                uri,
                HttpUtils.formatLogValue(requestParams),
                HttpUtils.formatLogValue(response));
        if (response == null)
        {
            throw new ServiceException("历史贷款合同接口无返回");
        }
        if (response.getCode() != null && response.getCode() != 200)
        {
            throw new ServiceException(StringUtils.hasText(response.getMsg()) ? response.getMsg() : "历史贷款合同查询失败");
        }
        return response.getData() == null ? Collections.emptyList() : response.getData();
    }

    private URI buildGetParamUri(String url, String paramName, String paramValue)
    {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                .replaceQueryParam("appCode")
                .replaceQueryParam(paramName);
        String normalizedAppCode = StringUtils.trimWhitespace(appCode);
        if (StringUtils.hasText(normalizedAppCode))
        {
            builder.queryParam("appCode", normalizedAppCode);
        }
        return builder.queryParam(paramName, paramValue)
                .build()
                .encode()
                .toUri();
    }

    private Map<String, String> buildRequestParamLog(String paramName, String paramValue)
    {
        Map<String, String> requestParams = new LinkedHashMap<>();
        String normalizedAppCode = StringUtils.trimWhitespace(appCode);
        if (StringUtils.hasText(normalizedAppCode))
        {
            requestParams.put("appCode", normalizedAppCode);
        }
        requestParams.put(paramName, paramValue);
        return requestParams;
    }

    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    static class HistoryLoanContractResponse
    {
        private Integer code;
        private String msg;
        private List<HistoryLoanContractVO> data;
    }
}
