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.GetPasswordDTO;
import com.cool.store.response.oppty.OpportunityApiResponse;
import com.cool.store.service.ThirdXinGuanJiaService;
import com.cool.store.utils.JsonUtils;
import com.cool.store.utils.SignatureUtils;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.stereotype.Service;

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

/**
 * @Author suzhuhong
 * @Date 2025/4/11 15:03
 * @Version 1.0
 */
@Service
@Slf4j
public class ThirdXinGuanJiaServiceImpl implements ThirdXinGuanJiaService {


    @Resource
    OkHttpClient okHttpClient;

    @Resource
    ObjectMapper objectMapper;


    @Override
    public String getPassword(GetPasswordDTO dto) {
        String url = "http://webapi.zhengxinfood.com/api/supply-chain/get-hash-pwd";
        return executeApiCall(url, dto, String.class);
    }



    private <T> T executeApiCall(String url, Object requestBody, Class<T> responseType) {
        try {
            Request request = buildRequest(requestBody, url);

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


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

                // 4. 解析响应
                T result = (T) JSONObject.parseObject(responseBody, JSONObject.class).get("result");
                return result;
            }
        } 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 Request buildRequest(Object requestBody, String url) {
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json"),
                JSONObject.toJSONString(requestBody)
        );

        return new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
    }

}
