package com.wms_main.service.controller.serviceImpl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wms_main.app.AppCommon;
import com.wms_main.constant.enums.wms.AppConfigKeyEnums;
import com.wms_main.constant.enums.wms.WmsStackerTaskStatusEnums;
import com.wms_main.constant.enums.wms.WmsTaskTypeEnums;
import com.wms_main.dao.ITAppStockService;
import com.wms_main.dao.ITAppTaskService;
import com.wms_main.model.bo.mes.MesDetailGoodsInfo;
import com.wms_main.model.bo.mes.MesDetailTaskInfo;
import com.wms_main.model.bo.wcs.WcsPickTask;
import com.wms_main.model.dto.request.mes.MesInTaskRequest;
import com.wms_main.model.dto.request.mes.MesOutTaskRequest;
import com.wms_main.model.dto.response.mes.MesGetGoodsResponse;
import com.wms_main.model.dto.response.wcs.WcsApiResponse;
import com.wms_main.model.dto.response.wms.BaseWmsApiResponse;
import com.wms_main.model.po.TAppLocation;
import com.wms_main.model.po.TAppTask;
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.repository.utils.StringUtils;
import com.wms_main.repository.utils.UUIDUtils;
import com.wms_main.service.business.IStackerTaskService;
import com.wms_main.service.controller.IMesControllerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * Mes控制类服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MesControllerServiceImpl implements IMesControllerService {
    private final ITAppTaskService appTaskService;// wms任务服务
    private final ITAppStockService appStockService;// wms库存服务
    private final IStackerTaskService stackerTaskService;// 堆垛机任务服务
    private final Map<String, Integer> mesTaskIdMap = new HashMap<>();// 防止mes发送重复任务号
    private final AppCommon appCommon;
    private final HttpClient httpClient;

    /**
     * Mes请求入库--实现
     * @param mesInTaskRequest 入库请求
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse requestIn(MesInTaskRequest mesInTaskRequest) {
        // 判断请求参数是否齐全
        if (mesTaskIdMap.containsKey(mesInTaskRequest.getTaskId())) {
            return BaseWmsApiResponse.error("任务号重复。");
        }
        // 添加任务号进缓存
        mesTaskIdMap.put(mesInTaskRequest.getTaskId(), 1);
        // 验证请求
        String validateInfo = validateMesInRequest(mesInTaskRequest);
        if (StringUtils.isNotEmpty(validateInfo)) {
            // 请求处理结束，删除任务号缓存
            mesTaskIdMap.remove(mesInTaskRequest.getTaskId());
            return BaseWmsApiResponse.error(validateInfo);
        }
        // 请求一个空库位
        TAppLocation targetLocation = stackerTaskService.requestOneLocation(null, mesInTaskRequest.getVehicleId());
        if (targetLocation == null) {
            // 请求处理结束，删除任务号缓存
            mesTaskIdMap.remove(mesInTaskRequest.getTaskId());
            return BaseWmsApiResponse.error("可用库位不足，请稍后重试。");
        }
        // 生成入库任务
        List<TAppTask> inTasks = new ArrayList<>();
        for (MesDetailTaskInfo mesDetailTaskInfo : mesInTaskRequest.getDetailTaskInfoList()) {
            inTasks.add(new TAppTask(
                    UUIDUtils.getNewUUID(),
                    WmsTaskTypeEnums.IN.getCode(),
                    WmsStackerTaskStatusEnums.WAIT.getCode(),
                    1,
                    mesInTaskRequest.getVehicleId(),
                    mesInTaskRequest.getStandId(),
                    targetLocation.getLocationId(),
                    null,
                    LocalDateTime.now(),
                    null,
                    mesDetailTaskInfo.getGoodsId(),
                    mesDetailTaskInfo.getQuantity(),
                    0.0,
                    "mes",
                    "",
                    mesInTaskRequest.getStandId(),
                    "",
                    mesDetailTaskInfo.getBarCode(),
                    mesInTaskRequest.getTaskId(),
                    "",
                    ""
            ));
        }
        // 保存任务
        appTaskService.saveBatch(inTasks);
        // 请求处理结束，删除任务号缓存
        mesTaskIdMap.remove(mesInTaskRequest.getTaskId());
        return BaseWmsApiResponse.success("请求入库成功。");
    }

    /**
     * Mes请求出库--实现
     * @param mesOutTaskRequest 出库请求
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse requestOut(MesOutTaskRequest mesOutTaskRequest) {
        // 验证出库请求
        // 生成出库任务
        List<TAppTask> outTasks = new ArrayList<>();
        for (MesDetailTaskInfo mesDetailTaskInfo : mesOutTaskRequest.getDetailTaskInfoList()) {
            outTasks.add(new TAppTask(
                    UUIDUtils.getNewUUID(),
                    WmsTaskTypeEnums.OUT.getCode(),
                    WmsStackerTaskStatusEnums.WAIT.getCode(),
                    1,
                    "test01",
                    "A01-01-01-01",
                    "",
                    null,
                    LocalDateTime.now(),
                    null,
                    mesDetailTaskInfo.getGoodsId(),
                    mesDetailTaskInfo.getQuantity(),
                    0.0,
                    "mes",
                    "",
                    mesOutTaskRequest.getStandId(),
                    "",
                    mesDetailTaskInfo.getBarCode(),
                    mesOutTaskRequest.getTaskId(),
                    "",
                    ""
            ));
        }
        appTaskService.saveBatch(outTasks);
        return BaseWmsApiResponse.success("请求出库成功。");
    }

    /**
     * 验证入库请求正确性
     * @param mesInTaskRequest 入库请求
     * @return 验证结果
     */
    private String validateMesInRequest(MesInTaskRequest mesInTaskRequest) {
        if (StringUtils.isEmpty(mesInTaskRequest.getTaskId())) {
            return "任务号/订单号为空";
        }
        // 判断任务号是否重复
        if (appTaskService.exists(new LambdaQueryWrapper<TAppTask>().eq(TAppTask::getMesId, mesInTaskRequest.getTaskId()))) {
            return "任务号/订单号重复";
        }

        return "";
    }

    /**
     * 根据条码号获取物料信息
     * @param barCode 条码号
     * @return 物料信息
     */
    private MesDetailGoodsInfo getGoodsByBarCode(String barCode) {
        String mesDetailQueryUrl = appCommon.getConfigByKey(AppConfigKeyEnums.MES_GET_GOODS_URL.getKey());
        if (StringUtils.isNotEmpty(mesDetailQueryUrl)) {
            Map<String, String> header = new HashMap<>();
            header.put("X-Requested-With", "XMLHttpRequest");
            // 设置http请求
            HttpRequest httpRequest = HttpRequest.getInstanceOf(mesDetailQueryUrl + "?scCode=" + barCode, 5000, header);
            HttpResponse httpResponse = httpClient.httpGet(httpRequest);
            log.info("请求物料接口响应信息：{}", StringUtils.objectToString(httpResponse));
            if (httpResponse != null && httpResponse.isSuccess()) {
                MesGetGoodsResponse goodsInfoResponse = httpResponse.getData(MesGetGoodsResponse.class);
                if (goodsInfoResponse != null && Objects.equals(goodsInfoResponse.getState(), "success")) {
                    return goodsInfoResponse.getData();
                }
            }
        } else {
            log.error("请求地址为空。");
        }
        return null;
    }
}
