package org.xyzh.common.wechat.kefu.info;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.xyzh.common.wechat.kefu.core.KefuAccessTokenManager;
import org.xyzh.common.wechat.pojo.kefu.KefuCustomer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

/**
 * @description    其他基础信息获取服务
 *                 - 获取客户基础信息
 *                 - 获取企业状态信息
 * @filename    KefuInfoService.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-12-19
 */
@Service
public class KefuInfoService {

    private static final Logger logger = LoggerFactory.getLogger(KefuInfoService.class);
    private static final String BASE_URL = "https://qyapi.weixin.qq.com/cgi-bin";

    private final RestTemplate restTemplate = new RestTemplate();
    private final KefuAccessTokenManager tokenManager;
    private KefuInfoHandler handler;

    public KefuInfoService(KefuAccessTokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    public void setHandler(KefuInfoHandler handler) {
        this.handler = handler;
    }

    /**
     * 获取客户基础信息
     */
    public List<KefuCustomer> getCustomerInfo(List<String> externalUseridList) {
        String accessToken = tokenManager.getAccessToken();
        String url = BASE_URL + "/kf/customer/batchget?access_token=" + accessToken;

        JSONObject body = new JSONObject();
        body.put("external_userid_list", externalUseridList);

        String response = postJson(url, body.toJSONString());
        JSONObject result = JSON.parseObject(response);

        if (result.getIntValue("errcode") == 0) {
            List<KefuCustomer> customers = result.getList("customer_list", KefuCustomer.class);
            if (handler != null && customers != null) {
                for (KefuCustomer customer : customers) {
                    handler.onCustomerInfoFetched(customer);
                }
            }
            return customers;
        }

        logger.error("获取客户信息失败: {}", response);
        return null;
    }

    /**
     * 获取企业状态信息
     */
    public JSONObject getCorpStatistic() {
        String accessToken = tokenManager.getAccessToken();
        String url = BASE_URL + "/kf/get_corp_statistic?access_token=" + accessToken;

        JSONObject body = new JSONObject();
        // 可添加时间范围等参数

        String response = postJson(url, body.toJSONString());
        JSONObject result = JSON.parseObject(response);

        if (result.getIntValue("errcode") == 0) {
            return result.getJSONObject("statistic");
        }

        logger.error("获取企业状态信息失败: {}", response);
        return null;
    }

    private String postJson(String url, String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(json, headers);
        return restTemplate.postForObject(url, entity, String.class);
    }

}
