package com.pqs9000.serviceimpl.report;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.njcn.utils.PubUtils;
import com.pqs9000.mapper.report.GetInegDataMapper;
import com.pqs9000.pojo.report.Condition;
import com.pqs9000.pojo.report.IntegrityDetailVo;
import com.pqs9000.pojo.report.ReportValue;
import com.pqs9000.service.report.GetInegDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class GetInegDataServiceImpl implements GetInegDataService {
    private static final Logger logger = LoggerFactory.getLogger(GetInegDataServiceImpl.class);

    @Autowired
    private GetInegDataMapper getInegDataMapper;

    private void transformData( List<ReportValue> list, List<Map<String, Object>> listMap) {
        for (Map<String, Object> map : listMap) {
            ReportValue uValue = new ReportValue();
            setData(uValue, list, map);
        }
    }

    private void setData( ReportValue reportValue, List<ReportValue> list, Map<String, Object> map) {
        reportValue.setPhaseType(map.get("PHASETYPE").toString());
        try {
            reportValue.setStrTime(PubUtils.date2String((Date) map.get("TIMEID"), "yyyy-MM-dd"));
        } catch (Exception e) {

        }
        reportValue.setMeanValue(Float.parseFloat(map.get("I_NEG").toString()));
        reportValue.setFmaxValue(Float.parseFloat(map.get("I_NEG_MAX").toString()));
        reportValue.setMinValue(Float.parseFloat(map.get("I_NEG_MIN").toString()));

        if (map.containsKey("I_NEG_CP95")) {
            reportValue.setCp95Value(Float.parseFloat(map.get("I_NEG_CP95").toString()));
        } else {
            reportValue.setCp95Value(null);
        }

        list.add(reportValue);
    }

    @Override
    public List<ReportValue> getInegData(Condition condition) {
        List<ReportValue> list = new ArrayList<>();
        List<ReportValue> listIneg = new ArrayList<>();

        //获取电压偏差
        List<Map<String, Object>> lists = getInegDataMapper.getInegData(condition);

        if (0 < lists.size() && null != lists.get(0)) {
            transformData(listIneg, lists);
        }

        RegroupData.regroupData(listIneg, true);
        list.addAll(listIneg);

        return list;
    }

    @Override
    public List<IntegrityDetailVo> getDetail(String lineId, String startTime, String endTime, String timeType) {
        List<IntegrityDetailVo> result = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (Objects.equals(timeType, "年份") || Objects.equals(timeType, "季度")){
            List<String> dateList = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            try {
                Date d1 = new SimpleDateFormat("yyyy-MM").parse(startTime);
                Date d2 = new SimpleDateFormat("yyyy-MM").parse(endTime);
                Calendar dd = Calendar.getInstance();
                dd.setTime(d1);
                while (dd.getTime().before(d2)) {
                    String str = sdf.format(dd.getTime());
                    dateList.add(str);
                    dd.add(Calendar.MONTH, 1);
                }
                dateList.add(sdf.format(d2));
                dateList.forEach(item->{
                    try {
                        String time1 = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN).format(DateUtil.beginOfMonth(sdf.parse(item)));
                        String time2 = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN).format(DateUtil.endOfMonth(sdf.parse(item)));
                        IntegrityDetailVo vo = getInegDataMapper.getDataByMonth(item,lineId,time1,time2);
                        result.add(vo);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                });
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else if (Objects.equals(timeType, "月份") || Objects.equals(timeType, "周")){
            List<String> dateList = new ArrayList<>();
            try {
                Date d1 = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
                Date d2 = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
                Calendar dd = Calendar.getInstance();
                dd.setTime(d1);
                while (dd.getTime().before(d2)) {
                    String str = simpleDateFormat.format(dd.getTime());
                    dateList.add(str);
                    dd.add(Calendar.DATE, 1);
                }
                dateList.add(simpleDateFormat.format(d2));
                dateList.forEach(item->{
                    try {
                        String time1 = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN).format(DateUtil.beginOfDay(simpleDateFormat.parse(item)));
                        String time2 = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN).format(DateUtil.endOfDay(simpleDateFormat.parse(item)));
                        IntegrityDetailVo vo = getInegDataMapper.getDataByMonth(item,lineId,time1,time2);
                        result.add(vo);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                });
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else if (Objects.equals(timeType, "天") ) {
            try {
                String time1 = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN).format(DateUtil.beginOfDay(simpleDateFormat.parse(startTime)));
                String time2 = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN).format(DateUtil.endOfDay(simpleDateFormat.parse(startTime)));
                List<String> timeList = getHourListRange(time1, time2);
                for (int i = 0; i< Objects.requireNonNull(timeList).size(); i++) {
                    if (i != timeList.size() - 1) {
                        IntegrityDetailVo vo = getInegDataMapper.getDataByDay(timeList.get(i),lineId,timeList.get(i),timeList.get(i+1));
                        result.add(vo);
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (CollUtil.isNotEmpty(result)){
            result.removeIf(Objects::isNull);
        }
        return result;
    }

    /**
     * 据指定时间片段，返回时间片段内的所有小时
     * @param startStr
     * @param endStr
     * @return
     */
    public static List<String> getHourListRange(String startStr , String endStr){
        try{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<String > list = new ArrayList<>();
            Calendar c = Calendar.getInstance();
            c.setTime(format.parse(startStr));
            Calendar ec = Calendar.getInstance();
            ec.setTime(format.parse(endStr));
            while (true){
                if(ec.before(c)){
                    list.add(format.format(c.getTime()));
                    break;
                }
                list.add(format.format(c.getTime()));
                c.add(Calendar.HOUR_OF_DAY,1);
            }
            return list ;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return null ;
    }

}
