package com.cpp.web.service.accuracy;

import com.cpp.system.service.ISysConfigService;
import com.cpp.web.domain.accuracy.AccuracyPassRate;
import com.cpp.web.domain.station.ElectricField;
import com.cpp.web.domain.station.PowerStationStatusData;
import com.cpp.web.service.station.*;
import com.cpp.web.utils.DateTimeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@RequiredArgsConstructor
public class CalcAccuracy {

    public final AccuracyPassRateService accuracyPassRateService;
    private final ElectricFieldService electricFieldService;
    private final ISysConfigService sysConfigService;
    private final PowerStationStatusDataService powerStationStatusDataService;
    private final List<CalculateInterface> calculateInterfaces;

    /**
     * 执行准确率计算
     */
    public void calculate() {
        Long day = 86400000L;
        Long now = System.currentTimeMillis();

        Date startTime = DateTimeUtil.getDayStartTime(now - day);
        Date endTime = DateTimeUtil.getDayLastTime(now - day);
        List<ElectricField> electricFieldList = electricFieldService.list();
        List<AccuracyPassRate> accuracyPassRateList = new ArrayList<>();
        String province = sysConfigService.selectConfigByKey("province");
        if (province.equals("")) province = "E65";
        if (!electricFieldList.isEmpty()) {
            List<PowerStationStatusData> powerStationStatusDataList = powerStationStatusDataService.findByTimeBetween(startTime, endTime);
            if (!powerStationStatusDataList.isEmpty()) {
                List<String> formulaTypes = Arrays.asList("DAY_SHORT_ACCURACY", "POINT_SHORT_ACCURACY", "POINT_ULTRA_SHORT_ACCURACY");
                for (CalculateInterface calculateInterface : calculateInterfaces) {
                    if (listHasIntersection(calculateInterface.calculationTypes(), formulaTypes)) {
                        accuracyPassRateList.addAll(calculateInterface.calc(startTime, endTime, powerStationStatusDataList, electricFieldList, formulaTypes, province));
                    }
                }
            }
        }
        if (accuracyPassRateList.size() > 0) {
            accuracyPassRateService.saveBatch(accuracyPassRateList);
        }
    }


    /**
     * 集合交集判断（此方法还需优化写法）
     *
     * @param strings
     * @param stringList
     * @return
     */
    public Boolean listHasIntersection(List<String> strings, List<String> stringList) {
        for (String string : strings) {
            for (String s : stringList) {
                if (string.equals(s)) {
                    return true;
                }
            }
        }
        return false;
    }
}
