//package com.cpp.web.service.datafactory;
//
//import cn.hutool.core.date.DateUtil;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.jiayue.ipfcst.common.core.util.DateMomentUtil;
//import com.jiayue.ipfcst.common.core.util.NumberUtils;
//import com.jiayue.ipp.common.data.entity.ForecastPowerShortTerm;
//import com.jiayue.ipp.common.data.entity.ForecastPowerShortTermHis;
//import com.jiayue.ipp.common.data.entity.Nwp;
//import com.jiayue.ipp.common.data.entity.an.ParsingChannel;
//import com.jiayue.ipp.common.data.entity.an.ParsingLog;
//import com.jiayue.ipp.common.data.entity.an.ParsingUrl;
//import com.jiayue.ipp.idp.service.ForecastPowerShortTermHisService;
//import com.jiayue.ipp.idp.service.ForecastPowerShortTermService;
//import com.jiayue.ipp.idp.service.NwpService;
//import lombok.AllArgsConstructor;
//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.BufferedReader;
//import java.io.File;
//import java.io.IOException;
//import java.io.InputStreamReader;
//import java.math.BigDecimal;
//import java.math.RoundingMode;
//import java.nio.charset.StandardCharsets;
//import java.nio.file.Files;
//import java.text.ParseException;
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//
///**
// * ftp通信业务层
// *
// * @author tl
// * @date 2022-05-11 09:51:21
// */
//@AllArgsConstructor
//@Slf4j
//@Service
//@Transactional
//public class DownloadService {
//
//    private final ParsingUrlService parsingUrlService;
//
//    private final ParsingFileService parsingFileService;
//
//    private final ParsingLogService parsingLogService;
//
//    private final ForecastPowerShortTermHisService forecastPowerShortTermHisService;
//
//    private final ForecastPowerShortTermService forecastPowerShortTermService;
//
//    private final NwpService nwpService;
//
//    /**
//     * 解析
//     *
//     * @param parsingChannel
//     */
//    public void parsing(ParsingChannel parsingChannel) {
//
//        //过滤出当前解析通道下在使用的《 解析路径 》
//        List<ParsingUrl> parsingUrls = parsingUrlService.list(Wrappers.lambdaQuery(ParsingUrl.class).eq(ParsingUrl::getCId, parsingChannel.getId()).eq(ParsingUrl::getUrlStatus, "1"));
//        String dateDir = DateFormatUtils.format(new Date(), "yyyyMMdd");
//        String dayStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
//        //遍历解析路径，对文件进行解析
//        for (ParsingUrl parsingUrl : parsingUrls) {
//
//            String failDir = parsingUrl.getUrl() + File.separator + "fail" + File.separator + dateDir;
//
//            String success = parsingUrl.getUrl() + File.separator + "success" + File.separator + dateDir;
//
//            String path = parsingUrl.getUrl() + File.separator + "new";
//
//            File dirFile = new File(path);
//
//            if (!dirFile.exists()) {
//                dirFile.mkdirs();
//            }
//            File[] files = dirFile.listFiles();
//            log.info("扫描路径：{}，文件数：{}", path, files.length);
//            //遍历文件
//            for (File file : files) {
//                String fileName = file.getName();
//                ParsingLog parsingLog = new ParsingLog();
//                parsingLog.setFileName(fileName);
//                parsingLog.setStationCode(parsingUrl.getStationCode());
//                parsingLog.setParsingTime(new Date());
//
//                if (!fileName.contains(dayStr)) {
//                    file.delete();
//                    log.warn(parsingUrl.getStationCode() + "下" + fileName + "云端文件不是当天的文件，删除！");
//                    break;
//                }
//
//                // 如果是短期文件
//                if (file.getName().startsWith("DQ")) {
//                    try {
//                        // 解析短期文件
//                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        List<ForecastPowerShortTerm> forecastPowerShortTermList = new ArrayList<>();
//                        List<ForecastPowerShortTermHis> forecastPowerShortTermHisList = new ArrayList<>();
//                        // 当文件未被使用时，进行解析上报
//                        if (file.renameTo(file)) {
//                            InputStreamReader read = null;
//                            BufferedReader bufferedReader = null;
//                            String stringLine;
//                            ForecastPowerShortTerm stf;
//                            try {
//                                read = new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8);
//                                bufferedReader = new BufferedReader(read);
//                                Long systemTime = System.currentTimeMillis();
//                                // 循环解析文件
//                                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 ForecastPowerShortTerm();
//                                            stf.setFpValue(new BigDecimal(string_arr[3]));
//                                            stf.setForecastTime(sdf.parse(string_arr[2]));
//                                            stf.setGenDate(new Date());
//                                            stf.setStationCode(parsingUrl.getStationCode());
//                                            stf.setForecastManufactor(parsingUrl.getForecastManufactor());
//                                            forecastPowerShortTermList.add(stf);
//
//                                            // 历史表
//                                            //过滤当天的数据
//                                            long secondDayTime = com.jiayue.ipp.idp.util.DateMomentUtil.getDayStartTime(systemTime) + 1000 * 60 * 60 * 24;
//                                            if (sdf.parse(string_arr[2]).getTime() >= secondDayTime) {
//                                                ForecastPowerShortTermHis forecastPowerShortTermHis = new ForecastPowerShortTermHis();
//                                                forecastPowerShortTermHis.setGenDate(new Date());
//                                                forecastPowerShortTermHis.setStationCode(parsingUrl.getStationCode());
//                                                forecastPowerShortTermHis.setAbleValue(new BigDecimal(string_arr[3]));
//                                                forecastPowerShortTermHis.setForecastTime(sdf.parse(string_arr[2]));
//                                                forecastPowerShortTermHis.setForecastHowLongAgo(DateMomentUtil.getDaysBetweenTwoDate(systemTime, sdf.parse(string_arr[2]).getTime()));
//                                                forecastPowerShortTermHis.setForecastManufactor(parsingUrl.getForecastManufactor());
//                                                forecastPowerShortTermHisList.add(forecastPowerShortTermHis);
//                                            }
//                                        }
//                                    }
//                                }
//
//                                if (forecastPowerShortTermList.size() > 0 && forecastPowerShortTermHisList.size() > 0) {
//                                    // 保存短期实时
//                                    Date startTime = forecastPowerShortTermList.get(0).getForecastTime();
//                                    Date endTime = forecastPowerShortTermList.get(forecastPowerShortTermList.size() - 1).getForecastTime();
//                                    LambdaQueryWrapper<ForecastPowerShortTerm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//                                    lambdaQueryWrapper.eq(ForecastPowerShortTerm::getStationCode, parsingUrl.getStationCode());
//                                    lambdaQueryWrapper.eq(ForecastPowerShortTerm::getForecastManufactor, parsingUrl.getForecastManufactor());
//                                    lambdaQueryWrapper.between(ForecastPowerShortTerm::getForecastTime, startTime, endTime);
//                                    forecastPowerShortTermService.remove(lambdaQueryWrapper);
//                                    forecastPowerShortTermService.saveBatch(forecastPowerShortTermList);
//
//                                    // 保存短期历史
//                                    LambdaQueryWrapper<ForecastPowerShortTermHis> forecastPowerShortTermHisLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                                    forecastPowerShortTermHisLambdaQueryWrapper.eq(ForecastPowerShortTermHis::getStationCode, parsingUrl.getStationCode());
//                                    forecastPowerShortTermHisLambdaQueryWrapper.eq(ForecastPowerShortTermHis::getForecastManufactor, parsingUrl.getForecastManufactor());
//                                    forecastPowerShortTermHisLambdaQueryWrapper.eq(ForecastPowerShortTermHis::getGenDate, DateUtil.format(new Date(), "yyyy-MM-dd"));
//                                    forecastPowerShortTermHisService.remove(forecastPowerShortTermHisLambdaQueryWrapper);
//                                    forecastPowerShortTermHisService.saveBatch(forecastPowerShortTermHisList);
//                                    log.info(parsingUrl.getStationCode() + "下" + fileName + "嘉越云端文件解析成功！");
//                                    try {
//                                        File file1 = new File(success + File.separator + fileName);
//                                        if (file1.exists()) {
//                                            file1.delete();
//                                        }
//                                        FileUtils.moveFile(file, new File(success + File.separator + fileName));
//                                    } catch (IOException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            } catch (Exception e) {
//                                log.error("嘉越云端文件解析失败：", e);
//                                try {
//                                    File file1 = new File(failDir + File.separator + fileName);
//                                    if (file1.exists()) {
//                                        file1.delete();
//                                    }
//                                    FileUtils.moveFile(file, new File(failDir + File.separator + fileName));
//                                } catch (IOException ex) {
//                                    log.error(parsingUrl.getStationCode() + "下" + fileName + "嘉越云端文件解析失败1", ex);
//                                }
//                            } finally {
//                                close(bufferedReader, read);
//                            }
//                        }
//                    } catch (Exception e) {
//                        log.error(parsingUrl.getStationCode() + "下" + fileName + "解析嘉越云端DQ文件失败", e);
//                        try {
//                            File file1 = new File(failDir + File.separator + fileName);
//                            if (file1.exists()) {
//                                file1.delete();
//                            }
//                            FileUtils.moveFile(file, new File(failDir + File.separator + fileName));
//                        } catch (IOException ex) {
//                            log.error(parsingUrl.getStationCode() + "下" + fileName + "嘉越云端文件解析失败1", ex);
//                        }
//                    }
//                }
//
//                if (file.getName().startsWith("NWP")) {
//                    List<Nwp> listNwp = new ArrayList<>();
//                    if (file.renameTo(file)) {
//                        InputStreamReader readNwp = null;
//                        BufferedReader bufferedReaderNwp = null;
//                        try {
//                            readNwp = new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8);//考虑到编码格式
//                            bufferedReaderNwp = new BufferedReader(readNwp);
//                            String lineTxt;
//                            Nwp nwpData;
//                            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 (sdf.parse(datas[5]).getTime() >= TimeUtils.getMillisecondsSubDay() + 24 * 60 * 60 *
//                                    // 1000) {
//                                    nwpData = new Nwp();
//                                    nwpData.setForecastManufactor(parsingUrl.getForecastManufactor());
//                                    //将截取的文件放入nwpData中
//                                    nwpData.setStationCode(parsingUrl.getStationCode());
////                                    nwpData.setScDate(datas[2]);
////                                    nwpData.setScTime(datas[3]);
////                                    nwpData.setPreDate(datas[4]);
//                                    nwpData.setPreTime(sdf.parse(datas[5]));//采集时间 与 短期预测时间关联
//                                    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));
//                                    if (datas.length > 35) {
//                                        //nwp 新增解析内容
////                                        nwpData.setWs20(new BigDecimal(datas[35]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWs40(new BigDecimal(datas[36]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWs60(new BigDecimal(datas[37]).setScale(2, RoundingMode.HALF_UP));
//                                        nwpData.setWs110(new BigDecimal(datas[38]).setScale(2, RoundingMode.HALF_UP));
//                                        nwpData.setWs120(new BigDecimal(datas[39]).setScale(2, RoundingMode.HALF_UP));
//                                        nwpData.setWs130(new BigDecimal(datas[40]).setScale(2, RoundingMode.HALF_UP));
//                                        nwpData.setWs140(new BigDecimal(datas[41]).setScale(2, RoundingMode.HALF_UP));
//                                        nwpData.setWs150(new BigDecimal(datas[42]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWs160(new BigDecimal(datas[43]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWs180(new BigDecimal(datas[44]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWs190(new BigDecimal(datas[45]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWs200(new BigDecimal(datas[46]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWd20(new BigDecimal(datas[47]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWd40(new BigDecimal(datas[48]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWd60(new BigDecimal(datas[49]).setScale(2, RoundingMode.HALF_UP));
//                                        nwpData.setWd110(new BigDecimal(datas[50]).setScale(2, RoundingMode.HALF_UP));
//                                        nwpData.setWd120(new BigDecimal(datas[51]).setScale(2, RoundingMode.HALF_UP));
//                                        nwpData.setWd130(new BigDecimal(datas[52]).setScale(2, RoundingMode.HALF_UP));
//                                        nwpData.setWd140(new BigDecimal(datas[53]).setScale(2, RoundingMode.HALF_UP));
//                                        nwpData.setWd150(new BigDecimal(datas[54]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWd160(new BigDecimal(datas[55]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWd180(new BigDecimal(datas[56]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWd190(new BigDecimal(datas[57]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setWd200(new BigDecimal(datas[58]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT10(new BigDecimal(datas[59]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT20(new BigDecimal(datas[60]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT30(new BigDecimal(datas[61]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT40(new BigDecimal(datas[62]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT50(new BigDecimal(datas[63]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT60(new BigDecimal(datas[64]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT70(new BigDecimal(datas[65]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT80(new BigDecimal(datas[66]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT90(new BigDecimal(datas[67]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT100(new BigDecimal(datas[68]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT110(new BigDecimal(datas[69]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT120(new BigDecimal(datas[70]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT130(new BigDecimal(datas[71]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT140(new BigDecimal(datas[72]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT150(new BigDecimal(datas[73]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT160(new BigDecimal(datas[74]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT170(new BigDecimal(datas[75]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT180(new BigDecimal(datas[76]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT190(new BigDecimal(datas[77]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setT200(new BigDecimal(datas[78]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setDniCalcd(new BigDecimal(datas[79]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setSolarZenith(new BigDecimal(datas[80]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setClearskyGhi(new BigDecimal(datas[81]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setLcc(new BigDecimal(datas[82]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setMcc(new BigDecimal(datas[83]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setHcc(new BigDecimal(datas[84]).setScale(2, RoundingMode.HALF_UP));
////                                        nwpData.setTcc(new BigDecimal(datas[85]).setScale(2, RoundingMode.HALF_UP));
//                                        nwpData.setTpr(new BigDecimal(datas[86]).setScale(2, RoundingMode.HALF_UP));
//                                    }
//                                    listNwp.add(nwpData);
//                                }
//                            }
//                            if (listNwp.size() > 0 ) {
//                                // 保存nwp实时
//                                Date startTime = listNwp.get(0).getPreTime();
//                                Date endTime = listNwp.get(listNwp.size() - 1).getPreTime();
//                                LambdaQueryWrapper<Nwp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//                                lambdaQueryWrapper.eq(Nwp::getStationCode, parsingUrl.getStationCode());
//                                lambdaQueryWrapper.eq(Nwp::getForecastManufactor, parsingUrl.getForecastManufactor());
//                                lambdaQueryWrapper.between(Nwp::getPreTime, startTime, endTime);
//                                nwpService.remove(lambdaQueryWrapper);
//                                nwpService.saveBatch(listNwp);
//                                log.info(parsingUrl.getStationCode() + "下" + fileName + "嘉越云端NWP文件解析成功！");
//                                try {
//                                    File file1 = new File(success + File.separator + fileName);
//                                    if (file1.exists()) {
//                                        file1.delete();
//                                    }
//                                    FileUtils.moveFile(file, new File(success + File.separator + fileName));
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        } 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(bufferedReaderNwp, readNwp);
//                        }
//                    }
//
//                }
//            }
//        }
//        log.info("解析嘉越云端文件定时执行完成");
//
//    }
//
//    /**
//     * 关闭文件流
//     *
//     * @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);
//        }
//    }
//}
