package com.cool.store.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.request.OrderSummaryRequest;
import com.cool.store.request.huoma.ShopBasicInfoRequest;
import com.cool.store.response.IncomeBaseResponse;
import com.cool.store.response.IncomeSummaryResponse;
import com.cool.store.response.OrderSummaryResponse;
import com.cool.store.response.huoma.ShopBaseInfoResponse;
import com.cool.store.response.oppty.OpportunityApiResponse;
import com.cool.store.service.HuoMaService;
import com.cool.store.utils.HmacSigner;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author suzhuhong
 * @Date 2025/4/1 23:20
 * @Version 1.0
 */
@Service
@Slf4j
public class ThirdHuoMaServiceImpl implements HuoMaService {

    @Value("${api.auth.url}")
    private String url;

    @Value("${api.auth.username}")
    private String username;

    @Value("${api.auth.secret}")
    private String secret;

    @Resource
    OkHttpClient okHttpClient;
    @Resource
    ObjectMapper objectMapper;



    @Override
    public ShopBaseInfoResponse getShopInfo(ShopBasicInfoRequest requestBody) {
        String apiUrl = url + "/dzgV1/shop/getShopBasicInfo";
        return executeApiCall(apiUrl,requestBody,ShopBaseInfoResponse.class);
    }

    @Override
    public IncomeBaseResponse getTodayPreIncome(ShopBasicInfoRequest requestBody) {
        String apiUrl = url + "/dzgV1/summary/shop/getTodayPreIncome";
        return executeApiCall(apiUrl,requestBody,IncomeBaseResponse.class);
    }

    @Override
    public IncomeBaseResponse getYesterdayPreIncome(ShopBasicInfoRequest requestBody) {
        String apiUrl = url + "/dzgV1/summary/shop/getYesterdayPreIncome";
        return executeApiCall(apiUrl,requestBody,IncomeBaseResponse.class);
    }

    @Override
    public IncomeBaseResponse getMonthPreIncome(ShopBasicInfoRequest requestBody) {
        String apiUrl = url + "/dzgV1/summary/shop/getMonthPreIncome";
        return executeApiCall(apiUrl,requestBody,IncomeBaseResponse.class);
    }

    @Override
    public OrderSummaryResponse getOrderSummary(OrderSummaryRequest requestBody) {
        String apiUrl = url + "/dzgV1/summary/shop/getOrderSummary";
        return executeApiCall(apiUrl,requestBody,OrderSummaryResponse.class);
    }

    @Override
    public IncomeSummaryResponse getIncomeSummary(OrderSummaryRequest requestBody) {
        String apiUrl = url + "/dzgV1/summary/shop/getIncomeSummary";
        return executeApiCall(apiUrl,requestBody,IncomeSummaryResponse.class);
    }


    private <T> T executeApiCall(String url, Object requestBody, Class<T> responseType) {
        // 1. 打印请求前日志
        logRequest(url, requestBody);

        try {
            Request request = buildRequest(requestBody, url);

            try (Response response = okHttpClient.newCall(request).execute()) {
                // 2. 获取原始响应内容
                String responseBody = response.body().string();

                // 3. 打印响应日志
                logResponse(url, response.code(), responseBody);

                if (!response.isSuccessful()) {
                    throw new ServiceException(ErrorCodeEnum.THIRD_API_ERROR,
                            "HTTP请求失败，状态码: " + response.code());
                }

                // 4. 解析响应
                JavaType javaType = objectMapper.getTypeFactory()
                        .constructParametricType(OpportunityApiResponse.class, responseType);

                OpportunityApiResponse<T> apiResponse = objectMapper.readValue(responseBody, javaType);

                if (apiResponse.getCode() != 200) {
                    throw new ServiceException(ErrorCodeEnum.THIRD_API_ERROR,apiResponse.getMsg());
                }

                return apiResponse.getData();
            }
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error("API调用异常 - URL: {}, 错误: {}", url, e.getMessage(), e);
            throw new ServiceException(ErrorCodeEnum.THIRD_API_ERROR, "接口调用异常: " + e.getMessage());
        }
    }


    /**
     * 记录请求日志
     */
    private void logRequest(String url, Object requestBody) {
        if (log.isInfoEnabled()) {
            try {
                log.info("\n======= 请求开始 =======\n" +
                                "API地址: {}\n" +
                                "请求参数: {}\n" +
                                "======= 请求结束 =======",
                        url,
                        objectMapper.writerWithDefaultPrettyPrinter()
                                .writeValueAsString(requestBody));
            } catch (JsonProcessingException e) {
                log.warn("日志JSON序列化失败", e);
            }
        }
    }

    /**
     * 记录响应日志
     */
    private void logResponse(String url, int statusCode, String responseBody) {
        if (log.isInfoEnabled()) {
            try {
                // 尝试美化JSON输出
                Object json = objectMapper.readValue(responseBody, Object.class);
                String prettyResponse = objectMapper.writerWithDefaultPrettyPrinter()
                        .writeValueAsString(json);

                log.info("\n======= 响应开始 =======\n" +
                                "API地址: {}\n" +
                                "HTTP状态码: {}\n" +
                                "响应内容: {}\n" +
                                "======= 响应结束 =======",
                        url,
                        statusCode,
                        prettyResponse);
            } catch (Exception e) {
                // 非JSON响应或解析失败时直接输出原始内容
                log.info("\n======= 响应开始 =======\n" +
                                "API地址: {}\n" +
                                "HTTP状态码: {}\n" +
                                "原始响应: {}\n" +
                                "======= 响应结束 =======",
                        url,
                        statusCode,
                        responseBody);
            }
        }
    }



    private Request buildRequest(Object requestBody, String url) {

        try {
            Map<String, String> authHeaders = HmacSigner.generateHeaders(
                    username, secret, JSONObject.toJSONString(requestBody));

            log.debug("签名生成 -  签名结果: {}", JSONObject.toJSONString(authHeaders));

            RequestBody body = RequestBody.create(MediaType.parse("application/json"),
                    JSONObject.toJSONString(requestBody)
            );

            return new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .addHeader("x-Date", authHeaders.get("x-Date"))
                    .addHeader("Digest", authHeaders.get("Digest"))
                    .addHeader("Authorization", authHeaders.get("Authorization"))
                    .build();
        } catch (Exception e) {
            throw new ServiceException(ErrorCodeEnum.THIRD_API_SIGN_ERROR);
        }
    }
}
