package com.jiayue.ipfcst.console.service;

import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import com.jiayue.ipfcst.common.core.exception.BusinessException;
import com.jiayue.ipfcst.common.core.util.*;
import com.jiayue.ipfcst.common.data.constant.enums.HolidayTypeEnum;
import com.jiayue.ipfcst.common.data.constant.enums.PredictionModelEnum;
import com.jiayue.ipfcst.common.data.entity.*;
import com.jiayue.ipfcst.common.data.entity.gathertunnelinfo.*;
import com.jiayue.ipfcst.common.data.entity.integration.InForecastPowerShortTerm;
import com.jiayue.ipfcst.common.data.entity.sendertunnelinfo.Sender104TcpTunnelInfo;
import com.jiayue.ipfcst.common.data.entity.sendertunnelinfo.SenderCdtRtuTunnelInfo;
import com.jiayue.ipfcst.common.data.entity.sendertunnelinfo.SenderModbusRtuTunnelInfo;
import com.jiayue.ipfcst.common.data.entity.sendertunnelinfo.SenderModbusTcpTunnelInfo;
import com.jiayue.ipfcst.common.data.repository.*;
import com.jiayue.ipfcst.common.data.service.BaseService;
import com.jiayue.ipfcst.dataexchange.service.*;
import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
import com.jiayue.ipfcst.fileupload.service.UploadFileCodeService;
import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
import com.jiayue.ipfcst.fileupload.service.UploadURLService;
import com.jiayue.ipfcst.fileupload.util.FileUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 解析电科院NWP和DQ文件
 *
 * @author cuil
 * @version 2.0
 * @since 2018/12/03 11:24
 */

@AllArgsConstructor
@Service
@Slf4j
@Transactional
public class FileAnalysisService extends BaseService {

	ElectricFieldService electricFieldService;

	ForecastPowerShortTermService forecastPowerShortTermService;

	InForecastPowerShortTermRepository inForecastPowerShortTermRepository;

	HolidayCalendarRepository holidayCalendarRepository;

	NwpService nwpService;

  NwpOneService nwpOneService;

  NwpTwoService nwpTwoService;

	FileAnalysisRecordService fileAnalysisRecordService;

	EntityManagerRepository entityManagerRepository;

	QuartzService quartzService;

	OverHaulPlanService overHaulPlanService;

	SysParameterService sysParameterService;

	InverterInfoService inverterInfoService;

	WeatherStationInfoService weatherStationInfoService;

	WindTowerInfoService windTowerInfoService;

	WindTurbineInfoService windTurbineInfoService;

	ElectricFieldRepository electricFieldRepository;

	PvModuleModelService pvModuleModelService;

	HolidayCalendarService holidayCalendarService;

	UploadObjectService uploadObjectService;

	UploadFileChannelService uploadFileChannelService;

	UploadFileCodeService uploadFileCodeService;

	UploadURLService uploadURLService;

	TunnelInfoService tunnelInfoService;

	EquipmentAttributeService equipmentAttributeService;

	ProtocolSenderDataPointService protocolSenderDataPointService;

	ProtocolGatherDataPointService protocolGatherDataPointService;

	ImpactOnContainerOperation impactOnContainerOperation;

	FileParseTunnelService fileParseTunnelService;

	PowerPlanSDService powerPlanSDService;

  ForecastPowerShortTermOneService forecastPowerShortTermOneService;

  ForecastPowerShortTermTwoService forecastPowerShortTermTwoService;

  ForecastPowerShortTermHisRepository forecastPowerShortTermHisRepository;
  AGC_AVCInfoService agcAvcInfoService;
  BoosterStationInfoService boosterStationInfoService;
  SubsidiaryEquipmentInfoService subsidiaryEquipmentInfoService;


  RepairPlanRepository repairPlanRepository;

  UltraShortTermCoefficientRepository ultraShortTermCoefficientRepository;



  @SneakyThrows
	public void analysisJob() {
		log.info("-----------------开始执行文件解析任务----------------------");
		long timeD = 15 * 60 * 1000;
		Long currentDate = DateTimeUtil.getMillisecondsSubDay();//今日凌晨
		boolean flag = false;
		ElectricField electricField = electricFieldService.getElectricField();

		String path = FileUtil.getDownloadFilePath() + File.separator + "new";

		File dirFile = new File(path);
		//判断该目录是否存在，不存在时创建
		if (!dirFile.exists()) {
			dirFile.mkdirs();
			log.info("【" + dirFile.getPath() + "】目录不存在，系统自动创建文件目录");
		}
		log.info("系统扫描路径【" + dirFile.getPath() + "】");

		Collection<File> files = FileUtils.listFiles(dirFile, new String[]{"RB"}, false);
		String dayStr = new SimpleDateFormat("yyyyMMdd").format(new Date());//当前时间格式化为年月日
		if (files != null && files.size() > 0) {

			for (File file : files) {
				flag = false;
				boolean sfqbxf = false;
				boolean startConsole = false;
				String fileName = file.getName();
//				if (fileName.indexOf(dayStr) < 0) {
//					file.delete();
//					log.warn(fileName + "不是当天的文件，删除！");
//					break;
//				}
				if (fileName.length() < 30) {
					//假期文件
					if (file.getName().startsWith("JH")) {
						List<HolidayCalendar> listJq = fileAnalysisJqTerm(file);
						if (listJq != null && listJq.size() > 0) {
							holidayCalendarRepository.deleteAll();
							holidayCalendarRepository.saveAll(listJq);
							flag = true;
						} else {
							flag = false;
						}
					}

					// 预测标识保存一期、二期还是总
          int ycbs = 0;
					if (file.getName().startsWith("DQ")) {
						try {
              try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), "utf-8");
                   BufferedReader bufferedReader = new BufferedReader(read);){
                String stringLine;
                while ((stringLine = bufferedReader.readLine()) != null) {
                  // 读取第一行的场站名称判断是哪期的
                  String[] firstRow = stringLine.split(" ");
                  if (firstRow.length==2){
                    // 获取场站名称
                    String czmc = firstRow[0].split("::")[1];
                    if ("光伏电场".equals(czmc)){
                      ycbs = 0;
                    }
                    if ("风电场".equals(czmc)){
                      ycbs = 1;
                    }
                  }
                  break;
                }
              }

              if (ycbs==0){
                // 原来总的
                List<ForecastPowerShortTerm> listDq = fileAnalysisShortTerm(file, currentDate);
                ForecastPowerShortTerm forecastPowerShortTerm = null;
                if (listDq != null && listDq.size() > 0) {
//                  //如果数据不全，进行补入
//                  while (listDq.get(listDq.size() - 1).getForecastTime() < DateTimeUtil.getMillisecondsSubDay() + 4 * 24 * 60 * 60 * 1000 - timeD) {
//                    forecastPowerShortTerm = new ForecastPowerShortTerm();
//                    forecastPowerShortTerm.setFpValue(listDq.get(listDq.size() - 96).getFpValue());//修正前值
//                    forecastPowerShortTerm.setGenDate(new Date()); //装机容量
//                    forecastPowerShortTerm.setForecastTime(currentDate);
//                    forecastPowerShortTerm.setPredictionModelEnum(PredictionModelEnum.E1);
//                    listDq.add(forecastPowerShortTerm);
//                  }
                  try {
                    //短期数据修正
                    Long startTime = listDq.get(0).getForecastTime();
                    Long endTime = listDq.get(listDq.size() - 1).getForecastTime();//删除相同时间数据
                    forecastPowerShortTermService.deleteBetweenAndGenTime(startTime, endTime, listDq);
                    flag = true;
                  } catch (Exception e) {
                    log.error("保存短期数据报错", e);
                    flag = false;
                  }
                } else {
                  log.info(file.getName() + "文件数据内容为空、不能正常解析 、移除该文件、执行数据修正功能");
                  flag = false;
                }
              }
              else if (ycbs==1){
                // 一期短期文件
                List<ForecastPowerShortTermOne> listDq = fileAnalysisShortTermOne(file, currentDate);
                ForecastPowerShortTermOne forecastPowerShortTermOne = null;
                if (listDq != null && listDq.size() > 0) {
                  //如果数据不全，进行补入
//                  while (listDq.get(listDq.size() - 1).getForecastTime() < DateTimeUtil.getMillisecondsSubDay() + 4 * 24 * 60 * 60 * 1000 - timeD) {
//                    forecastPowerShortTermOne = new ForecastPowerShortTermOne();
//                    forecastPowerShortTermOne.setFpValue(listDq.get(listDq.size() - 96).getFpValue());//修正前值
//                    forecastPowerShortTermOne.setGenDate(new Date()); //装机容量
//                    forecastPowerShortTermOne.setForecastTime(currentDate);
//                    forecastPowerShortTermOne.setPredictionModelEnum(PredictionModelEnum.E1);
//                    listDq.add(forecastPowerShortTermOne);
//                  }
                  try {
                    //短期数据修正
                    Long startTime = listDq.get(0).getForecastTime();
                    Long endTime = listDq.get(listDq.size() - 1).getForecastTime();//删除相同时间数据
                    forecastPowerShortTermOneService.deleteBetweenAndGenTime(startTime, endTime, listDq);
                    flag = true;
                  } catch (Exception e) {
                    log.error("风电文件保存短期数据报错", e);
                    flag = false;
                  }
                } else {
                  log.info(file.getName() + "风电文件数据内容为空、不能正常解析 、移除该文件、执行数据修正功能");
                  flag = false;
                }
              }
						} catch (Exception e) {
							flag = false;
							log.error("解析DQ文件失败", e);
						}
					}

					//用于解析一体化数据，将解析出的数据保存短期历史表和一体化实时表
          if (file.getName().startsWith("AMENDFORECAST")) {
            try {

              Map<String, List> stringListMap = fileAnalysisAmendfoForecast(file, currentDate);
              List<InForecastPowerShortTerm> inForecastPowerShortTerms = stringListMap.get("inForecast");
              List<ForecastPowerShortTermHis> forecastPowerShortTermHiss = stringListMap.get("forecastHis");
              inForecastPowerShortTerms.sort(Comparator.comparing(InForecastPowerShortTerm::getForecastTime));
              forecastPowerShortTermHiss.sort(Comparator.comparing(ForecastPowerShortTermHis::getForecastTime));
              if (inForecastPowerShortTerms != null && inForecastPowerShortTerms.size() > 0) {
                try {
                  //短期数据修正
                  Long startTime = inForecastPowerShortTerms.get(0).getForecastTime();
                  Long endTime = inForecastPowerShortTerms.get(inForecastPowerShortTerms.size() - 1).getForecastTime();//删除相同时间数据

                  String sysParameter = sysParameterService.getSysParameter("INTEGRATION_MENU", "no");
                  if(sysParameter.equals("yes")){
                    // 删除当日生成的短期历史记录
                    this.forecastPowerShortTermHisRepository.deleteToday(forecastPowerShortTermHiss.get(0).getForecastTime(),
                      forecastPowerShortTermHiss.get(forecastPowerShortTermHiss.size() - 1).getForecastTime());
                    // 保存短期历史记录
                    this.forecastPowerShortTermHisRepository.saveAll(forecastPowerShortTermHiss);
                  }
                  inForecastPowerShortTermRepository.deleteByForecastTimeBetween(startTime, endTime);
                  inForecastPowerShortTermRepository.saveAll(inForecastPowerShortTerms);
                  flag = true;
                } catch (Exception e) {
                  log.error("保存一体化数据报错", e);
                  flag = false;
                }
              } else {
                log.info(file.getName() + "文件数据内容为空、不能正常解析 、移除该文件、执行数据修正功能");
                flag = false;
              }
            } catch (Exception e) {
              flag = false;
              log.error("解析一体化文件失败", e);
            }
          }



					if (file.getName().startsWith("NWP")) {
						try {
              try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), "utf-8");
                   BufferedReader bufferedReader = new BufferedReader(read);){
                String stringLine;
                while ((stringLine = bufferedReader.readLine()) != null) {
                  // 读取第一行的场站名称判断是哪期的
                  String[] firstRow = stringLine.split(" ");
                  if (firstRow.length==2){
                    // 获取场站名称
                    String czmc = firstRow[0].split("::")[1];
                    if ("光伏电场".equals(czmc)){
                      ycbs = 0;
                    }
                    if ("风电场".equals(czmc)){
                      ycbs = 1;
                    }
                  }
                  break;
                }
              }

              if (ycbs==0) {
                // 原来总的
                List<Nwp> listNwp = fileAnalysisNwp(file);
                Nwp nwpData = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                if (listNwp != null && listNwp.size() > 0) {
//                  while (listNwp.get(listNwp.size() - 1).getPreTime() < DateTimeUtil.getMillisecondsSubDay() + 4 * 24 * 60 * 60 * 1000 - timeD) {
//                    nwpData = new Nwp();
//                    long time = 0;
//                    try {
//                      time = sdf.parse(listNwp.get(listNwp.size() - 96).getPreDate()).getTime() + 24 * 60 * 60 * 1000;
//                    } catch (ParseException e) {
//                      e.printStackTrace();
//                    }
//                    nwpData.setFarmId(listNwp.get(listNwp.size() - 96).getFarmId());
//                    nwpData.setScDate(listNwp.get(listNwp.size() - 96).getScDate());
//                    nwpData.setScTime(listNwp.get(listNwp.size() - 96).getScTime());
//                    nwpData.setPreDate(sdf.format(time));
//                    nwpData.setPreTime(listNwp.get(listNwp.size() - 1).getPreTime() + timeD);
//                    nwpData.setT(listNwp.get(listNwp.size() - 96).getT());//温度
//                    nwpData.setRh(listNwp.get(listNwp.size() - 96).getRh());//湿度
//                    nwpData.setPressure(listNwp.get(listNwp.size() - 96).getPressure());//气压
//                    nwpData.setSwr(listNwp.get(listNwp.size() - 96).getSwr());//辐射
//                    nwpData.setLwr(listNwp.get(listNwp.size() - 96).getLwr());//辐射
//                    nwpData.setDiffuseRadiation(listNwp.get(listNwp.size() - 96).getDiffuseRadiation());//散接辐射
//                    nwpData.setDirectRadiation(listNwp.get(listNwp.size() - 96).getDirectRadiation());//直接辐射
//
//                    nwpData.setSenf(listNwp.get(listNwp.size() - 96).getSenf());//热感通量
//
//                    nwpData.setWs10(listNwp.get(listNwp.size() - 96).getWs10());//10 m 风速
//                    nwpData.setWs30(listNwp.get(listNwp.size() - 96).getWs30());//30 m 风速
//                    nwpData.setWs50(listNwp.get(listNwp.size() - 96).getWs50());//50 m 风速
//                    nwpData.setWs70(listNwp.get(listNwp.size() - 96).getWs70());//70 m 风速
//                    nwpData.setWs80(listNwp.get(listNwp.size() - 96).getWs80());//80 m 风速
//                    nwpData.setWs90(listNwp.get(listNwp.size() - 96).getWs90());//90 m 风速
//                    nwpData.setWs100(listNwp.get(listNwp.size() - 96).getWs100());//100 m 风速
//                    nwpData.setWs170(listNwp.get(listNwp.size() - 96).getWs170());//170 m 风速
//
//                    nwpData.setWd10(listNwp.get(listNwp.size() - 96).getWd10());//10 m 风向
//                    nwpData.setWd30(listNwp.get(listNwp.size() - 96).getWd30());//30 m 风向
//                    nwpData.setWd50(listNwp.get(listNwp.size() - 96).getWd50());//50 m 风向
//                    nwpData.setWd70(listNwp.get(listNwp.size() - 96).getWd70());//70 m 风向
//                    nwpData.setWd80(listNwp.get(listNwp.size() - 96).getWd80());//80 m 风向
//                    nwpData.setWd90(listNwp.get(listNwp.size() - 96).getWd90());//90 m 风向
//                    nwpData.setWd100(listNwp.get(listNwp.size() - 96).getWd100());//100 m 风向
//                    nwpData.setWd170(listNwp.get(listNwp.size() - 96).getWd170());//170 m 风向
//                    listNwp.add(nwpData);
//                  }
                } else {
                  flag = false;
                  log.info(file.getName() + "文件数据内容为空、不能正常解析 、移除该文件、执行数据修正功能");
                }

                //保存NWP实时数据
                Long startTime = listNwp.get(0).getPreTime();
                Long endTime = listNwp.get(listNwp.size() - 1).getPreTime();//删除相同时间数据
                nwpService.deleteBetweenAndPreTime(startTime, endTime, listNwp);
                flag = true;
              }
              else if (ycbs==1) {
                // 一期
                List<NwpOne> listNwp = fileAnalysisNwpOne(file);
                NwpOne nwpData = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                if (listNwp != null && listNwp.size() > 0) {
//                  while (listNwp.get(listNwp.size() - 1).getPreTime() < DateTimeUtil.getMillisecondsSubDay() + 4 * 24 * 60 * 60 * 1000 - timeD) {
//                    nwpData = new NwpOne();
//                    long time = 0;
//                    try {
//                      time = sdf.parse(listNwp.get(listNwp.size() - 96).getPreDate()).getTime() + 24 * 60 * 60 * 1000;
//                    } catch (ParseException e) {
//                      e.printStackTrace();
//                    }
//                    nwpData.setFarmId(listNwp.get(listNwp.size() - 96).getFarmId());
//                    nwpData.setScDate(listNwp.get(listNwp.size() - 96).getScDate());
//                    nwpData.setScTime(listNwp.get(listNwp.size() - 96).getScTime());
//                    nwpData.setPreDate(sdf.format(time));
//                    nwpData.setPreTime(listNwp.get(listNwp.size() - 1).getPreTime() + timeD);
//                    nwpData.setT(listNwp.get(listNwp.size() - 96).getT());//温度
//                    nwpData.setRh(listNwp.get(listNwp.size() - 96).getRh());//湿度
//                    nwpData.setPressure(listNwp.get(listNwp.size() - 96).getPressure());//气压
//                    nwpData.setSwr(listNwp.get(listNwp.size() - 96).getSwr());//辐射
//                    nwpData.setLwr(listNwp.get(listNwp.size() - 96).getLwr());//辐射
//                    nwpData.setDiffuseRadiation(listNwp.get(listNwp.size() - 96).getDiffuseRadiation());//散接辐射
//                    nwpData.setDirectRadiation(listNwp.get(listNwp.size() - 96).getDirectRadiation());//直接辐射
//
//                    nwpData.setSenf(listNwp.get(listNwp.size() - 96).getSenf());//热感通量
//
//                    nwpData.setWs10(listNwp.get(listNwp.size() - 96).getWs10());//10 m 风速
//                    nwpData.setWs30(listNwp.get(listNwp.size() - 96).getWs30());//30 m 风速
//                    nwpData.setWs50(listNwp.get(listNwp.size() - 96).getWs50());//50 m 风速
//                    nwpData.setWs70(listNwp.get(listNwp.size() - 96).getWs70());//70 m 风速
//                    nwpData.setWs80(listNwp.get(listNwp.size() - 96).getWs80());//80 m 风速
//                    nwpData.setWs90(listNwp.get(listNwp.size() - 96).getWs90());//90 m 风速
//                    nwpData.setWs100(listNwp.get(listNwp.size() - 96).getWs100());//100 m 风速
//                    nwpData.setWs170(listNwp.get(listNwp.size() - 96).getWs170());//170 m 风速
//
//                    nwpData.setWd10(listNwp.get(listNwp.size() - 96).getWd10());//10 m 风向
//                    nwpData.setWd30(listNwp.get(listNwp.size() - 96).getWd30());//30 m 风向
//                    nwpData.setWd50(listNwp.get(listNwp.size() - 96).getWd50());//50 m 风向
//                    nwpData.setWd70(listNwp.get(listNwp.size() - 96).getWd70());//70 m 风向
//                    nwpData.setWd80(listNwp.get(listNwp.size() - 96).getWd80());//80 m 风向
//                    nwpData.setWd90(listNwp.get(listNwp.size() - 96).getWd90());//90 m 风向
//                    nwpData.setWd100(listNwp.get(listNwp.size() - 96).getWd100());//100 m 风向
//                    nwpData.setWd170(listNwp.get(listNwp.size() - 96).getWd170());//170 m 风向
//                    listNwp.add(nwpData);
//                  }
                } else {
                  flag = false;
                  log.info(file.getName() + "风电NWP文件数据内容为空、不能正常解析 、移除该文件、执行数据修正功能");
                }
                //保存NWP实时数据
                Long startTime = listNwp.get(0).getPreTime();
                Long endTime = listNwp.get(listNwp.size() - 1).getPreTime();//删除相同时间数据
                nwpOneService.deleteBetweenAndPreTime(startTime, endTime, listNwp);
                flag = true;
              }
						} catch (Exception e) {
							log.error("解析NWP文件失败", e);
							flag = false;
						}
					}
					if (file.getName().startsWith("UPSQL")) {
						try {
							List<String> sqlList = fileAnalysisUP(file);
							Optional.ofNullable(sqlList).ifPresent(s -> {
								entityManagerRepository.executeSql(s);
							});
							//TODO 清除缓存
							flag = true;
						} catch (Exception e) {
							flag = false;
							log.error(file.getName() + "解析失败。");
						}

					}
					if (file.getName().startsWith("UPJSON")) {

						try {
              //场站运维状态 运维状态下只对数据更新，新增操作，未运维状态下对数据进行删除后新增
              Integer operationalStatus = electricField.getStationStatusEnum().getCode();
              //状态编码等于2是运维状态
              boolean isOperational = operationalStatus == 2?true:false;
              //按行读文件内容
							List<String> list = fileAnalysisUP(file);
							if (null != list && list.size() > 0) {

								if (list.size() > 10) {
									sfqbxf = true;
								}

								for (String str : list) {
									String[] strs = str.split(":::");
									if (null != strs && strs.length > 1) {

                    //解析场站基本信息json，并入库
                    if (strs[0].equals("ElectricField")) {
                      List<ElectricField> beans = JsonBeanUtil.jsonToBean(strs[1],
                        ElectricField.class);
                      if (null != beans && beans.size() == 1) {
                        if (electricField.getStationCode().equals(beans.get(0).getStationCode())) {
                          electricFieldRepository.save(beans.get(0));
                        } else {
                          log.error("云端推送的场站信息中的编号:{} 和本地的编号：{} 不符合，请检查!",beans.get(0).getStationCode(),electricField.getStationCode());
                          break;
                        }
                      }
                    }

										//解析定时任务json，并入库
											if (strs[0].equals("Quartz")) {
												List<Quartz> quartzs = JsonBeanUtil.jsonToBean(strs[1], Quartz.class);
												if (isOperational) {
													for (Quartz quartz : quartzs) {
														quartzService.saveCloud(quartz);
													}
												} else {
													quartzService.saveCloud(quartzs);
												}
											}

										//解析检修json，并入库
											if (strs[0].equals("OverhaulPlan")) {
												List<OverhaulPlan> overhaulPlans = JsonBeanUtil.jsonToBean(strs[1], OverhaulPlan.class);
                        if(isOperational) {
                          for (OverhaulPlan overhaulPlan:overhaulPlans){
                            overHaulPlanService.saveCloud(overhaulPlan);
                          }
                        }else {
                          overHaulPlanService.saveCloud(overhaulPlans);
                        }
											}

										//解析定时系统参数，并入库
											if (strs[0].equals("SysParameter")) {
												List<SysParameter> beans = JsonBeanUtil.jsonToBean(strs[1],
														SysParameter.class);
												if (isOperational) {
													for (SysParameter bean : beans) {
														sysParameterService.saveCloud(bean);
													}
												} else {
													sysParameterService.saveCloud(beans);
												}
											}

										//解析逆变器基本信息json，并入库
											if (strs[0].equals("InverterInfo")) {
												List<InverterInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														InverterInfo.class);
												if (isOperational) {
													for (InverterInfo bean : beans) {
														inverterInfoService.saveCloud(bean);
													}
												} else {
													inverterInfoService.saveCloud(beans);
												}
											}

										//解析气象站基本信息json，并入库
											if (strs[0].equals("WeatherStationInfo")) {
												List<WeatherStationInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														WeatherStationInfo.class);
												if (isOperational) {
													for (WeatherStationInfo bean : beans) {
														weatherStationInfoService.saveCloud(bean);
													}
												} else {
													weatherStationInfoService.saveCloud(beans);
												}
											}

										//解析测风塔基本信息json，并入库
											if (strs[0].equals("WindTowerInfo")) {
												List<WindTowerInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														WindTowerInfo.class);
												if (isOperational) {
													for (WindTowerInfo bean : beans) {
														windTowerInfoService.saveCloud(bean);
													}
												} else {
													windTowerInfoService.saveCloud(beans);
												}
											}

										//解析风机基本信息json，并入库
											if (strs[0].equals("WindTurbineInfo")) {
												List<WindTurbineInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														WindTurbineInfo.class);
												if (isOperational) {
													for (WindTurbineInfo bean : beans) {
														windTurbineInfoService.saveCloud(bean);
													}
												} else {
													windTurbineInfoService.saveCloud(beans);
												}
											}

										//解析光伏组件json，并入库
											if (strs[0].equals("PvModuleModel")) {
												List<PvModuleModel> beans = JsonBeanUtil.jsonToBean(strs[1],
														PvModuleModel.class);
												if (isOperational) {
													for (PvModuleModel bean : beans) {
														pvModuleModelService.saveCloud(bean);
													}
												} else {
													pvModuleModelService.saveCloud(beans);
												}
											}

										//解析AgcAvc json，并入库
											if (strs[0].equals("AgcAvcInfo")) {
												List<AGC_AVCInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
                          AGC_AVCInfo.class);
												if (isOperational) {
													for (AGC_AVCInfo bean : beans) {
                            agcAvcInfoService.saveCloud(bean);
													}
												} else {
                          agcAvcInfoService.saveCloud(beans);
												}
											}

										//解析BoosterStationInfo json，并入库
											if (strs[0].equals("BoosterStationInfo")) {
												List<BoosterStationInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
                          BoosterStationInfo.class);
												if (isOperational) {
													for (BoosterStationInfo bean : beans) {
                            boosterStationInfoService.saveCloud(bean);
													}
												} else {
                          boosterStationInfoService.saveCloud(beans);
												}
											}

										//解析AgcAvc json，并入库
											if (strs[0].equals("SubsidiaryEquipmentInfo")) {
												List<SubsidiaryEquipmentInfo> subsidiaryEquipmentInfoList = JsonBeanUtil.jsonToBean(strs[1],
                          SubsidiaryEquipmentInfo.class);
												if (isOperational) {
													for (SubsidiaryEquipmentInfo bean : subsidiaryEquipmentInfoList) {
                            subsidiaryEquipmentInfoService.saveCloud(bean);
													}
												} else {
                          subsidiaryEquipmentInfoService.saveCloud(subsidiaryEquipmentInfoList);
												}
											}

										//解析假期日历json，并入库
											if (strs[0].equals("HolidayCalendar")) {
												List<HolidayCalendar> beans = JsonBeanUtil.jsonToBean(strs[1],
														HolidayCalendar.class);
												holidayCalendarService.saveCloud(beans);
											}

										//解析通道对象json，并入库
											if (strs[0].equals("UploadObject")) {
												List<UploadObject> beans = JsonBeanUtil.jsonToBean(strs[1],
														UploadObject.class);
												if (isOperational) {
													for (UploadObject bean : beans) {
														uploadObjectService.saveCloud(bean);
													}
												} else {
													uploadObjectService.saveCloud(beans);
												}
											}

										//解析通道json，并入库
											if (strs[0].equals("UploadFileChannel")) {
												List<UploadFileChannel> beans = JsonBeanUtil.jsonToBean(strs[1],
														UploadFileChannel.class);
												if (isOperational) {
													for (UploadFileChannel bean : beans) {
														uploadFileChannelService.saveCloud(bean);
													}
												} else {
													uploadFileChannelService.saveCloud(beans);
												}
											}

										//解析通道json，并入库
											if (strs[0].equals("UploadFileCode")) {
												List<UploadFileCode> beans = JsonBeanUtil.jsonToBean(strs[1],
														UploadFileCode.class);
												if (isOperational) {
													for (UploadFileCode bean : beans) {
														uploadFileCodeService.saveCloud(bean);
													}
												} else {
													uploadFileCodeService.saveCloud(beans);
												}
											}

										//解析通道json，并入库
											if (strs[0].equals("UploadURL")) {
												List<UploadURL> beans = JsonBeanUtil.jsonToBean(strs[1],
														UploadURL.class);
												if (isOperational) {
													for (UploadURL bean : beans) {
														uploadURLService.saveCloud(bean);
													}
												} else {
													uploadURLService.saveCloud(beans);
												}
											}

										//解析接数json，并入库
											if (strs[0].equals("EquipmentAttribute")) {
												List<EquipmentAttribute> equipmentAttributeList = JsonBeanUtil.jsonToBean(strs[1],
														EquipmentAttribute.class);
												if (equipmentAttributeList != null && equipmentAttributeList.size() > 0) {
                          if (isOperational) {
                            for (EquipmentAttribute equipmentAttribute:equipmentAttributeList) {
                              equipmentAttributeService.saveCloud(equipmentAttribute);
                            }
                          }else{
                            equipmentAttributeService.saveCloud(equipmentAttributeList);
                          }
												}
											}

											//通道信息解析并保存
											if (strs[0].equals("FileParseTunnelInfo")) {
												List<FileParseTunnelInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														FileParseTunnelInfo.class);
												if (isOperational) {
													for (FileParseTunnelInfo bean : beans) {
														bean.setDataPoints(null);
														tunnelInfoService.saveOrUpdateFileParseTunnel(bean);
													}
												} else {
													if (beans != null && beans.size() > 0) {
														List<FileParseTunnelInfo> fileParseTunnelInfos = tunnelInfoService.getAllFileParseTunnel();
														for (FileParseTunnelInfo fileParseTunnelInfo : fileParseTunnelInfos) {
																tunnelInfoService.delete(fileParseTunnelInfo.getId(), "FILEPARSE");
														}
														for (FileParseTunnelInfo bean : beans) {
															tunnelInfoService.saveOrUpdateFileParseTunnel(bean);
														}
													}
												}
											}

											if (strs[0].equals("Gather104TcpTunnelInfo")) {
												List<Gather104TcpTunnelInfo> beans = JsonBeanUtil.jsonToBean(strs[1],Gather104TcpTunnelInfo.class);
												if (isOperational) {
													for (Gather104TcpTunnelInfo bean : beans) {
														bean.setDataPoints(null);
														tunnelInfoService.saveOrUpdateGather104TcpTunnel(bean);
													}
												} else {
													if (beans != null && beans.size() > 0) {
														List<Gather104TcpTunnelInfo> list1 = tunnelInfoService.getAllGather104TcpTunnel();
														for (Gather104TcpTunnelInfo bean : list1) {
																tunnelInfoService.delete(bean.getId(), "IEC104TCPMASTER");
														}
														for (Gather104TcpTunnelInfo bean : beans) {
															tunnelInfoService.saveOrUpdateGather104TcpTunnel(bean);
														}
													}
												}
											}

											if (strs[0].equals("GatherCdtRtuTunnelInfo")) {
												List<GatherCdtRtuTunnelInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														GatherCdtRtuTunnelInfo.class);
												if (isOperational) {
													for (GatherCdtRtuTunnelInfo bean : beans) {
														bean.setDataPoints(null);
														tunnelInfoService.saveOrUpdateGatherCdtRtuTunnel(bean);
													}
												} else {
													if (beans != null && beans.size() > 0) {
														List<GatherCdtRtuTunnelInfo> list1 = tunnelInfoService.getAllGatherCdtRtuTunnel();
														for (GatherCdtRtuTunnelInfo bean : list1) {
																tunnelInfoService.delete(bean.getId(), "CDTRTUMASTER");
														}
														for (GatherCdtRtuTunnelInfo bean : beans) {
															tunnelInfoService.saveOrUpdateGatherCdtRtuTunnel(bean);
														}
													}
												}
											}

											if (strs[0].equals("GatherModbusRtuTunnelInfo")) {
												List<GatherModbusRtuTunnelInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														GatherModbusRtuTunnelInfo.class);
												if (isOperational) {
													for (GatherModbusRtuTunnelInfo bean : beans) {
														bean.setDataPoints(null);
														tunnelInfoService.saveOrUpdateGatherModbusRtuTunnel(bean);
													}
												} else {
													if (beans != null && beans.size() > 0) {
														List<GatherModbusRtuTunnelInfo> list1 = tunnelInfoService.getAllGatherModbusRtuTunnel();
														for (GatherModbusRtuTunnelInfo bean : list1) {
																tunnelInfoService.delete(bean.getId(), "MODBUSRTUMASTER");
														}
														for (GatherModbusRtuTunnelInfo bean : beans) {
															tunnelInfoService.saveOrUpdateGatherModbusRtuTunnel(bean);
														}
													}
												}
											}

											if (strs[0].equals("GatherModbusTcpTunnelInfo")) {
												List<GatherModbusTcpTunnelInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														GatherModbusTcpTunnelInfo.class);
												if (isOperational) {
													for (GatherModbusTcpTunnelInfo bean : beans) {
														bean.setDataPoints(null);
														tunnelInfoService.saveOrUpdateGatherModbusTcpTunnel(bean);
													}
												} else {
													if (beans != null && beans.size() > 0) {
														List<GatherModbusTcpTunnelInfo> list1 = tunnelInfoService.getAllGatherModbusTcpTunnel();
														for (GatherModbusTcpTunnelInfo bean : list1) {
																tunnelInfoService.delete(bean.getId(), "MODBUSTCPMASTER");
														}
														for (GatherModbusTcpTunnelInfo bean : beans) {
															tunnelInfoService.saveOrUpdateGatherModbusTcpTunnel(bean);
														}
													}
												}
											}

                      if (strs[0].equals("GatherModbusRtuWithTcpServerTunnelInfo")) {
                        List<GatherModbusRtuWithTcpServerTunnelInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
                          GatherModbusRtuWithTcpServerTunnelInfo.class);
                        if (isOperational) {
                          for (GatherModbusRtuWithTcpServerTunnelInfo bean : beans) {
                            bean.setDataPoints(null);
                            tunnelInfoService.saveOrUpdateGatherModbusRtuWithTcpServerTunnel(bean);
                          }
                        } else {
                          if (beans != null && beans.size() > 0) {
                            List<GatherModbusRtuWithTcpServerTunnelInfo> list1 = tunnelInfoService.getAllGatherModbusRtuWithTcpServerTunnel();
                            for (GatherModbusRtuWithTcpServerTunnelInfo bean : list1) {
                                tunnelInfoService.delete(bean.getId(), "TCPSERVERASMODBUSMASTER");
                            }
                            for (GatherModbusRtuWithTcpServerTunnelInfo bean : beans) {
                              tunnelInfoService.saveOrUpdateGatherModbusRtuWithTcpServerTunnel(bean);
                            }
                          }
                        }
                      }

											if (strs[0].equals("Sender104TcpTunnelInfo")) {
												List<Sender104TcpTunnelInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														Sender104TcpTunnelInfo.class);
												if (isOperational) {
													for (Sender104TcpTunnelInfo bean : beans) {
														bean.setDataPoints(null);
														tunnelInfoService.saveOrUpdateSender104TcpTunnel(bean);
													}
												} else {
													if (beans != null && beans.size() > 0) {
														List<Sender104TcpTunnelInfo> list1 = tunnelInfoService.getAllSender104TcpTunnel();
														for (Sender104TcpTunnelInfo bean : list1) {
														  tunnelInfoService.delete(bean.getId(), "IEC104TCPSLAVE");
														}
														for (Sender104TcpTunnelInfo bean : beans) {
															tunnelInfoService.saveOrUpdateSender104TcpTunnel(bean);
														}
													}
												}
											}

											if (strs[0].equals("SenderCdtRtuTunnelInfo")) {
												List<SenderCdtRtuTunnelInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														SenderCdtRtuTunnelInfo.class);
												if (isOperational) {
													for (SenderCdtRtuTunnelInfo bean : beans) {
														bean.setDataPoints(null);
														tunnelInfoService.saveOrUpdateSenderCdtRtuTunnel(bean);
													}
												} else {
													if (beans != null && beans.size() > 0) {
														List<SenderCdtRtuTunnelInfo> list1 = tunnelInfoService.getAllSenderCdtRtuTunnel();
														for (SenderCdtRtuTunnelInfo bean : list1) {
																tunnelInfoService.delete(bean.getId(), "CDTRTUSLAVE");
														}
														for (SenderCdtRtuTunnelInfo bean : beans) {
															tunnelInfoService.saveOrUpdateSenderCdtRtuTunnel(bean);
														}
													}
												}
											}

											if (strs[0].equals("SenderModbusRtuTunnelInfo")) {
												List<SenderModbusRtuTunnelInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														SenderModbusRtuTunnelInfo.class);
												if (isOperational) {
													for (SenderModbusRtuTunnelInfo bean : beans) {
														bean.setDataPoints(null);
														tunnelInfoService.saveOrUpdateSenderModbusRtuTunnel(bean);
													}
												} else {
													if (beans != null && beans.size() > 0) {
														List<SenderModbusRtuTunnelInfo> list1 = tunnelInfoService.getAllSenderModbusRtuTunnel();
														for (SenderModbusRtuTunnelInfo bean : list1) {
																tunnelInfoService.delete(bean.getId(), "MODBUSRTUSLAVE");
														}
														for (SenderModbusRtuTunnelInfo bean : beans) {
															tunnelInfoService.saveOrUpdateSenderModbusRtuTunnel(bean);
														}
													}
												}
											}

											if (strs[0].equals("SenderModbusTcpTunnelInfo")) {
												List<SenderModbusTcpTunnelInfo> beans = JsonBeanUtil.jsonToBean(strs[1],
														SenderModbusTcpTunnelInfo.class);
												if (isOperational) {
													for (SenderModbusTcpTunnelInfo bean : beans) {
														bean.setDataPoints(null);
														tunnelInfoService.saveOrUpdateSenderModbusTcpTunnel(bean);
													}
												} else {
													if (beans != null && beans.size() > 0) {
														List<SenderModbusTcpTunnelInfo> list1 = tunnelInfoService.getAllSenderModbusTcpTunnel();
														for (SenderModbusTcpTunnelInfo bean : list1) {
																tunnelInfoService.delete(bean.getId(), "MODBUSTCPSLAVE");
														}
														for (SenderModbusTcpTunnelInfo bean : beans) {
															tunnelInfoService.saveOrUpdateSenderModbusTcpTunnel(bean);
														}
													}
												}
											}

											if (strs[0].equals("ProtocolSenderDataPoint")) {
												List<ProtocolSenderDataPoint> beans = JsonBeanUtil.jsonToBean(strs[1],
														ProtocolSenderDataPoint.class);
												if (isOperational) {
													for (ProtocolSenderDataPoint bean : beans) {
														protocolSenderDataPointService.saveCloud(bean);
													}
												} else {
													protocolSenderDataPointService.saveCloud(beans);
												}
											}

											if (strs[0].equals("ProtocolGatherDataPoint")) {
												List<ProtocolGatherDataPoint> beans = JsonBeanUtil.jsonToBean(strs[1],
														ProtocolGatherDataPoint.class);
												if (isOperational) {
													for (ProtocolGatherDataPoint bean : beans) {
														protocolGatherDataPointService.saveCloud(bean);
													}
												} else {
													protocolGatherDataPointService.saveCloud(beans);
												}
											}
									}
								}
							}
							flag = true;
              startConsole = true;
							if (sfqbxf) {
								//把文件复制一份到system目录下，用来保存最后一次下发的配置文件。
								String sysPath = FileUtil.getSystemFilePath();
								mvFile(file, sysPath + File.separator + "UPJSON_BAK.RB");
							}
						} catch (Exception e) {
							flag = false;
							log.error(file.getName() + "解析失败。", e);
						}
					}
					if (file.getName().startsWith("CFT")) {
						try {
								flag = analysisEFormatCftFile(file);
						} catch (Exception e) {
							log.info(file.getName() + "文件数据内容为空、不能正常解析 、移除该文件、执行数据修正功能");
							flag = false;
						}
					}

//          if (file.getName().startsWith("CDQ_")) {
//            try {
//              flag = analysisEFormatCDQFile(file);
//            } catch (Exception e) {
//              log.info(file.getName() + "文件数据内容有误、不能正常解析 、移除该文件");
//              flag = false;
//            }
//          }
//          if (file.getName().startsWith("JX_")) {
//            try {
//              flag = analysisEFormatJXFile(file);
//            } catch (Exception e) {
//              log.info(file.getName() + "文件数据内容有误、不能正常解析 、移除该文件");
//              flag = false;
//            }
//          }

          if (flag) {
						//文件解析成功之后，保存记录
						saveFileParsingRecord(file, "1",ycbs);
						//移除文件备份到临时文件下
						moveFile(file);
						if (startConsole){
              log.info("准备重启console........");
              String str = RuntimeUtil.execForStr("ifconfig");
              log.info("ifconfig结果:"+str);

              try {
                Runtime.getRuntime().exec("service console restart");
              } catch (IOException e) {
                log.error("重启console执行失败",e);
              }
            }
					} else {
						//文件解析失败之后，保存记录
						saveFileParsingRecord(file, "0",ycbs);
						//移除文件备份到error文件下
						moveFileError(file);
					}
				}
			}
		} else {
			if (electricField.getStationCode().equals("T00000")) {
				//把保存最后一次下发的配置文件复制一份到扫描目录下，用来解析入库基础配置信息。
				String sysPath = FileUtil.getSystemFilePath();
				File file = new File(sysPath + File.separator + "UPJSON_BAK.RB");
				if (file.exists()) {
					String downloadPath = FileUtil.getDownloadFilePath() + File.separator + "new" + File.separator;
					mvFile(file, downloadPath + "UPJSON_" + dayStr + "0000000.RB");
				}
			}
		}


		Collection<File> filesXml = FileUtils.listFiles(dirFile, new String[]{"xml", "rb","RB", "txt"}, false);
		if (filesXml != null && filesXml.size() > 0) {
			for (File file : filesXml) {
				try {
          // 解析二版的外网文件
					if (file.getName().startsWith("CFT")) {
							flag = analysisEFormatCftFile(file);
					} else {
            // 解析三版的外网文件
						List<String> list = fileAnalysisUP(file);
						if (null != list && list.size() > 0) {
							for (String s : list) {
								if (s.indexOf("_") > -1) {
									String[] datas = s.split("_");
									List<BigDecimal> ycDatas = new ArrayList<>();
									if (datas.length > 1) {
										String[] vals = datas[1].split(",");
										for (String val : vals) {
											ycDatas.add(new BigDecimal(val));
										}
									}
									fileParseTunnelService.receiveData(datas[0], ycDatas);
									flag = true;
								}
							}
						}
					}
				} catch (Exception e) {
					log.error("解析xml文件失败", e);
				} finally {
					if (flag) {
						//文件解析成功之后，保存记录
						saveFileParsingRecord(file, "1",99);
						//移除文件备份到临时文件下
						moveFile(file);
					} else {
						//文件解析失败之后，保存记录
						saveFileParsingRecord(file, "0",99);
						//移除文件备份到error文件下
						moveFileError(file);
					}
				}
			}
		}
		log.info("-----------------执行文件解析任务完成----------------------");
	}





//  /**
//   * 解析E文本 得到一体化提供的超短期系数
//   */
//  public boolean analysisEFormatCDQFile(File file) {
//    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//    // 当文件未被使用时，进行解析
//    if (file.renameTo(file)) {
//      InputStreamReader read = null;
//      BufferedReader bufferedReader = null;
//      String stringLine;
//      try {
//        List<UltraShortTermCoefficient> list = new ArrayList<>();
//        read = new InputStreamReader(new FileInputStream(file), "utf-8");
//        bufferedReader = new BufferedReader(read);
//        //读取文件内容
//        String parseTime = "";
//        while ((stringLine = bufferedReader.readLine()) != null) {
//
//
//          //数据解析存入对象
//          if(stringLine.startsWith("#")){
//            UltraShortTermCoefficient ultraShortTermCoefficient = new UltraShortTermCoefficient();
//            String[] split = stringLine.split(" ");
//
//            ultraShortTermCoefficient.setTime(sdf.parse(split[2]));
//            ultraShortTermCoefficient.setCoefficient(new BigDecimal(split[3]));
//            ultraShortTermCoefficient.setParseTime(sdf1.parse(parseTime));
//            list.add(ultraShortTermCoefficient);
//          }else if(stringLine.startsWith("<!Entity=")){
//            String[] split = stringLine.split("'");
//            parseTime = split[1];
//          }
//        }
//        ultraShortTermCoefficientRepository.saveAll(list);
//      } catch (Exception e) {
//        log.error("超短期系数文件解析错误", e);
//        File destFile = new File(file.getPath().replaceFirst("new", "error"));
//        if (destFile.exists()) {
//          destFile.delete();
//        }
//        try {
//          FileUtils.moveFile(file, destFile);
//        } catch (IOException e1) {
//          log.error(file.getName() + "文件移动失败", e);
//        }
//      }finally {
//        close(bufferedReader, read);
//      }
//    }
//    return true;
//  }
//
//
//
//  /**
//   * 解析E文本 得到一体化提供的检修消减
//   */
//  public boolean analysisEFormatJXFile(File file) {
//    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//    // 当文件未被使用时，进行解析
//    if (file.renameTo(file)) {
//      InputStreamReader read = null;
//      BufferedReader bufferedReader = null;
//      String stringLine;
//      try {
//        List<RepairPlan> list = new ArrayList<>();
//        read = new InputStreamReader(new FileInputStream(file), "utf-8");
//        bufferedReader = new BufferedReader(read);
//
//        String parseTime = "";
//        //读取文件内容
//        while ((stringLine = bufferedReader.readLine()) != null) {
//
//          RepairPlan repairPlan = new RepairPlan();
//          //数据解析存入对象
//          if(stringLine.startsWith("#")){
//            String[] split = stringLine.split(" ");
//
//            repairPlan.setStartTime(sdf.parse(split[2]));
//            repairPlan.setEndTime(sdf.parse(split[3]));
//            repairPlan.setCapacityCurtailment(new BigDecimal(split[4]));
//            repairPlan.setParseTime(sdf1.parse(parseTime));
//            list.add(repairPlan);
//          }else if(stringLine.startsWith("<!Entity=")){
//            String[] split = stringLine.split("'");
//            parseTime = split[1];
//          }
//
//        }
//
//        repairPlanRepository.deleteAll();
//        repairPlanRepository.saveAll(list);
//      } catch (Exception e) {
//        log.error("检修计划文件解析错误", e);
//        File destFile = new File(file.getPath().replaceFirst("new", "error"));
//        if (destFile.exists()) {
//          destFile.delete();
//        }
//        try {
//          FileUtils.moveFile(file, destFile);
//        } catch (IOException e1) {
//          log.error(file.getName() + "文件移动失败", e);
//        }
//      }finally {
//        close(bufferedReader, read);
//      }
//    }
//    return true;
//  }

  /**
   * 分析E文本 协议采集生成的过隔离 文件
   */
  public boolean analysisEFormatCftFile(File file) {
    String proId = file.getName().split("_")[0].replace("CFT", "");
    List<String> list = fileAnalysisUP(file, "V2");
    Boolean tunnelStatus=null;
    if (null != list && list.size() > 0) {
      List<BigDecimal> ycDatas = new ArrayList<>();
      for (String s : list) {
        String[] datas = s.split("\t");
        if (datas.length > 1) {
          String[] vals = datas[1].split(",");
          for (String val : vals) {
            ycDatas.add(new BigDecimal(val));
          }
        }else{
          if("#correct".equals(s)){
            //通道状态正常
            tunnelStatus=true;
          }else if("#error".equals(s)){
            tunnelStatus=false;
          }
        }
      }
      fileParseTunnelService.receiveData(proId, ycDatas,tunnelStatus);
    }
    return true;
  }

  public static void mvFile(File file, String fdPath) {
		try {
			FileUtils.copyFile(file, new File(fdPath), true);
		} catch (IOException e) {
			log.error("文件移动错误", e);
		}
	}

	/**
	 * NWP解析
	 *
	 * @param file 文件路径
	 * @return 样例集合
	 */
	private List<Nwp> fileAnalysisNwp(File file) {
		List<Nwp> listNwp = new ArrayList<>();
		if (file.renameTo(file)) {
			InputStreamReader readNwp = null;
			BufferedReader bufferedReaderNwp = null;
			try {
				readNwp = new InputStreamReader(new FileInputStream(file), "utf-8");//考虑到编码格式
				bufferedReaderNwp = new BufferedReader(readNwp);
//				String fileName = file.getName();
//				fileName = fileName.substring(fileName.indexOf("_") + 1, fileName.lastIndexOf("."));
				String lineTxt;
				Nwp nwpData = null;
				BigDecimal nwpDirectRadiation = new BigDecimal(0.7); //直接辐射
				BigDecimal nwpDiffuseRadiation = new BigDecimal(0.3); //散接辐射

				while ((lineTxt = bufferedReaderNwp.readLine()) != null) {
					//NWP文件按照Tab方式截取
					String[] datas = lineTxt.split("\t");
					if (datas.length >= 35 && datas[0].startsWith("#")) {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						if (datas != null && datas.length > 0) {
							//过滤当天的数据
							//if (sdf.parse(datas[5]).getTime() >= TimeUtils.getMillisecondsSubDay() + 24 * 60 * 60 *
							// 1000) {
							nwpData = new Nwp();

							//将截取的文件放入nwpData中
							nwpData.setFarmId(datas[1]);
							nwpData.setScDate(datas[2]);
							nwpData.setScTime(datas[3]);
							nwpData.setPreDate(datas[4]);
							nwpData.setPreTime(sdf.parse(datas[5]).getTime());//采集时间 与 短期预测时间关联
							nwpData.setT(NumberUtils.subtract(new BigDecimal(datas[6]), new BigDecimal(273.15)));//温度

							nwpData.setSenf(new BigDecimal(datas[11]).setScale(2, RoundingMode.HALF_UP));//感热
							nwpData.setSwr(new BigDecimal(datas[9]).setScale(2, RoundingMode.HALF_UP));//短波辐射(相当于总辐射)
							nwpData.setLwr(new BigDecimal(datas[10]).setScale(2, RoundingMode.HALF_UP));//短波辐射(相当于总辐射)
							nwpData.setPressure(new BigDecimal(datas[8]).setScale(2, RoundingMode.HALF_UP));//地表气压
							nwpData.setRh(new BigDecimal(datas[7]).setScale(2, RoundingMode.HALF_UP));//2m相对湿度
							nwpData.setDiffuseRadiation(new BigDecimal(datas[9]).multiply(nwpDiffuseRadiation).setScale(2, RoundingMode.HALF_UP));//散接辐射
							nwpData.setDirectRadiation(new BigDecimal(datas[9]).multiply(nwpDirectRadiation).setScale(2, RoundingMode.HALF_UP));//直接辐射

							nwpData.setWs10(new BigDecimal(datas[19]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWs30(new BigDecimal(datas[20]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWs50(new BigDecimal(datas[21]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWs70(new BigDecimal(datas[22]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWs80(new BigDecimal(datas[23]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWs90(new BigDecimal(datas[24]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWs100(new BigDecimal(datas[25]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWs170(new BigDecimal(datas[26]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWd10(new BigDecimal(datas[27]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWd30(new BigDecimal(datas[28]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWd50(new BigDecimal(datas[29]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWd70(new BigDecimal(datas[30]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWd80(new BigDecimal(datas[31]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWd90(new BigDecimal(datas[32]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWd100(new BigDecimal(datas[33]).setScale(2, RoundingMode.HALF_UP));
							nwpData.setWd170(new BigDecimal(datas[34]).setScale(2, RoundingMode.HALF_UP));
							listNwp.add(nwpData);
							//}
						}
					}
				}
			} catch (IOException | ParseException | RuntimeException e) {
				log.error("系统错误：", e);
				// 进行告警
				String name = "NWP文件解析失败";
				String describe = "请查看NWP文件格式是否正常";
//                String errorInfo = CommonUtil.printStackTraceToString(e);
				String solution = "请修改NWP文件内容";
//                super.saveSysAlarm(SysAlarmTypeEnum.Other.name(), name, describe, SysAlarmPritorityEnum
//                .AlarmPritorityLow.name(), errorInfo, solution);
				File destFile = new File(file.getPath().replaceFirst("new", "error"));
				if (destFile.exists()) {
					destFile.delete();
				}
				try {
					FileUtils.moveFile(file, destFile);
				} catch (IOException e1) {
					log.error(file.getName() + "文件解析失败", e);
				}
			} finally {
				close(bufferedReaderNwp, readNwp);
			}
		}
		return listNwp;
	}

  /**
   * 一期NWP解析
   *
   * @param file 文件路径
   * @return 样例集合
   */
  private List<NwpOne> fileAnalysisNwpOne(File file) {
    List<NwpOne> listNwpOne = new ArrayList<>();
    if (file.renameTo(file)) {
      InputStreamReader readNwp = null;
      BufferedReader bufferedReaderNwp = null;
      try {
        readNwp = new InputStreamReader(new FileInputStream(file), "utf-8");//考虑到编码格式
        bufferedReaderNwp = new BufferedReader(readNwp);
//        String fileName = file.getName();
//        fileName = fileName.substring(fileName.indexOf("_") + 1, fileName.lastIndexOf("."));
        String lineTxt;
        NwpOne nwpData = null;
        BigDecimal nwpDirectRadiation = new BigDecimal(0.7); //直接辐射
        BigDecimal nwpDiffuseRadiation = new BigDecimal(0.3); //散接辐射

        while ((lineTxt = bufferedReaderNwp.readLine()) != null) {
          //NWP文件按照Tab方式截取
          String[] datas = lineTxt.split("\t");
          if (datas.length >= 35 && datas[0].startsWith("#")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (datas != null && datas.length > 0) {
              //过滤当天的数据
              //if (sdf.parse(datas[5]).getTime() >= TimeUtils.getMillisecondsSubDay() + 24 * 60 * 60 *
              // 1000) {
              nwpData = new NwpOne();

              //将截取的文件放入nwpData中
              nwpData.setFarmId(datas[1]);
              nwpData.setScDate(datas[2]);
              nwpData.setScTime(datas[3]);
              nwpData.setPreDate(datas[4]);
              nwpData.setPreTime(sdf.parse(datas[5]).getTime());//采集时间 与 短期预测时间关联
              nwpData.setT(NumberUtils.subtract(new BigDecimal(datas[6]), new BigDecimal(273.15)));//温度

              nwpData.setSenf(new BigDecimal(datas[11]).setScale(2, RoundingMode.HALF_UP));//感热
              nwpData.setSwr(new BigDecimal(datas[9]).setScale(2, RoundingMode.HALF_UP));//短波辐射(相当于总辐射)
              nwpData.setLwr(new BigDecimal(datas[10]).setScale(2, RoundingMode.HALF_UP));//短波辐射(相当于总辐射)
              nwpData.setPressure(new BigDecimal(datas[8]).setScale(2, RoundingMode.HALF_UP));//地表气压
              nwpData.setRh(new BigDecimal(datas[7]).setScale(2, RoundingMode.HALF_UP));//2m相对湿度
              nwpData.setDiffuseRadiation(new BigDecimal(datas[9]).multiply(nwpDiffuseRadiation).setScale(2, RoundingMode.HALF_UP));//散接辐射
              nwpData.setDirectRadiation(new BigDecimal(datas[9]).multiply(nwpDirectRadiation).setScale(2, RoundingMode.HALF_UP));//直接辐射

              nwpData.setWs10(new BigDecimal(datas[19]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs30(new BigDecimal(datas[20]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs50(new BigDecimal(datas[21]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs70(new BigDecimal(datas[22]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs80(new BigDecimal(datas[23]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs90(new BigDecimal(datas[24]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs100(new BigDecimal(datas[25]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs170(new BigDecimal(datas[26]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd10(new BigDecimal(datas[27]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd30(new BigDecimal(datas[28]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd50(new BigDecimal(datas[29]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd70(new BigDecimal(datas[30]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd80(new BigDecimal(datas[31]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd90(new BigDecimal(datas[32]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd100(new BigDecimal(datas[33]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd170(new BigDecimal(datas[34]).setScale(2, RoundingMode.HALF_UP));
              listNwpOne.add(nwpData);
            }
          }
        }
      } catch (IOException | ParseException | RuntimeException e) {
        log.error("系统错误：", e);
        File destFile = new File(file.getPath().replaceFirst("new", "error"));
        if (destFile.exists()) {
          destFile.delete();
        }
        try {
          FileUtils.moveFile(file, destFile);
        } catch (IOException e1) {
          log.error(file.getName() + "一期NWP文件解析失败", e);
        }
      } finally {
        close(bufferedReaderNwp, readNwp);
      }
    }
    return listNwpOne;
  }

  /**
   * 二期NWP解析
   *
   * @param file 文件路径
   * @return 样例集合
   */
  private List<NwpTwo> fileAnalysisNwpTwo(File file) {
    List<NwpTwo> listNwpTwo = new ArrayList<>();
    if (file.renameTo(file)) {
      InputStreamReader readNwp = null;
      BufferedReader bufferedReaderNwp = null;
      try {
        readNwp = new InputStreamReader(new FileInputStream(file), "utf-8");//考虑到编码格式
        bufferedReaderNwp = new BufferedReader(readNwp);
//        String fileName = file.getName();
//        fileName = fileName.substring(fileName.indexOf("_") + 1, fileName.lastIndexOf("."));
        String lineTxt;
        NwpTwo nwpData = null;
        BigDecimal nwpDirectRadiation = new BigDecimal(0.7); //直接辐射
        BigDecimal nwpDiffuseRadiation = new BigDecimal(0.3); //散接辐射

        while ((lineTxt = bufferedReaderNwp.readLine()) != null) {
          //NWP文件按照Tab方式截取
          String[] datas = lineTxt.split("\t");
          if (datas.length >= 35 && datas[0].startsWith("#")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (datas != null && datas.length > 0) {
              //过滤当天的数据
              //if (sdf.parse(datas[5]).getTime() >= TimeUtils.getMillisecondsSubDay() + 24 * 60 * 60 *
              // 1000) {
              nwpData = new NwpTwo();

              //将截取的文件放入nwpData中
              nwpData.setFarmId(datas[1]);
              nwpData.setScDate(datas[2]);
              nwpData.setScTime(datas[3]);
              nwpData.setPreDate(datas[4]);
              nwpData.setPreTime(sdf.parse(datas[5]).getTime());//采集时间 与 短期预测时间关联
              nwpData.setT(NumberUtils.subtract(new BigDecimal(datas[6]), new BigDecimal(273.15)));//温度

              nwpData.setSenf(new BigDecimal(datas[11]).setScale(2, RoundingMode.HALF_UP));//感热
              nwpData.setSwr(new BigDecimal(datas[9]).setScale(2, RoundingMode.HALF_UP));//短波辐射(相当于总辐射)
              nwpData.setLwr(new BigDecimal(datas[10]).setScale(2, RoundingMode.HALF_UP));//短波辐射(相当于总辐射)
              nwpData.setPressure(new BigDecimal(datas[8]).setScale(2, RoundingMode.HALF_UP));//地表气压
              nwpData.setRh(new BigDecimal(datas[7]).setScale(2, RoundingMode.HALF_UP));//2m相对湿度
              nwpData.setDiffuseRadiation(new BigDecimal(datas[9]).multiply(nwpDiffuseRadiation).setScale(2, RoundingMode.HALF_UP));//散接辐射
              nwpData.setDirectRadiation(new BigDecimal(datas[9]).multiply(nwpDirectRadiation).setScale(2, RoundingMode.HALF_UP));//直接辐射

              nwpData.setWs10(new BigDecimal(datas[19]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs30(new BigDecimal(datas[20]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs50(new BigDecimal(datas[21]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs70(new BigDecimal(datas[22]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs80(new BigDecimal(datas[23]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs90(new BigDecimal(datas[24]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs100(new BigDecimal(datas[25]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWs170(new BigDecimal(datas[26]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd10(new BigDecimal(datas[27]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd30(new BigDecimal(datas[28]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd50(new BigDecimal(datas[29]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd70(new BigDecimal(datas[30]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd80(new BigDecimal(datas[31]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd90(new BigDecimal(datas[32]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd100(new BigDecimal(datas[33]).setScale(2, RoundingMode.HALF_UP));
              nwpData.setWd170(new BigDecimal(datas[34]).setScale(2, RoundingMode.HALF_UP));
              listNwpTwo.add(nwpData);
            }
          }
        }
      } catch (IOException | ParseException | RuntimeException e) {
        log.error("系统错误：", e);
        File destFile = new File(file.getPath().replaceFirst("new", "error"));
        if (destFile.exists()) {
          destFile.delete();
        }
        try {
          FileUtils.moveFile(file, destFile);
        } catch (IOException e1) {
          log.error(file.getName() + "二期NWP文件解析失败", e);
        }
      } finally {
        close(bufferedReaderNwp, readNwp);
      }
    }
    return listNwpTwo;
  }

	/**
	 * update文件解析
	 *
	 * @param file 文件路径
	 * @return 样例集合
	 */
	private List<String> fileAnalysisUP(File file) {
		List<String> sqlList = new ArrayList<>();

    if (file.renameTo(file)) {
			InputStreamReader readup = null;
			BufferedReader bufferedReaderup = null;
			try {
				readup = new InputStreamReader(new FileInputStream(file), "utf-8");//考虑到编码格式
				bufferedReaderup = new BufferedReader(readup);
				String lineTxt;
				while ((lineTxt = bufferedReaderup.readLine()) != null) {
					if (!lineTxt.startsWith("<")) {
						if(lineTxt.startsWith("//") || lineTxt.startsWith("@@")){
							lineTxt = lineTxt.substring(2);
						}
						sqlList.add(StrUtil.trim(lineTxt));
					}
				}
			} catch (IOException e) {
				log.error("系统错误：", e);
				File destFile = new File(file.getPath().replaceFirst("new", "error"));
				if (destFile.exists()) {
					destFile.delete();
				}
				try {
					FileUtils.moveFile(file, destFile);
				} catch (IOException e1) {
					log.error(file.getName() + "文件解析失败", e);
				}
			} finally {
				close(bufferedReaderup, readup);
			}
		}else{
      log.error("当前配置文件没有读权限：{}",file.getAbsoluteFile());
    }
		return sqlList;
	}

	private List<String> fileAnalysisUP(File file, String v) {
		List<String> sqlList = new ArrayList<>();
		if (file.renameTo(file)) {
			InputStreamReader readup = null;
			BufferedReader bufferedReaderup = null;
			try {
				readup = new InputStreamReader(new FileInputStream(file), "utf-8");//考虑到编码格式
				bufferedReaderup = new BufferedReader(readup);
				String lineTxt;
				while ((lineTxt = bufferedReaderup.readLine()) != null) {
					if (lineTxt.startsWith("#")) {
						sqlList.add(StrUtil.trim(lineTxt));
					}
				}
			} catch (IOException e) {
				log.error("系统错误：", e);
				File destFile = new File(file.getPath().replaceFirst("new", "error"));
				if (destFile.exists()) {
          destFile.delete();
        }
				try {
					FileUtils.moveFile(file, destFile);
				} catch (IOException e1) {
					log.error(file.getName() + "文件解析失败", e);
				}
			} finally {
				close(bufferedReaderup, readup);
			}
		}
		return sqlList;
	}

	/**
	 * 假期解析
	 *
	 * @param file 文件路径
	 * @return 样例集合
	 */
	private List<HolidayCalendar> fileAnalysisJqTerm(File file) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<HolidayCalendar> holidayCalendars = new ArrayList<>();
		// 当文件未被使用时，进行解析上报
		if (file.renameTo(file)) {
			InputStreamReader read = null;
			BufferedReader bufferedReader = null;
			String stringLine;
			HolidayCalendar holiday;
			try {
				read = new InputStreamReader(new FileInputStream(file), "utf-8");
				bufferedReader = new BufferedReader(read);
				while ((stringLine = bufferedReader.readLine()) != null) {
					String[] string_arr = stringLine.split("\t");
					if (string_arr.length == 7 && string_arr[0].startsWith("#")) {
						holiday = new HolidayCalendar();
						holiday.setId(Integer.parseInt(string_arr[1] + ""));
						holiday.setName(string_arr[2] + "");
						holiday.setStartTime(sdf.parse(string_arr[3]).getTime());
						holiday.setEndTime(sdf.parse(string_arr[4]).getTime());
						holiday.setDays(Integer.parseInt(string_arr[5] + ""));
						if (string_arr[6].equals("1")) {
							holiday.setHolidayTypeEnum(HolidayTypeEnum.valueOf(string_arr[6]));
						}
						holidayCalendars.add(holiday);
					}
				}
			} catch (IOException | ParseException | RuntimeException e) {
				log.error("系统错误：", e);
				// 进行告警
				String name = "假期文件解析失败";
				String describe = "请查看假期文件格式是否正常";
//                String errorInfo = CommonUtil.printStackTraceToString(e);
				String solution = "请修改假期文件内容";
//                super.saveSysAlarm(SysAlarmTypeEnum.Other.name(), name, describe, SysAlarmPritorityEnum
//                .AlarmPritorityLow.name(), errorInfo, solution);
				File destFile = new File(file.getPath().replaceFirst("new", "error"));
				if (destFile.exists()) {
					destFile.delete();
				}
				try {
					FileUtils.moveFile(file, destFile);
				} catch (IOException e1) {
					log.error(file.getName() + "文件解析失败", e);
				}
			} finally {
				close(bufferedReader, read);
			}
		}
		return holidayCalendars;
	}

	/**
	 * 短期解析
	 *
	 * @param file        文件路径
	 * @param currentDate 当前时间
	 * @return 样例集合
	 */
	private List<ForecastPowerShortTerm> fileAnalysisShortTerm(File file, Long currentDate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<ForecastPowerShortTerm> forecastPowerShortTerm = new ArrayList<>();
		// 当文件未被使用时，进行解析上报
		if (file.renameTo(file)) {
			InputStreamReader read = null;
			BufferedReader bufferedReader = null;
			String stringLine;
			ForecastPowerShortTerm stf;
			try {
				read = new InputStreamReader(new FileInputStream(file), "utf-8");
				bufferedReader = new BufferedReader(read);
				while ((stringLine = bufferedReader.readLine()) != null) {
					String[] string_arr = stringLine.split("\t");
					if (string_arr.length == 4 && string_arr[0].startsWith("#")) {
						if (StringUtils.isNotEmpty(string_arr[2])) {
							//过滤当天的数据
							//if (sdf.parse(string_arr[2]).getTime() >= TimeUtils.getMillisecondsSubDay() + 24 * 60 *
							// 60 * 1000) {
							stf = new ForecastPowerShortTerm();
							stf.setFpValue(new BigDecimal(string_arr[3] + ""));
							stf.setForecastTime(sdf.parse(string_arr[2]).getTime());
							stf.setGenDate(new Date(currentDate));
							stf.setPredictionModelEnum(PredictionModelEnum.E1);
							forecastPowerShortTerm.add(stf);
							// }
						}
					}
				}
			} catch (IOException | ParseException | RuntimeException e) {
				log.error("系统错误：", e);
				// 进行告警
//                String fileName = "短期文件解析失败";
//                String describe = "请查看短期文件格式是否正常";
//                String errorInfo = CommonUtil.printStackTraceToString(e);
//                String solution = "请修改短期文件内容";
//                super.saveSysAlarm(SysAlarmTypeEnum.Other.name(), fileName, describe, SysAlarmPritorityEnum
//                .AlarmPritorityLow.name(), errorInfo, solution);
				File destFile = new File(file.getPath().replaceFirst("new", "error"));
				if (destFile.exists()) {
					destFile.delete();
				}
				try {
					FileUtils.moveFile(file, destFile);
				} catch (IOException e1) {
					log.error(file.getName() + "文件解析失败", e);
				}
			} finally {
				close(bufferedReader, read);
			}
		}
		return forecastPowerShortTerm;
	}

  /**
   * 一期短期解析
   *
   * @param file        文件路径
   * @param currentDate 当前时间
   * @return 样例集合
   */
  private List<ForecastPowerShortTermOne> fileAnalysisShortTermOne(File file, Long currentDate) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    List<ForecastPowerShortTermOne> forecastPowerShortTermOne = new ArrayList<>();
    // 当文件未被使用时，进行解析上报
    if (file.renameTo(file)) {
      InputStreamReader read = null;
      BufferedReader bufferedReader = null;
      String stringLine;
      ForecastPowerShortTermOne stf;
      try {
        read = new InputStreamReader(new FileInputStream(file), "utf-8");
        bufferedReader = new BufferedReader(read);
        while ((stringLine = bufferedReader.readLine()) != null) {
          String[] string_arr = stringLine.split("\t");
          if (string_arr.length == 4 && string_arr[0].startsWith("#")) {
            if (StringUtils.isNotEmpty(string_arr[2])) {
              stf = new ForecastPowerShortTermOne();
              stf.setFpValue(new BigDecimal(string_arr[3] + ""));
              stf.setForecastTime(sdf.parse(string_arr[2]).getTime());
              stf.setGenDate(new Date(currentDate));
              stf.setPredictionModelEnum(PredictionModelEnum.E1);
              forecastPowerShortTermOne.add(stf);
            }
          }
        }
      } catch (IOException | ParseException | RuntimeException e) {
        log.error("系统错误：", e);
        File destFile = new File(file.getPath().replaceFirst("new", "error"));
        if (destFile.exists()) {
          destFile.delete();
        }
        try {
          FileUtils.moveFile(file, destFile);
        } catch (IOException e1) {
          log.error(file.getName() + "一期文件解析失败", e);
        }
      } finally {
        close(bufferedReader, read);
      }
    }
    return forecastPowerShortTermOne;
  }

  /**
   * 二期短期解析
   *
   * @param file        文件路径
   * @param currentDate 当前时间
   * @return 样例集合
   */
  private List<ForecastPowerShortTermTwo> fileAnalysisShortTermTwo(File file, Long currentDate) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    List<ForecastPowerShortTermTwo> forecastPowerShortTermTwo = new ArrayList<>();
    // 当文件未被使用时，进行解析上报
    if (file.renameTo(file)) {
      InputStreamReader read = null;
      BufferedReader bufferedReader = null;
      String stringLine;
      ForecastPowerShortTermTwo stf;
      try {
        read = new InputStreamReader(new FileInputStream(file), "utf-8");
        bufferedReader = new BufferedReader(read);
        while ((stringLine = bufferedReader.readLine()) != null) {
          String[] string_arr = stringLine.split("\t");
          if (string_arr.length == 4 && string_arr[0].startsWith("#")) {
            if (StringUtils.isNotEmpty(string_arr[2])) {
              stf = new ForecastPowerShortTermTwo();
              stf.setFpValue(new BigDecimal(string_arr[3] + ""));
              stf.setForecastTime(sdf.parse(string_arr[2]).getTime());
              stf.setGenDate(new Date(currentDate));
              stf.setPredictionModelEnum(PredictionModelEnum.E1);
              forecastPowerShortTermTwo.add(stf);
            }
          }
        }
      } catch (IOException | ParseException | RuntimeException e) {
        log.error("系统错误：", e);
        File destFile = new File(file.getPath().replaceFirst("new", "error"));
        if (destFile.exists()) {
          destFile.delete();
        }
        try {
          FileUtils.moveFile(file, destFile);
        } catch (IOException e1) {
          log.error(file.getName() + "二期文件解析失败", e);
        }
      } finally {
        close(bufferedReader, read);
      }
    }
    return forecastPowerShortTermTwo;
  }

  /*
  * 一体化文件解析
  *
  * 一体化文件和dq文件一样也是使用云平台模式进行下发到new目录来进行解析
  * */
  private Map<String,List> fileAnalysisAmendfoForecast(File file, Long currentDate) throws BusinessException {
    ElectricField electricField = super.getElectricField();
    // 查询预测时间点对应的开机容量
    Map<Long, BigDecimal> openCapacityMap = null;
    try {
      openCapacityMap = super.queryOpenCapacity(currentDate, currentDate+864000000, electricField.getCapacity());
    } catch (BusinessException e) {
      log.error("预测数据生成获取开机容量出错：" + CommonUtil.printStackTraceToString(e));
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    List<InForecastPowerShortTerm> inForecastPowerShortTerms = new ArrayList<>();
    List<ForecastPowerShortTermHis> forecastPowerShortTermHiss = new ArrayList<>();
    // 当文件未被使用时，进行解析上报
    if (file.renameTo(file)) {
      InputStreamReader read = null;
      BufferedReader bufferedReader = null;
      String stringLine;
      InForecastPowerShortTerm istf;
      ForecastPowerShortTermHis forecastPowerShortTermHis;
      try {
        read = new InputStreamReader(new FileInputStream(file), "utf-8");
        bufferedReader = new BufferedReader(read);
        while ((stringLine = bufferedReader.readLine()) != null) {
          String[] string_arr = stringLine.split("\t");
          if (string_arr.length == 20 && string_arr[0].startsWith("#")) {
            if (StringUtils.isNotEmpty(string_arr[1])) {

              istf = new InForecastPowerShortTerm();
              istf.setFpValue(new BigDecimal(string_arr[3] + ""));
              istf.setSwr(new BigDecimal(string_arr[5] + ""));
              istf.setDiffuseRadiation(new BigDecimal(string_arr[9] + ""));
              istf.setDirectRadiation(new BigDecimal(string_arr[7] + ""));
              istf.setHumidity(new BigDecimal(string_arr[17] + ""));
              istf.setPressure(new BigDecimal(string_arr[19] + ""));
              istf.setTemperature(new BigDecimal(string_arr[15] + ""));
              istf.setWindspeed(new BigDecimal(string_arr[11] + ""));
              istf.setWindDir(new BigDecimal(string_arr[13] + ""));
              istf.setForecastTime(sdf.parse(string_arr[1]).getTime());
              istf.setGenDate(new Date(currentDate));
              istf.setPredictionModelEnum(PredictionModelEnum.E11);
              inForecastPowerShortTerms.add(istf);

              forecastPowerShortTermHis = new ForecastPowerShortTermHis();
              forecastPowerShortTermHis.setForecastTime(sdf.parse(string_arr[1]).getTime());
              forecastPowerShortTermHis.setTheoryValue(new BigDecimal(string_arr[3] + ""));
              forecastPowerShortTermHis.setCapacity(electricField.getCapacity());
              // 预测可用功率=预测*（开机容量/装机容量）
              BigDecimal ableValue =
                new BigDecimal(string_arr[2] + "").multiply(openCapacityMap.get(sdf.parse(string_arr[1]).getTime()))
                  .divide(electricField.getCapacity(), 2, BigDecimal.ROUND_HALF_UP);
              forecastPowerShortTermHis.setAbleValue(ableValue);
              forecastPowerShortTermHis.setHumidity(new BigDecimal(string_arr[16] + ""));
              forecastPowerShortTermHis.setPressure(new BigDecimal(string_arr[18] + ""));
              forecastPowerShortTermHis.setTemperature(new BigDecimal(string_arr[14] + ""));
              forecastPowerShortTermHis.setWindspeed(new BigDecimal(string_arr[10] + ""));
              forecastPowerShortTermHis.setWindDir(new BigDecimal(string_arr[12] + ""));
              forecastPowerShortTermHis.setPredictionModelEnum(PredictionModelEnum.E11);
              forecastPowerShortTermHis.setGenDate(new Date());
              forecastPowerShortTermHis.setSuCapacity(openCapacityMap.get(sdf.parse(string_arr[1]).getTime()));
              // 设置提前几天预测
              forecastPowerShortTermHis.setForecastHowLongAgo(DateMomentUtil.getDaysBetweenTwoDate(currentDate, forecastPowerShortTermHis.getForecastTime()));
              forecastPowerShortTermHiss.add(forecastPowerShortTermHis);
            }
          }
        }
      } catch (IOException | ParseException | RuntimeException e) {
        log.error("系统错误：", e);
        File destFile = new File(file.getPath().replaceFirst("new", "error"));
        if (destFile.exists()) {
          destFile.delete();
        }
        try {
          FileUtils.moveFile(file, destFile);
        } catch (IOException e1) {
          log.error(file.getName() + "文件解析失败", e);
        }
      } finally {
        close(bufferedReader, read);
      }
    }

    Map<String,List> map = new HashMap<>();
    map.put("inForecast",inForecastPowerShortTerms);
    map.put("forecastHis",forecastPowerShortTermHiss);
    return map;
  }

	/**
	 * 移动文件到临时目录下
	 *
	 * @param file 文件
	 */
	private void moveFile(File file) {
		// 移动文件到处理目录
		File destFile = new File(file.getPath().replaceFirst("new", "backupsTemp"));
		log.info("move file :{}, dest file:{}", file, destFile);
		if (destFile.exists()) {
			destFile.delete();
		}
		try {
			FileUtils.moveFile(file, destFile);
		} catch (IOException e) {
			log.error("系统移除文件错误：", e);
			// 进行告警
//      String name = file.getName();
//      String describe = "移除" + name + "失败";
//      String errorInfo = CommonUtil.printStackTraceToString(e);
//      String solution = "";
//      super.saveSysAlarm(SysAlarmTypeEnum.Other.name(), name, describe, SysAlarmPritorityEnum.AlarmPritorityLow
//      .name(), errorInfo, solution);
		}
		moveFileBackups(destFile.getParent());
	}

	/**
	 * 移动文件到处理目录
	 *
	 * @param filePath 文件路径
	 */
	private void moveFileBackups(String filePath) {
		String targetRoot = filePath.replaceFirst("backupsTemp", "backups");
		String path = mkDirForTime(targetRoot, null);
		path = mkDirForTime(path, "yyyy");
		path = mkDirForTime(path, "MM");
		path = mkDirForTime(path, "yyyyMMdd");
		path = mkDirForTime(path, "HHmm");
		// 移动文件夹内容
		File sourceFile = new File(filePath);
		if (sourceFile.exists()) {
			try {
				File[] files = sourceFile.listFiles();
				if (files != null && files.length > 0) {
					for (File f : files) {
						if (f.renameTo(new File(path + f.getName()))) {
							log.info("move file :{}, dest file:{}", path, f.getName());
						}
					}
				}
			} catch (Exception e) {
				// 进行告警
//        String name = sourceFile.getName();
//        String describe = "移动" + name + "失败";
//        String errorInfo = CommonUtil.printStackTraceToString(e);
//        String solution = "";
//        super.saveSysAlarm(SysAlarmTypeEnum.Other.name(), name, describe, SysAlarmPritorityEnum.AlarmPritorityLow
//        .name(), errorInfo, solution);
			}
		}
	}

	/**
	 * 移动文件到处理错误目录下
	 *
	 * @param file 文件
	 */
	private void moveFileError(File file) {
		File destFile = new File(file.getPath().replaceFirst("new", "error"));
		if (destFile.exists()) {
			destFile.delete();
		}
		try {
			FileUtils.moveFile(file, destFile);
		} catch (IOException e) {
			log.error(file.getName() + "文件解析失败", e);
		}
	}

	/**
	 * 创建备份文件夹
	 *
	 * @param targetRoot
	 * @param format
	 * @return
	 */
	public static String mkDirForTime(String targetRoot, String format) {
		String path = null;
		File file = null;
		if (StringUtils.isNotEmpty(format)) {
			Long current = System.currentTimeMillis();
			path = DateFormatUtils.format(current, format);
			file = new File(targetRoot + File.separator + path + File.separator);

		} else {
			file = new File(targetRoot + File.separator);
		}

		if (!file.exists() && !file.isFile()) {

			if (file.mkdir()) {
				log.info("已创建文件夹");
			} else {
				log.info("创建文件夹失败,路径：" + file.getPath());
			}
		}
		return file.getPath() + File.separator;
	}

	/**
	 * 保存文件解析记录
	 *
	 * @param file       文件信息
	 * @param fileStatus 文件解析状态 1:表示解析成功 0：解析失败
   * @param ycbs        预 测标识
	 */
	private void saveFileParsingRecord(File file, String fileStatus,Integer ycbs) {
		String fileType = "";
		if (file.getName().startsWith("JH")) {
			fileType = "JH";//假期文件
		} else if (file.getName().startsWith("DQ")) {
      if (ycbs==0){
        fileType = "DQ";//总短期文件
      }
      else if (ycbs==1){
        fileType = "DQ1";//一期短期文件
      }
      else if (ycbs==2){
        fileType = "DQ2";//二期短期文件
      }
		} else if (file.getName().startsWith("NWP")) {
      if (ycbs==0){
        fileType = "NWP";//总NWP
      }
      else if (ycbs==1){
        fileType = "NWP1";//一期NWP
      }
      else if (ycbs==2){
        fileType = "NWP2";//二期NWP
      }
		} else if (file.getName().startsWith("UP")) {
			fileType = "UP";//UP文件
		} else {
			fileType = "ZXGL";
		}
		FileAnalysisRecord fileParsingRecord = new FileAnalysisRecord();
		fileParsingRecord.setFileTitle(file.getName());
		fileParsingRecord.setFileType(fileType);
		fileParsingRecord.setFileStatus(fileStatus);
		fileParsingRecord.setFilePath(file.getPath());
		fileParsingRecord.setFileDescription(DateTimeUtil.getStringDate() + " 正常解析文件");
		fileAnalysisRecordService.save(fileParsingRecord);
	}

	private void saveFileParsingRecord(File file, String fileStatus, String fileType) {
//        String fileType = "";
//        if (file.getName().startsWith("JH")) {
//            fileType = "JH";//假期文件
//        } else if (file.getName().startsWith("DQ")) {
//            fileType = "DQ";//短期文件
//        } else if (file.getName().startsWith("NWP")) {
//            fileType = "NWP";//NWP文件
//        } else if (file.getName().startsWith("UP")) {
//            fileType = "UP";//UP文件
//        } else {
//            fileType = "ZXGL";
//        }
		FileAnalysisRecord fileParsingRecord = new FileAnalysisRecord();
		fileParsingRecord.setFileTitle(file.getName());
		fileParsingRecord.setFileType(fileType);
		fileParsingRecord.setFileStatus(fileStatus);
		fileParsingRecord.setFilePath(file.getPath());
		fileParsingRecord.setFileDescription(DateTimeUtil.getStringDate() + " 正常解析文件");
		fileAnalysisRecordService.save(fileParsingRecord);
	}

	/**
	 * 关闭文件流
	 *
	 * @param bufferedReader 字符数据
	 * @param read           字节流
	 */
	private void close(BufferedReader bufferedReader, InputStreamReader read) {
		try {
			if (bufferedReader != null) {
				bufferedReader.close();
			}
			if (read != null) {
				read.close();
			}
		} catch (IOException e) {
			log.error("关闭文件流失败:", e);
		}
	}

	/**
	 * 解析正向隔离文件
	 */
	@SneakyThrows
	public void analysisJobZxgl() {
		log.info("-----------------开始执行解析正向隔离文件任务----------------------");
		boolean flag = false;
		String path = FileUtil.getZxglFilePath() + File.separator + "new";
		File dirFile = new File(path);
		//判断该目录是否存在，不存在时创建
		if (!dirFile.exists()) {
			dirFile.mkdirs();
			log.info("【" + dirFile.getPath() + "】目录不存在，系统自动创建文件目录");
		}
		log.info("系统扫描路径【" + dirFile.getPath() + "】");
		Collection<File> files = FileUtils.listFiles(dirFile, new String[]{"xml", "rb", "txt"}, false);
		if (files != null && files.size() > 0) {
			for (File file : files) {
				try {
					String fileName = file.getName();
					List<String> list = fileAnalysisUP(file);
					if (null != list && list.size() > 0) {
						for (String s : list) {
							if (s.indexOf("_") > -1) {
								String[] datas = s.split("_");
								List<BigDecimal> ycDatas = new ArrayList<>();
								if (datas.length > 1) {
									String[] vals = datas[1].split(",");
									for (String val : vals) {
										ycDatas.add(new BigDecimal(val));
									}
								}
								fileParseTunnelService.receiveData(datas[0], ycDatas);
								flag = true;
							}
						}
					}
				} catch (Exception e) {
					log.error("解析正向隔离文件失败", e);
				} finally {
					if (flag) {
						//文件解析成功之后，保存记录
						saveFileParsingRecord(file, "1",99);
						//移除文件备份到临时文件下
						moveFile(file);
					} else {
						//文件解析失败之后，保存记录
						saveFileParsingRecord(file, "0",99);
						//移除文件备份到error文件下
						moveFileError(file);
					}
				}
			}
		}

		log.info("-----------------执行解析正向隔离文件任务完成----------------------");
	}

	/**
	 * 解析山东发电计划文件
	 */
	@SneakyThrows
	public void analysisJobSDPowerPlan() {
		log.info("-----------------开始执行解析山东发电计划文件任务----------------------");
		boolean flag = false;
		String path = FileUtil.getDownloadFilePath() + File.separator + "sdpowerplan" + File.separator + "new";
		File dirFile = new File(path);
		//判断该目录是否存在，不存在时创建
		if (!dirFile.exists()) {
			dirFile.mkdirs();
			log.info("【" + dirFile.getPath() + "】目录不存在，系统自动创建文件目录");
		}
		log.info("系统扫描路径【" + dirFile.getPath() + "】");
		Collection<File> files = FileUtils.listFiles(dirFile, new String[]{"RB"}, false);
		if (files != null && files.size() > 0) {
			for (File file : files) {
//                File readfile = new File(localFilePath + File.separator + tempSrcList[i].getName());
				InputStreamReader inputStreamReader = null;
				BufferedReader bufferedReader = null;
				try {
					inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8");
					bufferedReader = new BufferedReader(inputStreamReader);
					String lineTxt = null;
					List<PowerPlanSD> powerPlanList = new ArrayList<>();
					String dateStr = "";
					while ((lineTxt = bufferedReader.readLine()) != null) {
						PowerPlanSD powerPlan = new PowerPlanSD();
						if (lineTxt.indexOf("=") > 0) {
							//获取数据时间
							String[] dataTimeStr = lineTxt.split("=");
							dateStr = dataTimeStr[1].replace("'", "").replace(">", "").replace("-", "").trim();
						}
						if (lineTxt.startsWith("#")) {
							String b[] = lineTxt.split("\t");
							String time = b[1].replace("VAL", "");
							SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
							long planTime = sdf.parse(dateStr + time).getTime();
							powerPlan.setPlanTime(planTime);
							powerPlan.setPlanValue(Float.parseFloat(b[2]));
							powerPlanList.add(powerPlan);
						}
					}
					if (!powerPlanList.isEmpty()) {
						// 先删除库中存在的时间
						Long startTime = powerPlanList.get(0).getPlanTime();
						Long endTime = powerPlanList.get(powerPlanList.size() - 1).getPlanTime();//删除相同时间数据
						powerPlanSDService.deleteByPlanTime(startTime, endTime);
						// 保存入库
						powerPlanSDService.saveAll(powerPlanList);
						// 入库成功后将文件移动backups目录下
						flag = true;
					}
				} catch (Exception e) {
					log.error("解析山东发电计划文件失败", e);
					flag = false;
				} finally {
					bufferedReader.close();
					inputStreamReader.close();
					if (flag) {
						//文件解析成功之后，保存记录
						saveFileParsingRecord(file, "1", "PowerPlanSD");
						//移除文件备份到临时文件下
						moveFile(file);
					} else {
						//文件解析失败之后，保存记录
						saveFileParsingRecord(file, "0", "PowerPlanSD");
						//移除文件备份到error文件下
						moveFileError(file);
					}
				}
			}
		}

		log.info("-----------------执行解析山东发电计划文件任务完成----------------------");
	}



//
//    public static void main(String[] args) {
//	    String val = "^?^1111231^?^231111111^?^111111^?^111^?^11";
//	    String[] vals = val.split("\\^\\?\\^");
//	    System.out.println(vals);
//    }
}
