package com.wms_main.service.api.serviceImpl;

import com.wms_main.app.AppCommon;

import java.util.Objects;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wms_main.constant.enums.wcs.WcsApiResponseCodeEnums;
import com.wms_main.constant.enums.wms.AppConfigKeyEnums;
import com.wms_main.model.bo.wcs.WcsPickTask;
import com.wms_main.model.bo.wcs.WcsStackerTask;
import com.wms_main.model.dto.request.wcs.WcsPickTaskRequest;
import com.wms_main.model.dto.request.wcs.WcsQueryStandStatusRequest;
import com.wms_main.model.dto.request.wcs.WcsReleaseBoxRequest;
import com.wms_main.model.dto.request.wcs.WcsStackerTaskRequest;
import com.wms_main.model.dto.response.wcs.BaseWcsApiResponse;
import com.wms_main.model.dto.response.wcs.WcsApiResponse;
import com.wms_main.model.dto.response.wcs.WcsCanFeedResponse;
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.IWcsApiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * Wcs接口服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WcsApiServiceImpl implements IWcsApiService {
    private final HttpClient httpClient;// http客户端
    private final AppCommon appCommon;// 应用共通
    private final ObjectMapper objectMapper;

    /**
     * 发送堆垛机任务
     *
     * @param request 任务请求
     * @return 响应结果
     */
    @Override
    public WcsApiResponse<WcsStackerTask> sendWcsStackerTask(WcsStackerTaskRequest request) {
        // 设置http请求
        HttpRequest httpRequest = HttpRequest.postInstanceOf(appCommon.getConfigByKey(AppConfigKeyEnums.WCS_STACKER_TASK_URL.getKey()), request);
         HttpResponse httpResponse = httpClient.httpPost(httpRequest);
         if (httpResponse != null && httpResponse.isSuccess()) {
             WcsApiResponse<WcsStackerTask> response = new WcsApiResponse<>();
             response = httpResponse.getData(response.getClass().asSubclass(WcsApiResponse.class));
             return response;
         }
         return WcsApiResponse.error("请求未获得响应信息。", null);
//        return WcsApiResponse.success("请求未获得响应信息。", null);
    }

    /**
     * 发送拣选任务
     *
     * @param request 任务请求
     * @return 响应结果
     */
    @Override
    public WcsApiResponse<WcsPickTask> sendPickTask(WcsPickTaskRequest request) {
        // 设置http请求
        HttpRequest httpRequest = HttpRequest.postInstanceOf(appCommon.getConfigByKey(AppConfigKeyEnums.WCS_PICK_TASK_URL.getKey()), request);
        HttpResponse httpResponse = httpClient.httpPost(httpRequest);
        if (httpResponse != null && httpResponse.isSuccess()) {
            WcsApiResponse<WcsPickTask> response = new WcsApiResponse<>();
            response = httpResponse.getData(response.getClass().asSubclass(WcsApiResponse.class));
            return response;
        }
        return WcsApiResponse.error("请求未获得响应信息。", null);
    }

    /**
     * 发送释放载具请求
     *
     * @param request 释放请求信息
     * @return 响应结果
     */
    @Override
    public BaseWcsApiResponse releaseBox(WcsReleaseBoxRequest request) {
        // 设置http请求
        HttpRequest httpRequest = HttpRequest.postInstanceOf(appCommon.getConfigByKey(AppConfigKeyEnums.WCS_RELEASE_BOX_URL.getKey()), request);
        HttpResponse httpResponse = httpClient.httpPost(httpRequest);
        if (httpResponse != null && httpResponse.isSuccess()) {
            return httpResponse.getData(BaseWcsApiResponse.class);
        }
        return BaseWcsApiResponse.error("请求未获得响应信息。");
    }

    /**
     * 取消拣选任务请求
     *
     * @param request 取消请求信息
     * @return 响应结果
     */
    @Override
    public WcsApiResponse<WcsPickTask> cancelPickTask(WcsPickTaskRequest request) {
        // 设置http请求
        HttpRequest httpRequest = HttpRequest.postInstanceOf(appCommon.getConfigByKey(AppConfigKeyEnums.WCS_CANCEL_PICK_TASK_URL.getKey()), request);
        HttpResponse httpResponse = httpClient.httpPost(httpRequest);
        if (httpResponse != null && httpResponse.isSuccess()) {
            WcsApiResponse<WcsPickTask> response = new WcsApiResponse<>();
            response = httpResponse.getData(response.getClass().asSubclass(WcsApiResponse.class));
            return response;
        }
        return WcsApiResponse.error("请求未获得响应信息。", null);
    }

    /**
     * 查询WCS系统是否可上料
     *
     * @param request 查询请求信息
     * @return 查询结果
     */
    @Override
    public WcsApiResponse<WcsCanFeedResponse> queryStandStatus(WcsQueryStandStatusRequest request) {
        HttpRequest httpRequest = HttpRequest.postInstanceOf(appCommon.getConfigByKey(AppConfigKeyEnums.WCS_QUERY_STAND_STATUS_URL.getKey()), request);
        HttpResponse httpResponse = httpClient.httpPost(httpRequest);

        // 1. 检查HTTP请求是否成功
        if (httpResponse == null) {
            return WcsApiResponse.error("请求WCS接口失败，未获得任何响应信息。", null);
        }
        if (!httpResponse.isSuccess()) {
            log.error("请求WCS站台状态接口失败，状态码：{}，响应体：{}", httpResponse.getResponseCode(), httpResponse.getResponseMessage());
            return WcsApiResponse.error("WCS系统请求失败: " + httpResponse.getResponseMessage(), null);
        }

        try {
            // 2. 第一步：先反序列化为原始类型（忽略泛型）
            WcsApiResponse<Object> rawResponse = httpResponse.getData(WcsApiResponse.class);

            // 3. 检查WCS业务逻辑是否成功
            if (rawResponse == null) {
                return WcsApiResponse.error("WCS响应体解析为空", null);
            }

            if (!Objects.equals(WcsApiResponseCodeEnums.SUCCESS.getCode(), rawResponse.getCode())) {
                // WCS业务逻辑失败
                log.error("WCS系统返回业务逻辑错误：{}", rawResponse.getMessage());
                return WcsApiResponse.error(rawResponse.getMessage(), null);
            }

            // 4. 第二步：手动转换data字段
            Object rawData = rawResponse.getData();
            WcsCanFeedResponse canFeedResponse = null;

            if (rawData != null) {
                // 使用FastJSON转换
                canFeedResponse = objectMapper.convertValue(rawData, WcsCanFeedResponse.class);
            }

            // 5. 构建最终响应
            WcsApiResponse<WcsCanFeedResponse> finalResponse = new WcsApiResponse<>();
            finalResponse.setCode(rawResponse.getCode());
            finalResponse.setMessage(rawResponse.getMessage());
            finalResponse.setData(canFeedResponse);

            return finalResponse;

        } catch (Exception e) {
            log.error("解析WCS响应时发生异常", e);
            return WcsApiResponse.error("解析WCS响应失败: " + e.getMessage(), null);
        }
        // WcsCanFeedResponse wcsCanFeedResponse = new WcsCanFeedResponse();
        // wcsCanFeedResponse.setResponseTime(LocalDateTime.now());
        // wcsCanFeedResponse.setMsg("success");
        // wcsCanFeedResponse.setAllowAction(true);
        // return WcsApiResponse.success("成功", wcsCanFeedResponse);
    }

    @Override
    public BaseWcsApiResponse agvDone() {
        HttpRequest httpRequest = HttpRequest.postInstanceOf(appCommon.getConfigByKey(AppConfigKeyEnums.WCS_AGV_DONE.getKey()), null);
        HttpResponse httpResponse = httpClient.httpPost(httpRequest);
        if (httpResponse != null && httpResponse.isSuccess()) {
            BaseWcsApiResponse response = new BaseWcsApiResponse();
            response = httpResponse.getData(response.getClass().asSubclass(BaseWcsApiResponse.class));
            return response;
        }
        return BaseWcsApiResponse.error("请求未获得响应信息。");
        // return WcsApiResponse.success("成功", true);
    }
}
