package com.ruoyi.loanpricing.service;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.loanpricing.domain.vo.CustomerMapRecordVO;
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 LoanPricingCustomerMapService
{
    private final RestTemplate restTemplate;

    @Value("${customer-map.personal-url}")
    private String personalUrl;

    @Value("${customer-map.corporate-url}")
    private String corporateUrl;

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

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

    LoanPricingCustomerMapService(RestTemplate restTemplate, String personalUrl, String corporateUrl)
    {
        this.restTemplate = restTemplate;
        this.personalUrl = personalUrl;
        this.corporateUrl = corporateUrl;
    }

    public List<CustomerMapRecordVO> queryPersonal(String custId)
    {
        return query(personalUrl, custId);
    }

    public List<CustomerMapRecordVO> queryCorporate(String custId)
    {
        return query(corporateUrl, custId);
    }

    private List<CustomerMapRecordVO> query(String url, String custId)
    {
        String normalizedCustId = StringUtils.trimWhitespace(custId);
        if (!StringUtils.hasText(normalizedCustId))
        {
            throw new ServiceException("客户号不能为空");
        }
        URI uri = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("cust_id", normalizedCustId)
                .build()
                .encode()
                .toUri();
        CustomerMapResponse response = restTemplate.getForObject(uri, CustomerMapResponse.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 CustomerMapResponse
    {
        private Integer code;
        private String msg;
        private List<CustomerMapRecordVO> data;
    }
}
