package com.gyee.wisdom.alarm.sharding.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gyee.wisdom.alarm.sharding.entity.*;
import com.gyee.wisdom.alarm.sharding.mapper.*;
import com.gyee.wisdom.alarm.sharding.util.SnowflakeGenerator;
import com.gyee.wisdom.common.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FaultStatisticWindturbineService extends ServiceImpl<FaultStatisticWindturbineMapper, FaultStatisticWindturbine> {


    @Autowired
    private FaultStatisticWindturbineMapper faultStatisticWindturbineMapper;

    @Autowired
    private AlarmSnapMapper alarmSnapMapper;
    @Autowired
    private AlarmHisotryMapper alarmHisotryMapper;
    @Autowired
    private WindPowerStationMapper windPowerStationMapper;
    @Autowired
    private AlarmCountMapper alarmCountMapper;
    @Autowired
    private TableNameService tableNameService;
    @Autowired
    private WindturbineMapper windturbineMapper;
    @Autowired
    private Warning2Mapper warning2Mapper;


    @Value("${count.fault}")
    public boolean fault;

    /**
     * @param
     * @return
     */
    public int SaveFaultStatisticWindturbine(List<FaultStatisticWindturbine> lists) {


        for (FaultStatisticWindturbine f : lists) {
            List<FaultStatisticWindturbine> orifs = faultStatisticWindturbineMapper.selectFaultStatisticWindturbineByyearandmonth(f.getYear(), f.getMonth(), f.getWarningtype(), f.getWindturbineid(),"");
            if (null != orifs && orifs.size() > 0) {
                FaultStatisticWindturbine orif = orifs.get(0);
                orif.setMonthwarningtime(orif.getMonthwarningtime() + f.getMonthwarningtime());
                orif.setMonthwarningnum(orif.getMonthwarningnum() + f.getMonthwarningnum());

                orif.setMonthonmonthtime(orif.getMonthonmonthtime() + f.getMonthonmonthtime());
                orif.setMonthonmonthnum(orif.getMonthonmonthnum() + f.getMonthonmonthnum());

                orif.setYearoveryeartime(orif.getYearoveryeartime() + f.getYearoveryeartime());
                orif.setYearoveryearnum(orif.getYearoveryearnum() + f.getYearoveryearnum());
                faultStatisticWindturbineMapper.updateById(orif);
            } else {
                faultStatisticWindturbineMapper.insert(f);
            }
        }
        return 0;

    }

    public String queryCount() throws Exception {

        if (!fault){
            return null;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = sdf.format(DateUtil.addDays(new Date(), -1));
        Date startTime = sdf.parse(strDate);
        Date endTime = DateUtil.addDays(startTime, 1);
        Calendar cale = null;
        cale = Calendar.getInstance();
        List<WindPowerStation> wps = windPowerStationMapper.getStationAll("FDC");
        List<FaultStatisticWindturbine> list = new ArrayList<>();
        for (int i = 1; i <= 3; i++) {
            if (2 == i) {
                cale = Calendar.getInstance();
                cale.add(Calendar.MONTH, -1);
                startTime = sdf.parse(sdf.format(DateUtil.addDays(cale.getTime(), -1)));
                endTime = DateUtil.addDays(startTime, 1);
            }
            if (3 == i) {
                cale = Calendar.getInstance();
                cale.add(Calendar.YEAR, -1);
                startTime = sdf.parse(sdf.format(DateUtil.addDays(cale.getTime(), -1)));
                endTime = DateUtil.addDays(startTime, 1);
            }
            for (WindPowerStation w : wps) {
                InitFwlist(w.getId());
                List<FaultStatisticWindturbine> arrlist = Fwlist(i, w.getId(), startTime, endTime);
                list.addAll(arrlist);
                SaveFaultStatisticWindturbine(arrlist);
            }

        }
        return list.size() + "";
    }


    //当月记录为0时执行
    private List<FaultStatisticWindturbine> InitFwlist(String stationId) {
        Calendar cale = null;
        cale = Calendar.getInstance();
        int year = cale.get(Calendar.YEAR);
        int month = cale.get(Calendar.MONTH) + 1;
        List<FaultStatisticWindturbine> orifs = faultStatisticWindturbineMapper.selectFaultStatisticWindturbineByyearandmonth(String.valueOf(year), String.valueOf(month), "", "",stationId);

        List<Windturbine> windturbineList = windturbineMapper.selectWindturbineByCondition(stationId,"");
        List<String > types  = warning2Mapper.selectGroupType();

        if(orifs.size()>=windturbineList.size()*types.size()){
            return null;
        }
        List<FaultStatisticWindturbine> list = new ArrayList<>();
        for (Windturbine w : windturbineList) {
            for (String s : types){
                FaultStatisticWindturbine fw = new FaultStatisticWindturbine();
                fw.setId(SnowflakeGenerator.generateId());
                fw.setYear(String.valueOf(year));
                fw.setMonth(String.valueOf(month));
                fw.setWarningtype(s);
                fw.setWindpowerstationid(w.getWindpowerstationid());
                fw.setWindturbineid(w.getId());
                fw.setMonthwarningnum(0);
                fw.setMonthwarningtime(0);
                fw.setMonthonmonthnum(0);
                fw.setMonthonmonthtime(0);
                fw.setYearoveryearnum(0);
                fw.setYearoveryeartime(0);
                list.add(fw);
            }
        }
        SaveFaultStatisticWindturbine(list);
        return list;
    }


    private List<FaultStatisticWindturbine> Fwlist(int datetype, String tableName, Date startTime, Date endTime) {
        Calendar cale = null;
        cale = Calendar.getInstance();
        int year = cale.get(Calendar.YEAR);
        int month = cale.get(Calendar.MONTH) + 1;
        List<FaultStatisticWindturbine> list = new ArrayList<>();
        String tbName = tableNameService.getAlarmHistoryTableName(tableName, startTime);
        List<FaultWarning> alarmSnaps = alarmHisotryMapper.selectHistoryAlarmSnapAndWarning(tbName, startTime, endTime);
        Map<String, List<FaultWarning>> FaultWarningGroupTypes = alarmSnaps.stream().collect(Collectors.groupingBy(FaultWarning::getWarningtypeid));
        for (Map.Entry<String, List<FaultWarning>> entry : FaultWarningGroupTypes.entrySet()) {
            Map<String, List<FaultWarning>> FaultWarningGroupWindturbine = entry.getValue().stream().collect(Collectors.groupingBy(FaultWarning::getWindturbineid));
            for (Map.Entry<String, List<FaultWarning>> windturbine : FaultWarningGroupWindturbine.entrySet()) {
                FaultStatisticWindturbine fw = new FaultStatisticWindturbine();
                fw.setId(SnowflakeGenerator.generateId());
                fw.setYear(String.valueOf(year));
                fw.setMonth(String.valueOf(month));
                fw.setWarningtype(entry.getKey());
                fw.setWindpowerstationid(tableName);
                fw.setWindturbineid(windturbine.getValue().get(0).getWindturbineid());
                List<String> snapid = windturbine.getValue().stream().map(FaultWarning::getSnapid).collect(Collectors.toList());
                snapid = snapid.stream().distinct().collect(Collectors.toList());
                Double minall = 0.0;
                for (int i = 0; i < snapid.size(); i++) {
                    List<AlarmHistory> alarmHistories = alarmCountMapper.selectAlarmHistoryBySnapid(tbName, Long.valueOf(snapid.get(i)), startTime, endTime);
                    boolean bool = true;
                    Date alertTimebegin = null;
                    Date alertTimeend = null;
                    for (AlarmHistory alarmHistory : alarmHistories) {
                        int messageType = alarmHistory.getMessageType();
                        if (!(messageType == 1 ^ bool)) {
                            if (bool) {
                                alertTimebegin = alarmHistory.getAlertTime();
                            }
                            if (!bool) {
                                alertTimeend = alarmHistory.getAlertTime();
                                Double min = Double.parseDouble((alertTimeend.getTime() - alertTimebegin.getTime()) + "") / 1000 / 60;
                                minall = minall + min;
                                bool = true;
                            } else {
                                bool = false;
                            }
                        }
                    }
                }
                DecimalFormat df = new DecimalFormat("0.000");

                if (1 == datetype) {

                    fw.setMonthwarningnum(windturbine.getValue().size());
                    fw.setMonthwarningtime(Double.parseDouble(df.format(minall + 1)));
                    fw.setMonthonmonthnum(0);
                    fw.setMonthonmonthtime(0);
                    fw.setYearoveryearnum(0);
                    fw.setYearoveryeartime(0);
                }
                if (2 == datetype) {

                    fw.setMonthwarningnum(0);
                    fw.setMonthwarningtime(0);
                    fw.setMonthonmonthnum(windturbine.getValue().size());
                    fw.setMonthonmonthtime(Double.parseDouble(df.format(minall + 1)));
                    fw.setYearoveryearnum(0);
                    fw.setYearoveryeartime(0);
                }
                if (3 == datetype) {

                    fw.setMonthwarningnum(0);
                    fw.setMonthwarningtime(0);
                    fw.setMonthonmonthnum(0);
                    fw.setMonthonmonthtime(0);
                    fw.setYearoveryearnum(windturbine.getValue().size());
                    fw.setYearoveryeartime(Double.parseDouble(df.format(minall + 1)));
                }

                list.add(fw);

            }
        }

        return list;
    }
}
