package com.wms_main.service.quartz_job.job_executor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wms_main.constant.enums.wms.OrderStatusEnum;
import com.wms_main.constant.enums.wms.WmsApiResponseCodeEnums;
import com.wms_main.dao.ITAppOrderInService;
import com.wms_main.dao.ITAppWcsTaskService;
import com.wms_main.model.bo.erp.ErpGoodsDetail;
import com.wms_main.model.bo.erp.ErpVehicleNoResp;
import com.wms_main.model.dto.response.ycwms.YcwmsResponse;
import com.wms_main.model.po.TAppOrderIn;
import com.wms_main.model.po.TAppWcsTask;
import com.wms_main.repository.utils.StringUtils;
import com.wms_main.service.api.IExternalApiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@PersistJobDataAfterExecution
// 以下注解用于实现fixed_delay
@DisallowConcurrentExecution
@RequiredArgsConstructor
public class OrderInCheckor {
    private final ITAppOrderInService orderInService;
    private final ITAppWcsTaskService wcsTaskService;
    private final IExternalApiService externalApiService;

    public void execute(JobExecutionContext jobExecutionContext) {
        List<TAppOrderIn> inOrdersToCheck = orderInService.list(
                new LambdaQueryWrapper<TAppOrderIn>()
                        .eq(TAppOrderIn::getOrderStatus, OrderStatusEnum.CREATE.getCode()));
        // 根据载具号map一下
        Map<String, List<TAppOrderIn>> vehicleIdToTaskMap = inOrdersToCheck.stream()
                .filter(orderIn -> Objects.equals(orderIn.getOrderStatus(), OrderStatusEnum.CREATE.getCode()))
                .filter(orderIn -> !(orderIn.getGoodsId().equals("0")))
                .collect(Collectors.groupingBy(TAppOrderIn::getVehicleNo));
        for (String vehicleNo : vehicleIdToTaskMap.keySet()) {
            ErpGoodsDetail goods = new ErpGoodsDetail();
            goods.setGoodsId("test");
            goods.setGoodsName("test");
            goods.setGoodsType("test");
            List<ErpGoodsDetail> goodsDetails = new ArrayList<>();
            goodsDetails.add(goods);
            try {
                YcwmsResponse<ErpVehicleNoResp> erpResp = externalApiService.getVehicleNoData(vehicleNo);
                if (erpResp != null && WmsApiResponseCodeEnums.SUCCESS.getCode() == erpResp.getCode() && !erpResp.getReturnData().getGoodsDetail().isEmpty()) {
                    goodsDetails = erpResp.getReturnData().getGoodsDetail();
                } else {
                    log.warn("获取载具[{}]数据失败，响应：{}", vehicleNo, erpResp);
                }
            } catch (Exception e) {
                log.error("处理载具[{}]数据时发生异常：", vehicleNo, e);
            }
            List<TAppOrderIn> inTasks = vehicleIdToTaskMap.get(vehicleNo);
            if (inTasks.stream().anyMatch(task -> StringUtils.isEmpty(task.getClientId()))) {
                continue;
            }

            // 对比inTasks和goodsDetails
            Iterator<ErpGoodsDetail> iterator = goodsDetails.iterator();
            while (iterator.hasNext()) {
                ErpGoodsDetail goodsDetail = iterator.next();
                boolean matchFound = inTasks.stream().anyMatch(task ->
                                task.getGoodsId().equals(goodsDetail.getGoodsId()) &&
                                task.getGoodsBarcode().equals(goodsDetail.getGoodsBarcode()) &&
                                Objects.equals(task.getQuantity(), goodsDetail.getQuantity()) &&
                                task.getGoodsType().equals(goodsDetail.getGoodsType()) &&
                                Objects.equals(task.getSpecification(), goodsDetail.getSpecification())
                );
                if (matchFound) {
                    // 找到匹配的任务，删除该 goodsDetail
                    iterator.remove();
                }
            }
            if (!goodsDetails.isEmpty()) {
                orderInService.remove(new LambdaUpdateWrapper<TAppOrderIn>()
                        .eq(TAppOrderIn::getVehicleNo, vehicleNo));
                wcsTaskService.remove(new LambdaUpdateWrapper<TAppWcsTask>()
                        .eq(TAppWcsTask::getVehicleId, vehicleNo));
            } else {
                log.info("MES校验入库单成功, 载具[{}]", vehicleNo);
            }
        }
    }
}
