package com.ruoyi.loanpricing.service;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.loanpricing.domain.vo.HistoryLoanContractVO;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import lombok.Data;
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
public class LoanRateHistoryService
{
    private final RestTemplate restTemplate;

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

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

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

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

    public List<HistoryLoanContractVO> query(String custIsn)
    {
        String normalizedCustIsn = StringUtils.trimWhitespace(custIsn);
        if (!StringUtils.hasText(normalizedCustIsn))
        {
            throw new ServiceException("客户内码不能为空");
        }
        URI uri = UriComponentsBuilder.fromHttpUrl(historyUrl)
                .queryParam("cust_isn", normalizedCustIsn)
                .build()
                .encode()
                .toUri();
        HistoryLoanContractResponse response = restTemplate.getForObject(uri, HistoryLoanContractResponse.class);
        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();
    }

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