package org.hzhub.crm.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hzhub.common.core.domain.R;
import org.hzhub.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * ERP集成服务
 * 封装对 hzhub-erp 的调用
 *
 * @author hzhub
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ErpIntegrationService {

    @Value("${erp.base-url:http://localhost:8082}")
    private String erpBaseUrl;

    private final RestTemplate restTemplate;

    /**
     * 获取ERP客户详情
     *
     * @param customerCode ERP客户编码
     * @return 客户信息（Map形式，包含customerName, contactName, phone等字段）
     */
    public Map<String, Object> getCustomerDetail(String customerCode) {
        if (StringUtils.isBlank(customerCode)) {
            return null;
        }

        try {
            String url = erpBaseUrl + "/erp/dynamic/v1/customer/detail?customerCode=" + customerCode;
            log.info("调用ERP服务获取客户详情: {}", url);

            R<Map<String, Object>> response = restTemplate.getForObject(url, R.class);
            if (response != null && response.getCode() == 200) {
                return response.getData();
            }

            log.warn("ERP客户详情获取失败: customerCode={}, response={}", customerCode, response);
            return null;
        } catch (Exception e) {
            log.error("调用ERP服务异常: customerCode={}", customerCode, e);
            return null;
        }
    }

    /**
     * 获取ERP客户列表（可选）
     *
     * @param params 查询参数
     * @return 客户列表
     */
    public Object getCustomerList(Map<String, Object> params) {
        try {
            String url = erpBaseUrl + "/erp/dynamic/v1/customer/list";
            log.info("调用ERP服务获取客户列表: {}", url);

            // 这里简化处理，实际应根据params构建查询参数
            R<Object> response = restTemplate.getForObject(url, R.class);
            if (response != null && response.getCode() == 200) {
                return response.getData();
            }

            log.warn("ERP客户列表获取失败: response={}", response);
            return null;
        } catch (Exception e) {
            log.error("调用ERP服务异常", e);
            return null;
        }
    }
}