package com.jiayue.ipfcst.console.service;

import com.jiayue.ipfcst.common.data.entity.PowerPlanSD;
import com.jiayue.ipfcst.common.data.repository.PowerPlanSDRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 检修计划业务层
 *
 * @author Tangle
 * @version 1.0
 * @since 2020/03/27 10:02
 */
@Service
@Slf4j
public class PowerPlanSDService {
    private final PowerPlanSDRepository PowerPlanSDRepository;
    @Autowired
    public PowerPlanSDService(PowerPlanSDRepository PowerPlanSDRepository){
        this.PowerPlanSDRepository = PowerPlanSDRepository;
    }

    public void deleteByPlanTime(Long startTime, Long endTime) {
        PowerPlanSDRepository.deleteByPlanTimeBetween(startTime,endTime);
    }

    public void saveAll(List<PowerPlanSD> powerPlanList) {
        PowerPlanSDRepository.saveAll(powerPlanList);
    }

    public List<PowerPlanSD> getPowerPlan(String startTimeStr, String endTimeStr) {
        List<PowerPlanSD> list = PowerPlanSDRepository.findByPlanTimeBetween(Long.parseLong(startTimeStr),Long.parseLong(endTimeStr));
        Collections.sort(list, Comparator.comparing(PowerPlanSD::getPlanTime));
        return list;
    }

    public List<PowerPlanSD> getPowerPlanDrawing(String startTimeStr, String endTimeStr) {
        Map<String, Object> map = new HashMap<>();
        Long startTime = 0L;
        Long endTime = 0L;
        startTime = Long.parseLong(startTimeStr);
        endTime = Long.parseLong(endTimeStr) + 1000 * 60 * 60 * 24-1000;
        List<PowerPlanSD> powerPlanList = PowerPlanSDRepository.findByPlanTimeBetween(startTime, endTime);
        List<PowerPlanSD> resultList = new ArrayList<>();

        // 如果时间点缺数需要补空
        boolean bo = false;
        for (long tempDateTime = startTime; tempDateTime <= endTime; tempDateTime = tempDateTime + 15 * 60 * 1000) {
            for (PowerPlanSD powerPlan : powerPlanList) {
                bo = tempDateTime == powerPlan.getPlanTime().longValue();
                if (bo) {
                    resultList.add(powerPlan);
                    break;
                }
            }

            if (!bo) {
                // 时间点缺数需要补空
                PowerPlanSD powerPlan = new PowerPlanSD();
                powerPlan.setPlanTime(tempDateTime);
                resultList.add(powerPlan);
            }
        }
        return resultList;
    }
}
