package com.clx.performance.service.impl.linewarn;

import com.clx.performance.dao.linewarn.LineWarnConfigDao;
import com.clx.performance.dao.linewarn.LineWarnInfoDao;
import com.clx.performance.dto.linewarn.LineWarnCommonInfoDTO;
import com.clx.performance.enums.linewarn.LineWarnConfigEnum;
import com.clx.performance.enums.linewarn.LineWarnInfoEnum;
import com.clx.performance.extranal.order.InternalReportService;
import com.clx.performance.model.OrderGoods;
import com.clx.performance.model.linewarn.LineWarnConfig;
import com.clx.performance.model.linewarn.LineWarnInfo;
import com.clx.performance.service.linewarn.LineWarnCommonService;
import com.clx.performance.service.linewarn.LineWarnCongestionWarnService;
import com.clx.performance.utils.LocalDateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class LineWarnCongestionWarnServiceImpl implements LineWarnCongestionWarnService {
    // 默认监控时间
    private static final int DEFAULT_TIME = 5;
    @Autowired
    private LineWarnConfigDao lineWarnConfigDao;

    @Autowired
    private InternalReportService internalReportService;
    @Autowired
    private LineWarnCommonService lineWarnCommonService;
    @Autowired
    private LineWarnInfoDao lineWarnInfoDao;

    @Override
    public void congestionWarn(OrderGoods orderGoods, LineWarnCommonInfoDTO lineWarnCommonInfo) {
        LocalDateTime beginTime = LocalDateTime.now().minusMinutes(DEFAULT_TIME);

        List<LineWarnConfig> lineWarnConfigList = lineWarnConfigDao
                .listByWarnType(LineWarnConfigEnum.WarnType.CONGESTION.getCode());
        if (lineWarnConfigList.isEmpty()) {return;}

        for (LineWarnConfig item : lineWarnConfigList) {
            doCongestionWarn(orderGoods, item, beginTime);
        }

    }

    private void doCongestionWarn(OrderGoods orderGoods, LineWarnConfig lineWarnConfig, LocalDateTime beginTime){
        LineWarnInfo lineWarnInfo = lineWarnInfoDao
                .findByOrderGoodsNoAndWarnConfigId(orderGoods.getOrderGoodsNo(), lineWarnConfig.getId()).orNull();
        if (lineWarnInfo != null
                && Objects.equals(lineWarnInfo.getStatus(), LineWarnInfoEnum.Status.RESOLVE.getCode())){
            return;
        }

        // 检测是否拥堵
        Boolean flag = internalReportService.checkLineJam(orderGoods.getSendSystemAddressId(),
                orderGoods.getReceiveSystemAddressId(),
                LocalDateTimeUtils.formatTime(beginTime), lineWarnConfig.getCongestionTime());
        if (!flag) {return;}

        // 更新
        lineWarnCommonService.lineWarnInfoUpdate(orderGoods, lineWarnInfo, lineWarnConfig);

    }
}
