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.CustomerMapRecordVO;
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 LoanPricingCustomerMapService
{
    private final RestTemplate restTemplate;

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

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

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

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

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

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

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

    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 = buildGetParamUri(url, "cust_id", normalizedCustId);
        Map<String, String> requestParams = buildRequestParamLog("cust_id", normalizedCustId);
        CustomerMapResponse response = restTemplate.getForObject(uri, CustomerMapResponse.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 CustomerMapResponse
    {
        private Integer code;
        private String msg;
        private List<CustomerMapRecordVO> data;
    }
}
