package test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gyee.SpringbootStart;
import com.gyee.frame.common.domain.AjaxResult;
import com.gyee.frame.common.feign.RemoteServiceBuilder;
import com.gyee.frame.mapper.auto.AlarmsnapMapper;
import com.gyee.frame.mapper.auto.WindTurbineTestingPointAi2Mapper;
import com.gyee.frame.model.auto.FaultInfo;
import com.gyee.frame.model.auto.WindTurbineTestingPointAi2;
import com.gyee.frame.model.auto.WindTurbineTestingPointAi2Example;
import com.gyee.frame.model.config.FilePathConfig;
import com.gyee.frame.model.custom.export.TsPointData;
import com.gyee.frame.model.excel.Woworktickeask;
import com.gyee.frame.service.export.WorkticketService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 每个月各场站每台风机有多少次故障（故障时间持续超过2小时），停机时间。停机损失多少电量
 */
@SpringBootTest(classes = SpringbootStart.class)
@RunWith(SpringRunner.class)
public class LosePowerTest {

    @Resource
    private WindTurbineTestingPointAi2Mapper windTurbineTestingPointAi2Mapper;@Resource
    private AlarmsnapMapper alarmsnapMapper;
    @Resource
    private RemoteServiceBuilder remoteServiceBuilder;

    private List<WindTurbineTestingPointAi2> faultCodes;
    private Map<String, String> llfdlMap;
    private Map<String, String> fcMap;


    @Resource
    private WorkticketService workticketService;
    private final String REGEX = "\\d+";

    @Test()
    public void test() throws ParseException {
        getFaultCodes();
        getLlfdlMap();
        Date start = DateUtils.parseDate("2022-10-01", "yyyy-MM-dd");
        Date end = DateUtils.parseDate("2022-10-31", "yyyy-MM-dd");
        calc3(start, end);

    }

    private void calc3(Date start, Date end) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();

        XSSFRow row0 = sheet.createRow(0);
        row0.createCell(0).setCellValue("序号");
        row0.createCell(1).setCellValue("场站");
        row0.createCell(2).setCellValue("风机");
        row0.createCell(3).setCellValue("故障开始时间");
        row0.createCell(4).setCellValue("故障结束时间");
        row0.createCell(5).setCellValue("故障次数");
        row0.createCell(6).setCellValue("故障时间(分钟)");
        row0.createCell(7).setCellValue("损失电量(kWh)");
        row0.createCell(8).setCellValue("机型");
        row0.createCell(9).setCellValue("当时故障");

        int i = 1;
        for (WindTurbineTestingPointAi2 wttpai2 : faultCodes) {

            XSSFRow rowz = sheet.createRow(i);

            List<TsPointData> historyRaw = remoteServiceBuilder.ShardingService().getHistoryRaw(wttpai2.getId(), start.getTime(), end.getTime());
            //时间从小到大
            historyRaw = historyRaw.stream().sorted(Comparator.comparing(TsPointData::getTs)).collect(Collectors.toList());

            long duration = 0;//故障时间
            long durationlj = 0;//停机时间
            double ssdl = 0;//损失电量
            long faultTime = historyRaw.get(0).getTs();
            short gzcs = 0;//故障次数

            short k = 0;//是否连续故障，如果点是连续的2，故障次数算1次

            short 当前风机是否有故障 = 0;
            //测点列表
            for (TsPointData tsPointData : historyRaw) {
                //点值
                int doubleValue = (int) tsPointData.getDoubleValue();
                if (doubleValue == 4) {
                    continue;
                } else if (doubleValue == 2) {
                    if(k==0){
                        faultTime = tsPointData.getTs();
                        k = 1;
                    }else {
                        continue;
                    }
                } else {
                    if(k==1){
                        long ts = tsPointData.getTs();
                        duration = faultTime - ts;
                        //超过2小时,毫秒
                        int 两小时 = 2 * 60 * 60 * 1000;
                        int 一小时 = 1 * 60 * 60 * 1000;
                        int 半小时 = 1 * 30 * 60 * 1000;
                        if (duration > 一小时) {
                            当前风机是否有故障 = 1;
                            gzcs++;
                            //一个故障一行excel
                            XSSFRow row = sheet.createRow(i);
                            i++;

                            durationlj += duration;
                            String s = llfdlMap.get(wttpai2.getWindturbineid());
                            Map<String, TsPointData> h1 = remoteServiceBuilder.ShardingService().getHistorySection(s, ts);
                            Map<String, TsPointData> h2 = remoteServiceBuilder.ShardingService().getHistorySection(s, faultTime);
                            double doubleValue2 = h2.get(s).getDoubleValue();
                            double doubleValue1 = h1.get(s).getDoubleValue();
                            ssdl = doubleValue2 - doubleValue1;

                            row.createCell(0).setCellValue(i - 1);
                            row.createCell(1).setCellValue(wttpai2.getWindpowerstationid());
                            row.createCell(2).setCellValue(wttpai2.getWindturbineid());
                            row.createCell(3).setCellValue(DateFormatUtils.format(ts, "yyyy-MM-dd HH:mm:ss"));
                            row.createCell(4).setCellValue(DateFormatUtils.format(faultTime, "yyyy-MM-dd HH:mm:ss"));
                            row.createCell(5).setCellValue(1);
                            row.createCell(6).setCellValue(duration / 60000);
                            row.createCell(7).setCellValue(ssdl);
                            row.createCell(8).setCellValue(wttpai2.getModelid());

                            List<FaultInfo> recentFault = alarmsnapMapper.getRecentFault(wttpai2.getWindturbineid(), new Date(ts-1*60*60*1000), new Date(ts), 4);
                            if(recentFault.size()==0){
                                recentFault = alarmsnapMapper.getRecentFault(wttpai2.getWindturbineid(), new Date(ts-8*60*60*1000), new Date(ts), 2);
                            }
                            String dsgz = "";
                            for (FaultInfo faultInfo : recentFault) {
                                dsgz = dsgz + DateFormatUtils.format(faultInfo.getFaultTime(), "yyyy-MM-dd HH:mm:ss") + ":" + faultInfo.getAlertText() + "\n";
                            }
                            row.createCell(9).setCellValue(dsgz);
                        }
                        k = 0;
                    }else {
                        continue;
                    }

                }
            }

            if (当前风机是否有故障 == 0) {
                rowz.createCell(0).setCellValue(i - 1);
                rowz.createCell(1).setCellValue(wttpai2.getWindpowerstationid());
                rowz.createCell(2).setCellValue(wttpai2.getWindturbineid());
                rowz.createCell(3).setCellValue(DateFormatUtils.format(faultTime, "yyyy-MM"));
                rowz.createCell(4).setCellValue(DateFormatUtils.format(faultTime, "yyyy-MM"));
                rowz.createCell(5).setCellValue(gzcs);
                rowz.createCell(6).setCellValue(durationlj / 60000);
                rowz.createCell(7).setCellValue(ssdl);
                rowz.createCell(8).setCellValue(wttpai2.getModelid());
                i++;
            }

        }
        //通过输出流将workbook对象下载到磁盘
        FileOutputStream out = null;
        try {
            out = new FileOutputStream("D:\\计算\\风电场202210-1小时.xlsx");
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //每行是一个故障
    private void calc2(Date start, Date end) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();

        XSSFRow row0 = sheet.createRow(0);
        row0.createCell(0).setCellValue("序号");
        row0.createCell(1).setCellValue("场站");
        row0.createCell(2).setCellValue("风机");
        row0.createCell(3).setCellValue("故障开始时间");
        row0.createCell(4).setCellValue("故障结束时间");
        row0.createCell(5).setCellValue("故障次数");
        row0.createCell(6).setCellValue("故障时间(分钟)");
        row0.createCell(7).setCellValue("损失电量(kWh)");
        row0.createCell(8).setCellValue("机型");

        int i = 1;
        for (WindTurbineTestingPointAi2 wttpai2 : faultCodes) {

            XSSFRow rowz = sheet.createRow(i);

            List<TsPointData> historyRaw = remoteServiceBuilder.ShardingService().getHistoryRaw(wttpai2.getId(), start.getTime(), end.getTime());
            //时间从大到小
            historyRaw = historyRaw.stream().sorted(Comparator.comparing(TsPointData::getTs).reversed()).collect(Collectors.toList());

            long duration = 0;//故障时间
            long durationlj = 0;//停机时间
            double ssdl = 0;//损失电量
            long faultTime = historyRaw.get(0).getTs();
            short gzcs = 0;//故障次数

            short k = 0;//是否连续，如果点是连续的2，故障次数算1次

            short 当前风机是否有故障 = 0;
            //测点列表
            for (TsPointData tsPointData : historyRaw) {
                //点值
                int doubleValue = (int) tsPointData.getDoubleValue();
                if (doubleValue == 4) {
                    k = 0;
                    continue;
                } else if (doubleValue == 2) {
                    long ts = tsPointData.getTs();
                    duration = faultTime - ts;
                    //超过2小时,毫秒
                    int 两小时 = 2 * 60 * 60 * 1000;
                    int 一小时 = 1 * 60 * 60 * 1000;
                    int 半小时 = 1 * 30 * 60 * 1000;
                    if (duration > 一小时) {
                        当前风机是否有故障 = 1;
                        if (k == 0) gzcs++;
                        k = 1;
                        //一个故障一行excel
                        XSSFRow row = sheet.createRow(i);
                        i++;

                        durationlj += duration;
                        String s = llfdlMap.get(wttpai2.getWindturbineid());
                        Map<String, TsPointData> h1 = remoteServiceBuilder.ShardingService().getHistorySection(s, ts);
                        Map<String, TsPointData> h2 = remoteServiceBuilder.ShardingService().getHistorySection(s, faultTime);
                        double doubleValue2 = h2.get(s).getDoubleValue();
                        double doubleValue1 = h1.get(s).getDoubleValue();
                        ssdl = doubleValue2 - doubleValue1;

                        row.createCell(0).setCellValue(i - 1);
                        row.createCell(1).setCellValue(wttpai2.getWindpowerstationid());
                        row.createCell(2).setCellValue(wttpai2.getWindturbineid());
                        row.createCell(3).setCellValue(DateFormatUtils.format(ts, "yyyy-MM-dd HH:mm:ss"));
                        row.createCell(4).setCellValue(DateFormatUtils.format(faultTime, "yyyy-MM-dd HH:mm:ss"));
                        row.createCell(5).setCellValue(1);
                        row.createCell(6).setCellValue(duration / 60000);
                        row.createCell(7).setCellValue(ssdl);
                        row.createCell(8).setCellValue(wttpai2.getModelid());
                    } else {
                        k = 0;
                    }
                    faultTime = ts;
                } else {
                    faultTime = tsPointData.getTs();
                    k = 0;
                    continue;
                }
            }

            if (当前风机是否有故障 == 0) {
                rowz.createCell(0).setCellValue(i - 1);
                rowz.createCell(1).setCellValue(wttpai2.getWindpowerstationid());
                rowz.createCell(2).setCellValue(wttpai2.getWindturbineid());
                rowz.createCell(3).setCellValue(DateFormatUtils.format(faultTime, "yyyy-MM"));
                rowz.createCell(4).setCellValue(DateFormatUtils.format(faultTime, "yyyy-MM"));
                rowz.createCell(5).setCellValue(gzcs);
                rowz.createCell(6).setCellValue(durationlj / 60000);
                rowz.createCell(7).setCellValue(ssdl);
                rowz.createCell(8).setCellValue(wttpai2.getModelid());
                i++;
            }

        }
        //通过输出流将workbook对象下载到磁盘
        FileOutputStream out = null;
        try {
            out = new FileOutputStream("D:\\计算\\麻黄山风电场202210-1小时.xlsx");
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void calc(Date start, Date end) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();

        XSSFRow row0 = sheet.createRow(0);
        row0.createCell(0).setCellValue("序号");
        row0.createCell(1).setCellValue("场站");
        row0.createCell(2).setCellValue("风机");
        row0.createCell(3).setCellValue("月份");
        row0.createCell(4).setCellValue("故障次数");
        row0.createCell(5).setCellValue("故障时间(分钟)");
        row0.createCell(6).setCellValue("损失电量(kWh)");
        row0.createCell(7).setCellValue("机型");

        int i = 1;
        for (WindTurbineTestingPointAi2 wttpai2 : faultCodes) {
            if (wttpai2.getWindturbineid().equals("MG01_01")) {
                System.out.println();
            }
            XSSFRow row = sheet.createRow(i);
            i++;
            List<TsPointData> historyRaw = remoteServiceBuilder.ShardingService().getHistoryRaw(wttpai2.getId(), start.getTime(), end.getTime());
            //时间从大到小
            historyRaw = historyRaw.stream().sorted(Comparator.comparing(TsPointData::getTs).reversed()).collect(Collectors.toList());

            long duration = 0;//故障时间
            long durationlj = 0;//停机时间
            int ssdl = 0;//损失电量
            long faultTime = historyRaw.get(0).getTs();
            short gzcs = 0;//故障次数

            short k = 0;//是否连续

            //测点列表
            for (TsPointData tsPointData : historyRaw) {
                //点值
                int doubleValue = (int) tsPointData.getDoubleValue();
                if (doubleValue == 4) {
                    k = 0;
                    continue;
                } else if (doubleValue == 2) {
                    duration = faultTime - tsPointData.getTs();
                    //超过2小时,毫秒
                    int 两小时 = 2 * 60 * 60 * 1000;
                    int 一小时 = 1 * 60 * 60 * 1000;
                    int 半小时 = 1 * 30 * 60 * 1000;
                    if (duration > 半小时) {
                        if (k == 0) gzcs++;
                        k = 1;

                        durationlj += duration;
                        String s = llfdlMap.get(wttpai2.getWindturbineid());
                        Map<String, TsPointData> h1 = remoteServiceBuilder.ShardingService().getHistorySection(s, tsPointData.getTs());
                        Map<String, TsPointData> h2 = remoteServiceBuilder.ShardingService().getHistorySection(s, faultTime);
                        double doubleValue2 = h2.get(s).getDoubleValue();
                        double doubleValue1 = h1.get(s).getDoubleValue();
                        ssdl += doubleValue2 - doubleValue1;
                    } else {
                        k = 0;
                    }
                    faultTime = tsPointData.getTs();
                } else {
                    faultTime = tsPointData.getTs();
                    k = 0;
                    continue;
                }
            }
            row.createCell(0).setCellValue(i - 1);
            row.createCell(1).setCellValue(wttpai2.getWindpowerstationid());
            row.createCell(2).setCellValue(wttpai2.getWindturbineid());
            row.createCell(3).setCellValue(DateFormatUtils.format(faultTime, "yyyy-MM"));
            row.createCell(4).setCellValue(gzcs);
            row.createCell(5).setCellValue(durationlj / 60000);
            row.createCell(6).setCellValue(ssdl);
            row.createCell(7).setCellValue(wttpai2.getModelid());

        }
        //通过输出流将workbook对象下载到磁盘
        FileOutputStream out = null;
        try {
            out = new FileOutputStream("C:\\dell\\UpdatePackage\\麻黄山风电场202210-半小时.xlsx");
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<WindTurbineTestingPointAi2> getFaultCodes() {
        if (faultCodes == null) {
            WindTurbineTestingPointAi2Example wtspAi2Example = new WindTurbineTestingPointAi2Example();
            wtspAi2Example.createCriteria().andUniformcodeEqualTo("FJZT").andWindpowerstationidLike("%_FDC");
            faultCodes = windTurbineTestingPointAi2Mapper.selectByExample(wtspAi2Example);
            faultCodes = faultCodes.stream().sorted((t1, t2) -> {
                return Integer.parseInt(t1.getWindturbineid().replaceFirst(".+_", "")) - Integer.parseInt(t2.getWindturbineid().replaceFirst(".+_", ""));
            }).collect(Collectors.toList());
        }
        return faultCodes;
    }

    public Map<String, String> getLlfdlMap() {
        if (llfdlMap == null) {
            WindTurbineTestingPointAi2Example wtspAi2Example = new WindTurbineTestingPointAi2Example();
            wtspAi2Example.createCriteria().andUniformcodeEqualTo("YFDLLL").andWindpowerstationidLike("%_FDC");
            List<WindTurbineTestingPointAi2> ai2s = windTurbineTestingPointAi2Mapper.selectByExample(wtspAi2Example);
            llfdlMap = ai2s.stream().collect(Collectors.toMap(WindTurbineTestingPointAi2::getWindturbineid, WindTurbineTestingPointAi2::getId));
        }
        return llfdlMap;
    }


    @Test()
    public void test2() {
        List<Woworktickeask> getsomething = workticketService.getsomething("2022-08-01");

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();

        XSSFRow row0 = sheet.createRow(0);
        row0.createCell(0).setCellValue("序号");
        row0.createCell(1).setCellValue("场站");
        row0.createCell(2).setCellValue("风机");
        row0.createCell(3).setCellValue("风机定检日期");
        row0.createCell(4).setCellValue("持续时长(天)");

        int i = 1;
        for (Woworktickeask wwtt : getsomething) {
            //获取风机id
            String windturbine = getFjMap(wwtt.getSitenum()) + getWindturbine(wwtt.getAddress());
            if (windturbine == null) continue;

            XSSFRow row = sheet.createRow(i);
            row.createCell(0).setCellValue(i - 1);
            i++;
            row.createCell(1).setCellValue(wwtt.getSitenum());
            row.createCell(2).setCellValue(windturbine);
            row.createCell(3).setCellValue(DateFormatUtils.format(wwtt.getStartdate(), "yyyy-MM-dd HH:mm:ss"));
            String duration = getDuration(windturbine, wwtt.getEnddate());
            row.createCell(4).setCellValue(duration);
        }
    }

    private String getDuration(String wt, Date enddate) {
        getFaultCodes();

        List<WindTurbineTestingPointAi2> collect = faultCodes.stream().filter(f -> f.getWindturbineid().equals(wt)).collect(Collectors.toList());

        List<TsPointData> historyRaw = remoteServiceBuilder.ShardingService().getHistoryRaw(collect.get(0).getId(), enddate.getTime(), enddate.getTime() + 7 * 604800000);
        //时间从小到大
        historyRaw = historyRaw.stream().sorted(Comparator.comparing(TsPointData::getTs)).collect(Collectors.toList());

        long duration = 0;//故障时间
        long durationlj = 0;//停机时间
        double ssdl = 0;//损失电量
        long faultTime = historyRaw.get(0).getTs();
        short gzcs = 0;//故障次数

        //测点列表
        for (TsPointData tsPointData : historyRaw) {
            //点值
            int doubleValue = (int) tsPointData.getDoubleValue();

        }

        return "";
    }

    private String getWindturbine(String address) {
        Pattern pattern = Pattern.compile(REGEX);
        Matcher matcher = pattern.matcher(address);
        String group = null;
        if (matcher.find()) {
            group = matcher.group(0);
            if (group.length() < 2) group = "0" + group;
            if (group.length() > 3) return null;
        } else {
            return null;
        }
        //String s = address.replaceAll("[\\u4e00-\\u9fa5]{0,}", "");
        return group;
    }

    public String getFjMap(String fccn) {
        if (fccn.contains("麻黄山")) return "MG01_";
        if (fccn.contains("牛首山")) return "NG01_";
        if (fccn.contains("青山")) return "QG01_";
        if (fccn.contains("石板泉")) return "SG01_";
        if (fccn.contains("香山")) return "XG01_";
        return null;
    }

    public static void main(String[] args) {
        String a = null;
        String b = null;
        String c = "aa";
        String d = a + b;
        String e = a + c;
    }
}