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.LineWarnLineWarnService;
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 LineWarnLineWarnServiceImpl implements LineWarnLineWarnService {
    // 默认监控时间
    private static final int DEFAULT_TIME = 5;
    @Autowired
    private LineWarnConfigDao lineWarnConfigDao;
    @Autowired
    private LineWarnInfoDao lineWarnInfoDao;
    @Autowired
    private InternalReportService internalReportService;
    @Autowired
    private LineWarnCommonService lineWarnCommonService;

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

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

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

    private void doLineAbnormalWarn(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.checkLineAbnormal(orderGoods.getSendSystemAddressId(),
                orderGoods.getReceiveSystemAddressId(),
                LocalDateTimeUtils.formatTime(beginTime));
        if (!flag) {return;}

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

    }

}
