package com.wms_main.service.api.serviceImpl;

import com.wms_main.app.AppCommon;
import com.wms_main.constant.enums.wms.AppConfigKeyEnums;
import com.wms_main.model.dto.request.ewm.*;
import com.wms_main.model.dto.response.ewm.EwmApiBackResponse;
import com.wms_main.model.dto.response.ewm.EwmApiLocalResponse;
import com.wms_main.model.dto.response.ewm.EwmApiStockResponse;
import com.wms_main.repository.http.HttpClient;
import com.wms_main.repository.http.entity.HttpRequest;
import com.wms_main.repository.http.entity.HttpResponse;
import com.wms_main.service.api.IEwmApiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * Ewm接口服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class EwmApiServiceImpl implements IEwmApiService {
    private final HttpClient httpClient;// http客户端
    private final AppCommon appCommon;// 应用共通asrs/mom@123456

    /**
     * 发送载具入库请求到EWM系统
     * @param request 载具入库请求
     * @return EWM系统响应结果
     */
    @Override
    public EwmApiLocalResponse sendVehicleForIn(SendEwmVehicleForInRequest request) {
        try {
            // 构建Basic Auth认证信息
            String auth = "asrs:mom@123456";
            String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes());

            // 设置http请求
            HttpRequest httpRequest = HttpRequest.postInstanceOf(
                    appCommon.getConfigByKey(AppConfigKeyEnums.EWM_SEND_VEHICLE_URL.getKey()),
                    request,
                    5000,
                    "application/json",
                    "Basic " + encodedAuth);

            // 记录即将发送的请求数据
            String requestData = com.alibaba.fastjson2.JSON.toJSONString(request);
            log.info("即将发送的请求数据: {}", requestData);

            HttpResponse httpResponse = httpClient.httpPost(httpRequest);

            if (httpResponse != null && httpResponse.isSuccess()) {
                return httpResponse.getData(EwmApiLocalResponse.class);
            }

            log.warn("载具请求入库时EWM系统返回空响应或请求失败，请求参数: {}", request);
            return EwmApiLocalResponse.error("EWM系统返回空响应或请求失败");
        } catch (Exception e) {
            log.error("调用EWM系统接口异常，请求参数: {}", request, e);
            return EwmApiLocalResponse.error("调用EWM系统接口异常: " + e.getMessage());
        }
    }
    /**
     * 入库上架后获取EWM系统返回的信息
     * @param request 载具入库完成
     * @return EWM系统响应结果
     */
    @Override
    public EwmApiBackResponse sendWarehouseInCompleted(SendWarehouseInCompletedRequest request) {
        try {
            // 构建Basic Auth认证信息
            String auth = "asrs:mom@123456";
            String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes());

            // 设置http请求
            HttpRequest httpRequest = HttpRequest.postInstanceOf(
                    appCommon.getConfigByKey(AppConfigKeyEnums.EWM_SEND_WAREHOUSE_IN_COMPLETED_URL.getKey()),
                    request,
                    10000,
                    "application/json",
                    "Basic " + encodedAuth);
            HttpResponse httpResponse = httpClient.httpPost(httpRequest);

            if (httpResponse != null && httpResponse.isSuccess()) {
                return httpResponse.getData(EwmApiBackResponse.class);
            }

            log.warn("入库完成EWM系统返回空响应或请求失败，请求参数: {}", request);
            return EwmApiBackResponse.error("EWM系统返回空响应或请求失败");
        } catch (Exception e) {
            log.error("调用EWM系统接口异常，请求参数: {}", request, e);
            return EwmApiBackResponse.error("调用EWM系统接口异常: " + e.getMessage());
        }
    }

    @Override
    public EwmApiBackResponse sendWarehouseOutCompleted(SendWarehouseOutCompletedRequest request) {
        try {
            // 构建Basic Auth认证信息
            String auth = "asrs:mom@123456";
            String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes());

            // 设置http请求
            HttpRequest httpRequest = HttpRequest.postInstanceOf(
                    appCommon.getConfigByKey(AppConfigKeyEnums.EWM_SEND_WAREHOUSE_OUT_COMPLETED_URL.getKey()),
                    request,
                    10000,
                    "application/json",
                    "Basic " + encodedAuth);

            HttpResponse httpResponse = httpClient.httpPost(httpRequest);

            if (httpResponse != null && httpResponse.isSuccess()) {
                return httpResponse.getData(EwmApiBackResponse.class);
            }

            log.warn("出库完成EWM系统返回空响应或请求失败，请求参数: {}", request);
            return EwmApiBackResponse.error("EWM系统返回空响应或请求失败");
        } catch (Exception e) {
            log.error("调用EWM系统接口异常，请求参数: {}", request, e);
            return EwmApiBackResponse.error("调用EWM系统接口异常: " + e.getMessage());
        }
    }

    @Override
    public EwmApiBackResponse sendContainerEmpty(SendEwmVehicleForInRequest request) {
        try {
            // 获取基础URL
            String baseUrl = appCommon.getConfigByKey(AppConfigKeyEnums.EWM_SEND_CONTAINER_EMPTY_URL.getKey());

            // 替换URL中的{palletNo}占位符（假设request中有palletNo字段）
            // 需要根据SendEwmVehicleForInRequest的实际结构来获取palletNo
            String finalUrl = baseUrl.replace("{palletNo}", request.getContainerNo()); // 示例，具体字段名需根据实际类确定

            // 构建Basic Auth认证信息
            String auth = "asrs:mom@123456";
            String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes());

            // 设置http请求，将认证信息放在token字段中
            HttpRequest httpRequest = HttpRequest.postInstanceOf(
                    finalUrl,
                    request,
                    10000,
                    "application/json",
                    "Basic " + encodedAuth);

            HttpResponse httpResponse = httpClient.httpPost(httpRequest);

            if (httpResponse != null && httpResponse.isSuccess()) {
                return httpResponse.getData(EwmApiBackResponse.class);
            }
            log.warn("出库完成回告EWM系统容器置空返回空响应或请求失败，请求参数: {}", request);
            return EwmApiBackResponse.error("EWM系统返回空响应或请求失败");
        } catch (Exception e) {
            log.error("调用EWM系统接口异常，请求参数: {}", request, e);
            return EwmApiBackResponse.error("调用EWM系统接口异常: " + e.getMessage());
        }
    }

    @Override
    public EwmApiStockResponse getEwmStock(SendEwmGetStockInformationRequest request) {
        try {
            // 构建Basic Auth认证信息
            String auth = "asrs:mom@123456";
            String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes());

            // 设置http请求
            HttpRequest httpRequest = HttpRequest.postInstanceOf(
                    appCommon.getConfigByKey(AppConfigKeyEnums.EWM_GET_STOCK_LIST_URL.getKey()),
                    request,
                    10000,
                    "application/json",
                    "Basic " + encodedAuth);
            HttpResponse httpResponse = httpClient.httpPost(httpRequest);

            if (httpResponse != null && httpResponse.isSuccess()) {
                return httpResponse.getData(EwmApiStockResponse.class);
            }
            log.warn("拉取EWM系统库存数据失败，请求参数: {}", request);
            return EwmApiStockResponse.error("拉取EWM系统库存数据失败");
        } catch (Exception e) {
            log.error("调用EWM系统接口异常，请求参数: {}", request, e);
            return EwmApiStockResponse.error("调用EWM系统接口异常: " + e.getMessage());
        }
    }

    @Override
    public EwmApiBackResponse sendEwmCheckContainerNo(SendEwmCheckContainerNo request) {
        try {
            // 构建Basic Auth认证信息
            String auth = "asrs:mom@123456";
            String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes());

            // 设置http请求
            HttpRequest httpRequest = HttpRequest.postInstanceOf(
                    appCommon.getConfigByKey(AppConfigKeyEnums.EWM_CHECK_CONTAINER_NO_URL.getKey()),
                    request,
                    10000,
                    "application/json",
                    "Basic " + encodedAuth);
            HttpResponse httpResponse = httpClient.httpPost(httpRequest);

            if (httpResponse != null && httpResponse.isSuccess()) {
                return httpResponse.getData(EwmApiBackResponse.class);
            }

            log.warn("请求验证EWM系统返回空响应或请求失败，请求参数: {}", request);
            return EwmApiBackResponse.error("EWM系统返回空响应或请求失败");
        } catch (Exception e) {
            log.error("调用EWM系统接口异常，请求参数: {}", request, e);
            return EwmApiBackResponse.error("调用EWM系统接口异常: " + e.getMessage());
        }
    }
}
