package com.zjsgfa.project.zt.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.zjsgfa.common.utils.DateUtils;
import com.zjsgfa.framework.aspectj.lang.annotation.DataSource;
import com.zjsgfa.framework.aspectj.lang.enums.DataSourceType;
import com.zjsgfa.framework.web.domain.AjaxResult;
import com.zjsgfa.project.zjsgfa.domain.*;
import com.zjsgfa.project.zjsgfa.mapper.*;
import com.zjsgfa.project.zt.domain.*;
import com.zjsgfa.project.zt.domain.vo.JsgaVo;
import com.zjsgfa.project.zt.domain.vo.JswaVo;
import com.zjsgfa.project.zt.domain.vo.SjInfo;
import com.zjsgfa.project.zt.mapper.*;
import com.zjsgfa.project.zt.service.DjdcService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.StringReader;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
@DataSource(value = DataSourceType.SLAVE)
public class DjdcServiceImpl implements DjdcService {

    @Autowired
    private DjdcInfoMapper djdcInfoMapper;
    @Autowired
    private JstaMapper jstaMapper;

    @Autowired
    private JswaMapper jswaMapper;
    @Autowired
    private JsqaMapper jsqaMapper;

    @Autowired
    private LjZtzhdfMapper ljZtzhdfMapper;

    @Autowired
    private LjSzfxjgMapper ljSzfxjgMapper;
    @Autowired
    private LjZtdfzhMapper ljZtdfzhMapper;
    @Autowired
    private LjZjzhfxMapper ljZjzhfxMapper;


    @Autowired
    private SjDzfcMapper sjDzfcMapper;
    @Autowired
    private LjQueryMapper ljQueryMapper;

    @Autowired
    private DzgzzbMapper dzgzzbMapper;

    @Autowired
    private TsyxclxxMapper tsyxclxxMapper;

    @Autowired
    private SjLjjwMapper sjLjjwMapper;


    @Autowired
    private JsbaMapper jsbaMapper;

    @Autowired
    private SjJygjGdsjgdcsMapper sjJygjGdsjgdcsMapper;

    @Autowired
    private SjDcfxTsyxMapper sjDcfxTsyxMapper;


    @Autowired
    private SjZysxMapper sjZysxMapper;

    @Override
    public List<DjDcInfo> getList(DjDcInfo info) {
        return djdcInfoMapper.getList(info);
    }

    @Override
    public List<Ljinfo> ljListByJh(Ljinfo info) {
        return djdcInfoMapper.ljListByJh(info);
    }

    @Override
    public List<Djjc> getDjjcList(CommonParam param) {
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
//            Djjc djjc=djdcInfoMapper.getDjinfoByjh(param.getJh());
//            if(djjc==null){
//                return new ArrayList<>();
//            }else {
//                param.setJdhzb(djjc.getJdhzb());
//                param.setJdzzb(djjc.getJdzzb());
//            }
        }
        // 创建数据列表
        List<Qzyy> qzyyList = new ArrayList<>();

        // 添加数据
        qzyyList.add(new Qzyy("BHA", "更换井底钻具"));
        qzyyList.add(new Qzyy("CP", "取心位置"));
        qzyyList.add(new Qzyy("CM", "调整钻井液"));
        qzyyList.add(new Qzyy("DSF", "钻具失效"));
        qzyyList.add(new Qzyy("DMF", "井下马达失效"));
        qzyyList.add(new Qzyy("DP", "转矩堵塞"));
        qzyyList.add(new Qzyy("DTF", "井下钻具失效"));
        qzyyList.add(new Qzyy("DST", "中途测试"));
        qzyyList.add(new Qzyy("DOG", "试油"));
        qzyyList.add(new Qzyy("FM", "地层变化"));
        qzyyList.add(new Qzyy("HR", "已到规定时间"));
        qzyyList.add(new Qzyy("HP", "井眼问题"));
        qzyyList.add(new Qzyy("LOG", "电测"));
        qzyyList.add(new Qzyy("PP", "泵压正常"));
        qzyyList.add(new Qzyy("PR", "钻速原因"));
        qzyyList.add(new Qzyy("RIG", "钻机修理"));
        qzyyList.add(new Qzyy("TD", "钻达设计井深"));
        qzyyList.add(new Qzyy("TQ", "扭矩变化"));
        qzyyList.add(new Qzyy("TW", "钻杆扭坏"));
        qzyyList.add(new Qzyy("WC", "气候变化"));
        qzyyList.add(new Qzyy("WD", "钻具刺漏"));
        //查询临井
        List<Djjc> list =djdcInfoMapper.getDjjcList(param);

        for(Djjc item:list){
            //查询密度
            Jswa jswapa=new Jswa();
            jswapa.setJh(item.getJh());
            jswapa.setJs(item.getJs());
            if(item.getJs()!=null){
                Jswa md=jswaMapper.selectMd(jswapa);
                if(md!=null){
                    item.setZjymd(md.getMd());
                }
            }
            Map<Integer, Integer> valueCountMap = new TreeMap<>(); // 使用TreeMap自动按值排序

           //判断喷嘴
            List<Integer> values = Arrays.asList(
                    item.getPZ1(), item.getPZ2(), item.getPZ3(),
                    item.getPZ4(), item.getPZ5(), item.getPZ6(),
                    item.getPZ7(), item.getPZ8(), item.getPZ9(), item.getPZ10()
            );
            for (Integer value : values) {
                if (value != null && value != 0) {
                    valueCountMap.put(value, valueCountMap.getOrDefault(value, 0) + 1);
                }
            }
            String pz=valueCountMap.entrySet().stream()
                    .map(entry -> entry.getKey() + "*" + entry.getValue())
                    .collect(Collectors.joining("+"));
            item.setPz(pz);
            //
            String lx = item.getLx();
            if(StringUtils.isNotEmpty(lx)){
                if(lx.startsWith("PDC") || lx.startsWith("pdc")){
                    String wpc = item.getWpc();
                    String npc = item.getNpc();
                    String wpcqk="";
                    String npcqk="";
                    if(StringUtils.isNotEmpty(wpc)){
                        Integer clsz = clsz(wpc);
                        for(int i=0 ;i<9;i++){
                            if(clsz==i){
                                if(i==0){
                                    wpcqk="外排齿：无磨损";
                                }else {
                                    wpcqk="外排齿："+i+"级磨损";
                                }
                                break;
                            }
                        }
                    }

                    if(StringUtils.isNotEmpty(npc)){
                        Integer clsz = clsz(npc);
                        for(int i=0 ;i<9;i++){
                            if(clsz==i){
                                if(i==0){
                                    npcqk="内排齿：无磨损";
                                }else {
                                    npcqk="内排齿："+i+"级磨损";
                                }
                                break;
                            }
                        }
                    }
                    item.setMxqk(npcqk+" "+wpcqk);

                }else {
                    String yc = item.getYcmsqk();
                    String zc = item.getZcmsqk();
                    String wpcqk="";
                    String npcqk="";
                    if(StringUtils.isNotEmpty(yc)){
                        Integer clsz = clsz(yc);
                        for(int i=1 ;i<9;i++){
                            if(clsz==i){
                                if(i==0){
                                    wpcqk="牙齿：无磨损";
                                }else {
                                    wpcqk="牙齿：1/"+i+"磨损";
                                }
                                break;
                            }
                        }
                    }

                    if(StringUtils.isNotEmpty(zc)){
                        Integer clsz = clsz(yc);
                        for(int i=1 ;i<9;i++){
                            if(clsz==i){
                                if(i==0){
                                    npcqk="轴承：无磨损";
                                }else {
                                    npcqk="轴承：1/"+i+"磨损";
                                }
                                break;
                            }
                        }
                    }
                    item.setMxqk(npcqk+" "+wpcqk);
                }
            }
            //起钻原因：
            if(StringUtils.isNotEmpty(item.getQzyy())){
                Qzyy qzyy = qzyyList.stream().filter(it -> it.getLabel().equals(item.getQzyy())).findFirst().orElse(null);
                if(qzyy!=null){
                    item.setQzyy(qzyy.getLabel()+"-"+qzyy.getValue());
                }
            }

        }
        return list;
    }

    public Integer clsz(String str){

//        List<Integer> numbers = new ArrayList<>();
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(str);

        String re="";
        while (matcher.find()) {
            re=re+matcher.group();

        }
        if(StringUtils.isNotEmpty(re)){
            return  Integer.parseInt(re);
        }else {
            return 0;
        }




    }

    @Override
    public List<DjZqsjfx> getZqshfxList(CommonParam param) throws Exception {
        //查询临井
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
//            Djjc djjc=djdcInfoMapper.getDjinfoByjh(param.getJh());
//            if(djjc==null){
//                return new ArrayList<>();
//            }else {
//                param.setJdhzb(djjc.getJdhzb());
//                param.setJdzzb(djjc.getJdzzb());
//            }
        }

//        String result2 = HttpRequest.get(url).execute().body();

//        System.out.println(result2);
//        模拟返回值
//        List<Map<String, Object>> mapList = processJson(result2);
//        List<Map<String, Object>> mapList = processJson(jsonString);

//        List<Map<String, Object>> jh = mapList.stream().filter(it -> param.getJh().equals(it.get("JH").toString())).collect(Collectors.toList());

        List<DjZqsjfx> list =djdcInfoMapper.getZqshfxList(param);
        DecimalFormat df = new DecimalFormat("#.00");
        DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);

        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter outputFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for(DjZqsjfx item:list){
            //查询进尺和层位
            DjZqsjfx djZqsjfx=djdcInfoMapper.getJcAndCw(item);
            if(djZqsjfx == null){
                continue;
            }
            item.setJc(djZqsjfx.getJc());
            item.setCw(djZqsjfx.getCw().substring(djZqsjfx.getCw().lastIndexOf("-")+1));
//查询日志表
            String kssj =item.getKssj();
            String jssj =item.getJssj();
            String zwsj ="";
            String wasj ="";

            Jswa jswap=new Jswa();
            jswap.setKsrq(DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.parseDate(item.getKssj())));
            jswap.setJsrq(DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.parseDate(item.getJssj())));
            jswap.setJs(item.getJs());
            jswap.setJh(item.getJh());
            Jswa jswaZwsj = jswaMapper.selectZwsj(jswap);
            if(jswaZwsj!=null){

                String brzygz = jswaZwsj.getBrzygz();
                // 去除所有空白字符（包括空格、制表符、换行符等）
                String cleanedRecord = brzygz.replaceAll("\\s+", "");
                List<TimePointPair> timePointPairs = extractTimePointPairsBeforeDrilling(cleanedRecord);
                if(timePointPairs.size()==0){
                    timePointPairs=extractTimePeriodsBeforeDrilling(cleanedRecord);
                }
                System.out.println("钻进字样前的时间点及其前一个时间点：");
                for (TimePointPair pair : timePointPairs) {
                    System.out.println("前一个时间点：" + pair.getPreviousTime() +
                            "，钻进时间点：" + pair.getDrillingTime() +
                            "，是否跨天：" + pair.isCrossDay());

                    String formattedTime = pair.getDrillingTime().format(DateTimeFormatter.ISO_LOCAL_TIME);
                    if( pair.isCrossDay()){
                        zwsj= DateUtils.parseDateToStr("yyyy-MM-dd",jswaZwsj.getRq()) +" "+formattedTime;
                    }else {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(jswaZwsj.getRq());        // 设置为当前日期
                        calendar.add(Calendar.DAY_OF_YEAR, -1);  // 一天
                        // 获取明天的Date对象
                        Date tomorrow = calendar.getTime();
                        zwsj= DateUtils.parseDateToStr("yyyy-MM-dd",tomorrow) +" "+formattedTime;
                    }
                }
            }

            System.out.println(zwsj);
            item.setZwsj(zwsj);

            item.setWasj(wasj);

            //计算钻进实际周期
            if(StringUtils.isNotEmpty(kssj) && StringUtils.isNotEmpty(zwsj) ){
                // 解析字符串并转换为 UTC 时间

                // 转换为 UTC 时间戳（Instant）
//                Instant instant1 = kssj.toInstant();
//                Instant instant2 = zwsj.toInstant();
//                String dateTimeStr1 = kssj.format(outputFormatter2);
//                String dateTimeStr2 = zwsj.format(outputFormatter2);

                LocalDateTime dateTime1 = LocalDateTime.parse(kssj, outputFormatter2);
                LocalDateTime dateTime2 = LocalDateTime.parse(zwsj, outputFormatter2);

                // 转换为 Instant（假设为 UTC 时区）
                Instant instant1 = dateTime1.atZone(ZoneOffset.UTC).toInstant();
                Instant instant2 = dateTime2.atZone(ZoneOffset.UTC).toInstant();

                // 计算秒数差
                long secondsDiff = Duration.between(instant1, instant2).getSeconds();

                // 转换为天数（保留两位小数）
                double daysDiff = secondsDiff / (24.0 * 60 * 60);

                item.setZjzq(Double.parseDouble(df.format(daysDiff)));
                //计算异常周期
                Jswa jswa =new Jswa();
                jswa.setKsrq(kssj);
                jswa.setJsrq(zwsj);
                jswa.setJh(item.getJh());
                List<Jswa> jswaList = jswaMapper.getList(jswa);
                Double zjycsl=0.0;
                for(Jswa wa:jswaList){
                    zjycsl=zjycsl+(wa.getSg()+wa.getXl()+wa.getZrtg()+wa.getZztg()+wa.getFzqk());
                }

                //异常周期
                item.setZjycsl(Double.parseDouble(df.format(zjycsl/24)));
                //生产周期
                item.setZjsczq(Double.parseDouble(df.format(item.getZjzq()-item.getZjycsl())));
                //钻进速率
                if(item.getZjzq()>0){
                    Double zjsl=item.getJc()/item.getZjzq();
                    item.setZjsl(Double.parseDouble(df.format(zjsl)));
                }
                if(zjycsl>0){
                    //钻进异常描述
                    item.setZjycms(String.join(",",jswaList.stream().map(Jswa::getBrzygz).collect(Collectors.toList())));
                }

            }
            //计算中完实际周期
            if(StringUtils.isNotEmpty(jssj)&& StringUtils.isNotEmpty(zwsj)){
                // 转换为 UTC 时间戳（Instant）

//                String dateTimeStr1 = zwsj.format(outputFormatter2);
//                String dateTimeStr2 = jssj.format(outputFormatter2);

                LocalDateTime dateTime1 = LocalDateTime.parse(zwsj, outputFormatter2);
                LocalDateTime dateTime2 = LocalDateTime.parse(jssj, outputFormatter2);

                // 转换为 Instant（假设为 UTC 时区）
                Instant instant1 = dateTime1.atZone(ZoneOffset.UTC).toInstant();
                Instant instant2 = dateTime2.atZone(ZoneOffset.UTC).toInstant();

                // 计算秒数差
                long secondsDiff = Duration.between(instant1, instant2).getSeconds();

                // 转换为天数（保留两位小数）
                double daysDiff = secondsDiff / (24.0 * 60 * 60);

                item.setZwzq(Double.parseDouble(df.format(daysDiff)));

                item.setZwzq(Double.parseDouble(df.format(daysDiff)));
                //计算异常周期
                Jswa jswa =new Jswa();
                jswa.setKsrq(zwsj);
                jswa.setJsrq(jssj);
                jswa.setJh(item.getJh());
                List<Jswa> jswaList = jswaMapper.getList(jswa);
                Double zjycsl=0.0;
                for(Jswa wa:jswaList){
                    zjycsl=zjycsl+(wa.getSg()+wa.getXl()+wa.getZrtg()+wa.getZztg()+wa.getFzqk());
                }
                item.setWjycsl(Double.parseDouble(df.format(zjycsl/24)));
                //生产周期
                item.setWjsczq(Double.parseDouble(df.format(item.getZwzq()-item.getWjycsl())));
                if(zjycsl>0){
                    //中完异常描述
                    item.setWjycms(String.join(",",jswaList.stream().map(Jswa::getBrzygz).collect(Collectors.toList())));
                }
            }


        }
        
        


        return list;
    }


    public static List<TimePointPair> extractTimePointPairsBeforeDrilling(String record) {
        List<TimePointPair> pairs = new ArrayList<>();

        // 匹配所有时间点（格式为H:mm）
        Pattern timePattern = Pattern.compile("(\\d+:\\d+)");
        Matcher timeMatcher = timePattern.matcher(record);

        // 匹配"钻进"前的时间点
        Pattern drillingPattern = Pattern.compile("(\\d+:\\d+)(?=钻进)");
        Matcher drillingMatcher = drillingPattern.matcher(record);

        List<LocalTime> allTimePoints = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm");

        // 提取所有时间点
        while (timeMatcher.find()) {
            allTimePoints.add(LocalTime.parse(timeMatcher.group(1), formatter));
        }

        // 查找"钻进"前的时间点及其前一个时间点
        while (drillingMatcher.find()) {
            LocalTime drillingTime = LocalTime.parse(drillingMatcher.group(1), formatter);
            int index = allTimePoints.indexOf(drillingTime);

            if (index > 0) {
                LocalTime previousTime = allTimePoints.get(index - 1);
                if(index>2){
                    LocalTime previousTime2 = allTimePoints.get(index - 2);
                    pairs.add(new TimePointPair(previousTime, drillingTime,previousTime2));
                }else {
                    pairs.add(new TimePointPair(previousTime, drillingTime));
                }


            }
        }

        return pairs;
    }

    public static List<TimePointPair> extractTimePointPairsBeforeDrilling2(String record) {
        List<TimePointPair> pairs = new ArrayList<>();
        record=record.replaceAll("：",":");
        record=record.replaceAll("，",",");
        int zj = record.indexOf("钻进");
        if(zj==-1){
            return pairs;

        }
        record=record.substring(0,zj+2);
        if(StringUtils.isEmpty(record)){
            return pairs;
        }
        // 匹配所有时间点（格式为H:mm）
        Pattern timePattern = Pattern.compile("(\\d+:\\d+)");
        Matcher timeMatcher = timePattern.matcher(record);

        // 匹配"钻进"前的时间点
        Pattern drillingPattern = Pattern.compile("(\\d+:\\d+)(?=钻进)");
        Matcher drillingMatcher = drillingPattern.matcher(record);

        List<LocalTime> allTimePoints = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm");

        // 提取所有时间点
        while (timeMatcher.find()) {
            allTimePoints.add(LocalTime.parse(timeMatcher.group(1), formatter));
        }

        // 查找"钻进"前的时间点及其前一个时间点
        while (drillingMatcher.find()) {
            LocalTime drillingTime = LocalTime.parse(drillingMatcher.group(1), formatter);
            int index = allTimePoints.indexOf(drillingTime);

            if (index > 0) {
                LocalTime previousTime = allTimePoints.get(index - 1);
                if(index>=2){
                    LocalTime previousTime2 = allTimePoints.get(index - 2);
                    pairs.add(new TimePointPair(previousTime, drillingTime,previousTime2));
                }else {
                    pairs.add(new TimePointPair(previousTime, drillingTime));
                }


            }
        }

        return pairs;
    }


    public static void main(String[] args) {
        String record = "13:30-17:00一开钻进-18:00循环钻井液-19:00起钻-20:00下套管准备-23:00下表层套管-1:00固井-3:00侯凝-8:00安装防喷器";

        // 去除所有空白字符（包括空格、制表符、换行符等）
        String cleanedRecord = record.replaceAll("\\s+", "");

        List<TimePointPair> timePointPairs = extractTimePeriodsBeforeDrilling(cleanedRecord);

        System.out.println("钻进字样前的时间点及其前一个时间点：");
        for (TimePointPair pair : timePointPairs) {
            System.out.println("前一个时间点：" + pair.getPreviousTime() +
                    "，钻进时间点：" + pair.getDrillingTime() +
                    "，是否跨天：" + pair.isCrossDay());
        }
    }
    public static List<TimePointPair> extractTimePeriodsBeforeDrilling(String record) {
        List<TimePointPair> pairs = new ArrayList<>();

        // 匹配所有时间点（格式为H:mm）
        Pattern timePattern = Pattern.compile("(\\d+:\\d+)");
        Matcher timeMatcher = timePattern.matcher(record);

        // 匹配"XX钻进"或"钻进"前的时间点
        Pattern drillingPattern = Pattern.compile("(\\d+:\\d+)(?=[^-]*?钻进)");
        Matcher drillingMatcher = drillingPattern.matcher(record);

        List<LocalTime> allTimePoints = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm");

        // 提取所有时间点
        while (timeMatcher.find()) {
            allTimePoints.add(LocalTime.parse(timeMatcher.group(1), formatter));
        }

        // 记录当前匹配的位置
        int currentPosition = 0;

        // 查找"钻进"前的时间点及其前一个时间点
        while (drillingMatcher.find()) {
            String timeStr = drillingMatcher.group(1);
            LocalTime drillingTime = LocalTime.parse(timeStr, formatter);

            // 从当前位置开始查找下一个匹配的时间点
            int index = -1;
            for (int i = currentPosition; i < allTimePoints.size(); i++) {
                if (allTimePoints.get(i).equals(drillingTime)) {
                    index = i;
                    currentPosition = i + 1; // 更新当前位置
                    break;
                }
            }

            if (index > 0) {
                LocalTime previousTime = allTimePoints.get(index - 1);
                if(index>2){
                    LocalTime previousTime2 = allTimePoints.get(index - 2);
                    pairs.add(new TimePointPair(previousTime, drillingTime,previousTime2));
                }else {
                    pairs.add(new TimePointPair(previousTime, drillingTime));
                }

            }
        }

        return pairs;
    }

    public static List<TimePointPair> extractTimePeriodsBeforeDrilling2(String record) {
        List<TimePointPair> pairs = new ArrayList<>();
        record=record.replaceAll("：",":");
        record=record.replaceAll("，",",");
        int zj = record.indexOf("钻进");
        if(zj==-1){
            return pairs;

        }
        record=record.substring(0,zj+2);
        if(StringUtils.isEmpty(record)){
            return pairs;
        }
        // 匹配所有时间点（格式为H:mm）
        Pattern timePattern = Pattern.compile("(\\d+:\\d+)");
        Matcher timeMatcher = timePattern.matcher(record);

        // 匹配"XX钻进"或"钻进"前的时间点
        Pattern drillingPattern = Pattern.compile("(\\d+:\\d+)(?=[^-]*?钻进)");
        Matcher drillingMatcher = drillingPattern.matcher(record);

        List<LocalTime> allTimePoints = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm");

        // 提取所有时间点
        while (timeMatcher.find()) {
            allTimePoints.add(LocalTime.parse(timeMatcher.group(1), formatter));
        }

        // 记录当前匹配的位置
        int currentPosition = 0;

        // 查找"钻进"前的时间点及其前一个时间点
        while (drillingMatcher.find()) {
            String timeStr = drillingMatcher.group(1);
            LocalTime drillingTime = LocalTime.parse(timeStr, formatter);

            // 从当前位置开始查找下一个匹配的时间点
            int index = -1;
            for (int i = currentPosition; i < allTimePoints.size(); i++) {
                if (allTimePoints.get(i).equals(drillingTime)) {
                    index = i;
                    currentPosition = i + 1; // 更新当前位置
                    break;
                }
            }

            if (index > 0) {
                LocalTime previousTime = allTimePoints.get(index - 1);
                if(index>=2){
                    LocalTime previousTime2 = allTimePoints.get(index - 2);
                    pairs.add(new TimePointPair(previousTime, drillingTime,previousTime2));
                }else {
                    pairs.add(new TimePointPair(previousTime, drillingTime));
                }

            }
        }

        return pairs;
    }

    @Override
    public List<DjZjzhfx> getZjzhfxList(CommonParam param) {
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
//            Djjc djjc=djdcInfoMapper.getDjinfoByjh(param.getJh());
//            if(djjc==null){
//                return new ArrayList<>();
//            }else {
//                param.setJdhzb(djjc.getJdhzb());
//                param.setJdzzb(djjc.getJdzzb());
//            }
        }
        List<DjZjzhfx> list= djdcInfoMapper.getZjzhfxList(param);
        DecimalFormat df = new DecimalFormat("#.00");
        for (DjZjzhfx item:list){
            String zjzh = item.getZjzh();
//            if(StringUtils.isNotEmpty(zjzh)){
//                Map<String,Object> map=new HashMap<>();
//                map.put("prompt",zjzh+" 这是一个钻具组合信息，请把这个钻具组合信息拆分成竖表，" +
//                        "字段为钻具名称(zjmc)、型号(xh)、长度(cd),最终输出json格式数据,其他内容不输出," +
//                        "输出内容不换行，只要数据，反斜杠不输出，输出格式为：\"{\\\"data\\\":[{\\\"zjmc\\\":\\\"\\***\\\",\\\"xh\\\":\\\"*\\\",\\\"cd\\\":\\\"*\\\"}]}");
//                Gson gson = new GsonBuilder().setPrettyPrinting().create();
//                String json = gson.toJson(map);
//
//                String url="http://10.68.249.59:33331/api/chat/1";
//
//                String result2 = HttpRequest.post(url).body(json).execute().body();
//                System.out.println(result2);
//                JSONObject jsonObject = JSON.parseObject(result2);
//                Object error = jsonObject.get("error");
//                if(error!=null){
//                    System.out.println("错误信息: " + jsonObject.getString("error"));
//                    continue;
//                }
////                JsonObject elementerror = new Gson().fromJson(result2, JsonObject.class);
////
////                if (isValidString(elementerror, "error")) {
////                    String errorMsg = elementerror.get("error").getAsString();
////                    System.out.println("错误信息: " + errorMsg);
////                    continue;
////                }
//
//
//                // 解析API响应
////                Gson gsonres = new GsonBuilder().setPrettyPrinting().create();
//                JsonObject apiResponse = JsonParser.parseString(result2).getAsJsonObject();
//                // 提取message.content字段
//
//                JsonObject message = apiResponse.getAsJsonObject("message");
//                String content = message.get("content").getAsString();
//
//                // 提取content中的JSON部分（去除Markdown代码块标记）
//                String jsonContent = extractJsonContent(content);
//
//                // 解析并格式化JSON内容
//                JsonElement jsonElement = JsonParser.parseString(jsonContent);
//                String formattedJson = gson.toJson(jsonElement);
//
//                // 输出格式化后的JSON
//                System.out.println(formattedJson);
//
//                // 示例：处理解析后的数据
//                JsonObject dataObject = JsonParser.parseString(jsonContent).getAsJsonObject();
//                JsonArray dataArray = dataObject.getAsJsonArray("data");
//                String zjzhmx="";
//                String tsgj="";
//
//                // 遍历数据数组
//                for (JsonElement element : dataArray) {
//                    JsonObject it = element.getAsJsonObject();
//                    String zjmc = it.get("zjmc").getAsString();
//                    String xh = it.get("xh").getAsString();
//                    String cd = it.get("cd").getAsString();
//                    //判断钻具组合模型
//                    if( zjmc.contains("单弯螺杆") ||  zjmc.contains("无磁钻铤")||  zjmc.contains("加重钻杆")||  zjmc.contains("钻杆")){
//
//                        if(StringUtils.isEmpty(zjzhmx)){
//                            zjzhmx=(xh+"+"+zjmc);
//                        }else {
//                            zjzhmx=zjzhmx+"+"+(xh+"+"+zjmc);
//                        }
//
//                    }
//                    //判断特殊钻具
//                    if( zjmc.contains("随钻扩眼器") ||  zjmc.contains("微偏心扩眼器")||  zjmc.contains("水力振荡器")||  zjmc.contains("修壁器")){
//
//                        if(StringUtils.isEmpty(zjzhmx)){
//                            tsgj=(xh+"+"+zjmc);
//                        }else {
//                            tsgj=tsgj+"+"+(xh+"+"+zjmc);
//                        }
//                    }
//                }
//
//                item.setZjzhmx(zjzhmx);
//                item.setTsgj(tsgj);
//            }

            //查询钻具组合

//            LjZjzhfx ljZjzhfx =new LjZjzhfx();
//            ljZjzhfx.setJh(item.getJh());
//            ljZjzhfx.setKc(item.getKc());
//            List<LjZjzhfx> zjzhfxList = ljZjzhfxMapper.selectLjZjzhfxList(ljZjzhfx);
//            if(zjzhfxList.size()>0){
//                LjZjzhfx ljZjzhfx1 = zjzhfxList.get(0);
//                item.setTsgj(ljZjzhfx1.getTsgj());
//                item.setZjzhmx(ljZjzhfx1.getZjzhmx());
//            }

            //查询进尺和时效
            if(item.getKsjs()!=null && item.getJs()!=null){
                DjZjzhfx djZjzhfx=djdcInfoMapper.getJshaJc(item.getJh(),item.getKsjs(),item.getJs());
                if(djZjzhfx!=null){
                    Double jc = djZjzhfx.getJc();
                    Double jcsjhj = djZjzhfx.getJcsjhj();
                    item.setJc(jc);
                    item.setJcsjhj(jcsjhj);
                    if(jcsjhj>0){
                        double zb =jc/jcsjhj;
                        item.setZb(Double.parseDouble(df.format(zb)));
                    }
                }
            }

        }


        return list;
    }

    @Override
    public AjaxResult getLjjwList(CommonParam param) {

        if(StringUtils.isNotEmpty(param.getJh())){
            Jsba jsba = jsbaMapper.selectJsbaByJh(param.getJh());
            if(jsba!=null){
                if(jsba.getJkhzb()!=null && jsba.getJkhzb()!=null){
                    param.setJkhzb(jsba.getJkhzb());
                    param.setJkzzb(jsba.getJkzzb());
                }else {
                    if(jsba.getJdhzb()!=null && jsba.getJdhzb()!=null){
                        param.setJkhzb(jsba.getJdhzb());
                        param.setJkzzb(jsba.getJdhzb());
                    }else {
                        return AjaxResult.error("未查询到井坐标信息");
                    }
                }
                if(jsba.getJdhzb()!=null && jsba.getJdhzb()!=null){
                    param.setJdhzb(jsba.getJdhzb());
                    param.setJdzzb(jsba.getJdzzb());
                }else {
                    param.setJdhzb(jsba.getJkhzb());
                    param.setJdzzb(jsba.getJkzzb());
                }




            }else {
                return  AjaxResult.error("未查询到井数据");
            }
        }


        List<Ljjw> ljjwList = djdcInfoMapper.getLjjwList(param);
        return AjaxResult.success(ljjwList);
    }

    @Override
    public List<Jsfa> getJsfaList(CommonParam param) {

        return null;
    }

    @Override
    public List<Jsqa> getJsqaList(CommonParam param) {
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
//            Djjc djjc=djdcInfoMapper.getDjinfoByjh(param.getJh());
//            if(djjc==null){
//                return new ArrayList<>();
//            }else {
//                param.setJdhzb(djjc.getJdhzb());
//                param.setJdzzb(djjc.getJdzzb());
//            }
        }
        return jsqaMapper.getJsqaList(param);
    }

    @Override
    public List<DjZtfx> getDjZtfxList(CommonParam param) {
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
        }
        return djdcInfoMapper.getDjZtfxList(param);
    }

    @Override
    public Map<String,Object> calZtzhdf(CommonParam param) {

        Map<String,Object> map = new HashMap<>();
        List<LjZtzhdf> ljZtzhdfList=new ArrayList<>();
        List<LjSzfxjg> ljSzfxjgList=new ArrayList<>();
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
        }
        //根据qk获取钻头分析
        List<DjZtfx> djZtfxList = djdcInfoMapper.getDjZtfxList(param);
        //根据井号取钻头关键数据
//        List<Djjc> djjcList = getDjjcList(param);

        DecimalFormat df = new DecimalFormat("#.00");
        List<SjInfo> sjInfoList = param.getSj();


        for(SjInfo info :sjInfoList){
            List<SjInfo> reList =new ArrayList<>();

            //钻头分析模块
            List<DjZtfx> collect = djZtfxList.stream().filter(ztfx -> equals(ztfx.getCc(), info.getZtcc()) && info.getKc().equals(ztfx.getKc())).collect(Collectors.toList());
            //按使用数量排序
            List<DjZtfx> ztslList=collect.stream()
                    .sorted(Comparator.comparingInt(DjZtfx::getZtsl).reversed()).collect(Collectors.toList());
            int size=0;
            if(ztslList.size()>3){
                size=3;
            }else {
                size=ztslList.size();
            }
            int ztsl=0;
            for(int i =0;i<size;i++){
                DjZtfx djZtfx = ztslList.get(i);
                SjInfo sjInfo=new SjInfo();
                sjInfo.setKc(djZtfx.getKc());
                sjInfo.setZtcc(djZtfx.getCc());
                sjInfo.setZtxh(djZtfx.getZtxh());
                sjInfo.setJc(djZtfx.getJcZw());
                sjInfo.setJs(djZtfx.getJxzsZw());
                sjInfo.setZb(0.0);
                sjInfo.setSl(djZtfx.getZtsl());
                sjInfo.setGnmk("钻头分析区块");
                sjInfo.setYtzl(djZtfx.getYtzl());
                ztsl=djZtfx.getZtsl();
                reList.add(sjInfo);
            }
            if(size==3){
                for(int i =3;i<ztslList.size();i++){
                    DjZtfx djZtfx = ztslList.get(i);
                    if(ztsl==djZtfx.getZtsl()){
                        SjInfo sjInfo=new SjInfo();
                        sjInfo.setKc(djZtfx.getKc());
                        sjInfo.setZtcc(djZtfx.getCc());
                        sjInfo.setZtxh(djZtfx.getZtxh());
                        sjInfo.setJc(djZtfx.getJcZw());
                        sjInfo.setJs(djZtfx.getJxzsZw());
                        sjInfo.setZb(0.0);
                        sjInfo.setSl(djZtfx.getZtsl());
                        sjInfo.setGnmk("钻头分析区块");
                        sjInfo.setYtzl(djZtfx.getYtzl());
                        reList.add(sjInfo);
                        ztsl=djZtfx.getZtsl();
                    }
                }
            }




            //按一趟钻率排序
            List<DjZtfx> zjlList=collect.stream()
                    .sorted(Comparator.comparingDouble(DjZtfx::getYtzl).reversed()).collect(Collectors.toList());
            if(zjlList.size()>3){
                size=3;
            }else {
                size=zjlList.size();
            }
            Double ytzl=0.0;
            for(int i =0;i<size;i++){
                DjZtfx djZtfx = zjlList.get(i);
                SjInfo sjInfo=new SjInfo();
                sjInfo.setKc(djZtfx.getKc());
                sjInfo.setZtcc(djZtfx.getCc());
                sjInfo.setZtxh(djZtfx.getZtxh());
                sjInfo.setJc(djZtfx.getJcZw());
                sjInfo.setJs(djZtfx.getJxzsZw());
                sjInfo.setZb(0.0);
                sjInfo.setSl(djZtfx.getZtsl());
                sjInfo.setGnmk("钻头分析区块");
                sjInfo.setYtzl(djZtfx.getYtzl());
                ytzl=djZtfx.getYtzl();
                reList.add(sjInfo);
            }

            if(size==3){
                for(int i =3;i<ztslList.size();i++){
                    DjZtfx djZtfx = ztslList.get(i);
                    if( equals(ytzl, djZtfx.getYtzl())){
                        SjInfo sjInfo=new SjInfo();
                        sjInfo.setKc(djZtfx.getKc());
                        sjInfo.setZtcc(djZtfx.getCc());
                        sjInfo.setZtxh(djZtfx.getZtxh());
                        sjInfo.setJc(djZtfx.getJcZw());
                        sjInfo.setJs(djZtfx.getJxzsZw());
                        sjInfo.setZb(0.0);
                        sjInfo.setSl(djZtfx.getZtsl());
                        sjInfo.setGnmk("钻头分析区块");
                        sjInfo.setYtzl(djZtfx.getYtzl());
                        reList.add(sjInfo);
                        ytzl=djZtfx.getYtzl();
                    }
                }
            }

            List<SjInfo> collect1 = reList.stream().distinct().collect(Collectors.toList());



            //计算得分
            calculateScores(collect1);

            // 按进尺降序排序
            List<SjInfo> jcSorted = collect1.stream()
                    .sorted(Comparator.comparingDouble(SjInfo::getJc).reversed())
                    .collect(Collectors.toList());

            LjSzfxjg ljSzfxjg=new LjSzfxjg();
            ljSzfxjg.setGnmk("钻头分析区块");
            ljSzfxjg.setFxfw(info.getKc()+"开");
            ljSzfxjg.setFxdx("钻头使用");
            ljSzfxjg.setScfx("钻头选型");
            ljSzfxjg.setYxyj("进尺最高");
            if(jcSorted.size()>=2){
                SjInfo sjInfo = jcSorted.get(0);
                SjInfo sjInfo2 = jcSorted.get(1);
                ljSzfxjg.setFxxy("钻头进尺最高是"+sjInfo.getZtxh()+"（"+sjInfo.getSl()+"只）、进尺"+sjInfo.getJc()+"、一趟钻率（"+sjInfo.getYtzl()+"%），其次钻头进尺最高是"+sjInfo2.getZtxh()+"（"+sjInfo2.getSl()+"只），进尺"+sjInfo2.getJc()+"、一趟钻率（"+sjInfo2.getYtzl()+"%）");
                ljSzfxjg.setZyjy(sjInfo.getZtxh());
                ljSzfxjg.setQcyj(sjInfo2.getZtxh());
                ljSzfxjg.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }else if(jcSorted.size()==1){
                SjInfo sjInfo = jcSorted.get(0);
                ljSzfxjg.setFxxy("钻头进尺最高是"+sjInfo.getZtxh()+"（"+sjInfo.getSl()+"只）、进尺"+sjInfo.getJc()+"、一趟钻率（"+sjInfo.getYtzl()+"%）");
                ljSzfxjg.setZyjy(sjInfo.getZtxh());
                ljSzfxjg.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }
            ljSzfxjgList.add(ljSzfxjg);

            // 按机速降序排序
            List<SjInfo> jsSorted = collect1.stream()
                    .sorted(Comparator.comparingDouble(SjInfo::getJs).reversed())
                    .collect(Collectors.toList());
            LjSzfxjg ljSzfxjgjs=new LjSzfxjg();
            ljSzfxjgjs.setGnmk("钻头分析区块");
            ljSzfxjgjs.setFxfw(info.getKc()+"开");
            ljSzfxjgjs.setFxdx("钻头使用");
            ljSzfxjgjs.setScfx("钻头选型");
            ljSzfxjgjs.setYxyj("机速最快");
            if(jsSorted.size()>=2){
                SjInfo sjInfo = jsSorted.get(0);
                SjInfo sjInfo2 = jsSorted.get(1);
                ljSzfxjgjs.setFxxy("钻头机速最快是"+sjInfo.getZtxh()+"（"+sjInfo.getSl()+"只）、机械转速为"+sjInfo.getJs()+"、一趟钻率（"+sjInfo.getYtzl()+"%），其次钻头数量使用最多是"+sjInfo2.getZtxh()+"（"+sjInfo2.getSl()+"只），机械转速为"+sjInfo2.getJs()+"、一趟钻率（"+sjInfo2.getYtzl()+"%）");
                ljSzfxjgjs.setZyjy(sjInfo.getZtxh());
                ljSzfxjgjs.setQcyj(sjInfo2.getZtxh());
                ljSzfxjgjs.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }else if(jsSorted.size()==1){
                SjInfo sjInfo = jsSorted.get(0);
                ljSzfxjgjs.setFxxy("钻头机速最快是"+sjInfo.getZtxh()+"（"+sjInfo.getSl()+"只）、机械转速为"+sjInfo.getJs()+"、一趟钻率（"+sjInfo.getYtzl()+"%）");
                ljSzfxjgjs.setZyjy(sjInfo.getZtxh());
                ljSzfxjgjs.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }
            ljSzfxjgList.add(ljSzfxjgjs);
            // 按数量降序排序
            List<SjInfo> slSorted = collect1.stream()
                    .sorted(Comparator.comparingInt(SjInfo::getSl).reversed())
                    .collect(Collectors.toList());

            LjSzfxjg ljSzfxjgSl=new LjSzfxjg();
            ljSzfxjgSl.setGnmk("钻头分析区块");
            ljSzfxjgSl.setFxfw(info.getKc()+"开");
            ljSzfxjgSl.setFxdx("钻头使用");
            ljSzfxjgSl.setScfx("钻头选型");
            ljSzfxjgSl.setYxyj("数量最多");
            if(slSorted.size()>=2){
                SjInfo sjInfo = slSorted.get(0);
                SjInfo sjInfo2 = slSorted.get(1);
                ljSzfxjgSl.setFxxy("钻头数量使用最多是"+sjInfo.getZtxh()+"（"+sjInfo.getSl()+"只）、一趟钻率（"+sjInfo.getYtzl()+"%），其次钻头数量使用最多是"+sjInfo2.getZtxh()+"（"+sjInfo2.getSl()+"只），一趟钻率（"+sjInfo2.getYtzl()+"%）");
                ljSzfxjgSl.setZyjy(sjInfo.getZtxh());
                ljSzfxjgSl.setQcyj(sjInfo2.getZtxh());
                ljSzfxjgSl.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }else if(slSorted.size()==1){
                SjInfo sjInfo = slSorted.get(0);
                ljSzfxjgSl.setFxxy("钻头数量使用最多是"+sjInfo.getZtxh()+"、一趟钻率（"+sjInfo.getYtzl()+"%）");
                ljSzfxjgSl.setZyjy(sjInfo.getZtxh());
                ljSzfxjgSl.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }
            ljSzfxjgList.add(ljSzfxjgSl);

            //钻头关键数据（匹配数据）
            List<SjInfo> collect3=new ArrayList<>();
//            List<Djjc> ztppList = djjcList.stream().filter(dj -> equals(dj.getZtcc(),info.getZtcc() )  && info.getKc().equals(dj.getKc())).collect(Collectors.toList());
//            ztppList.forEach(ztpp->{
//                SjInfo sjInfo=new SjInfo();
//                sjInfo.setKc(ztpp.getKc());
//                sjInfo.setZtcc(ztpp.getZtcc());
//                sjInfo.setZtxh(ztpp.getZtxh());
//                sjInfo.setJc(ztpp.getJc()==null?0.0:ztpp.getJc());
//                sjInfo.setJs(ztpp.getJxzs() ==null?0.0:ztpp.getJxzs());
//                sjInfo.setZb(ztpp.getZb());
//                sjInfo.setSl(1);
//                sjInfo.setGnmk("钻头关键数据");
//                collect3.add(sjInfo);
//            });

//            calculateScores(collect3);
//            collect1.addAll(collect3);
            for(SjInfo sjInfodf:collect1){
                LjZtzhdf ljZtzhdf=new LjZtzhdf();
                ljZtzhdf.setKc(sjInfodf.getKc());
                ljZtzhdf.setZtxh(sjInfodf.getZtxh());
                ljZtzhdf.setCc(sjInfodf.getZtcc());
                ljZtzhdf.setJcdf(sjInfodf.getJcScore());
                ljZtzhdf.setJsdf(sjInfodf.getJsScore());
                ljZtzhdf.setZbdf(sjInfodf.getZbScore());
                ljZtzhdf.setSldf(sjInfodf.getSlScore());
                ljZtzhdf.setZhdf(Double.parseDouble(df.format(sjInfodf.getTotalScore())));
                if(ljZtzhdf.getZhdf()>0){
                    ljZtzhdfList.add(ljZtzhdf);
                }
            }
        }
        List<LjZtdfzh> ljZtdfzhList= new ArrayList<>();
        //去重
        if(ljZtzhdfList.size()>0){
            ljZtzhdfList=ljZtzhdfList.stream().distinct().collect(Collectors.toList());
            int i=ljZtzhdfMapper.batchLjZtzhdf(ljZtzhdfList);


            for(LjZtzhdf item:ljZtzhdfList){
                LjZtdfzh ljZtdfzh=new LjZtdfzh();
                ljZtdfzh.setKc(item.getKc());
                ljZtdfzh.setZtxh(item.getZtxh());
                ljZtdfzh.setCc(item.getCc());
                ljZtdfzh.setJcdf(Double.parseDouble(df.format(item.getJcdf()+(item.getJsdf()*0.25))));
                ljZtdfzh.setJsdf(Double.parseDouble(df.format(item.getJsdf()+(item.getJcdf()*0.25))));
                ljZtdfzh.setZhdf(Double.parseDouble(df.format((item.getJcdf()*0.5)+(item.getJsdf()*0.5)+item.getSldf())));
                ljZtdfzhMapper.insertLjZtdfzh(ljZtdfzh);
                ljZtdfzhList.add(ljZtdfzh);
            }

        }
        if(ljSzfxjgList.size()>0){
            int i=ljSzfxjgMapper.batchLjSzfxjg(ljSzfxjgList);
        }

        //钻头综合得分
        map.put("ztzhdf",ljZtzhdfList);
        //实钻分析结果
        map.put("szfxjg",ljSzfxjgList);
        //钻头最终得分
        map.put("zjzhdf",ljZtdfzhList);
        return map ;
    }

    @Override
    public List<LjZtzhdf> getzhzhdfList(CommonParam param) {

        return ljZtzhdfMapper.selectLjZtzhdfListByCom(param);
    }

    @Override
    public List<LjSzfxjg> getszfxjgList(CommonParam param) {
        return ljSzfxjgMapper.getszfxjgList(param);
    }

    @Override
    public List<LjZtdfzh> getZtzhzzdfList(CommonParam param) {
        return ljZtdfzhMapper.getZtzhzzdfList(param);
    }

    @Override
    public int dyAiModelJxZjzh(CommonParam param) {
        List<DjZjzhfx> list = djdcInfoMapper.getZjzhfxList(param);
        int batchSize = 4;
        // 计算批次数
        int numBatches = (int) Math.ceil((double) list.size() / batchSize);

        List<LjZjzhfx> zjzhfxList=new ArrayList<>();

        List<List<DjZjzhfx>> collect = IntStream.range(0, numBatches)
                .mapToObj(i -> {
                    int start = i * batchSize;
                    int end = Math.min(start + batchSize, list.size());
                    return list.subList(start, end);
                }).collect(Collectors.toList());

        for(List<DjZjzhfx> djZjzhfxes:collect){
            for(DjZjzhfx item:djZjzhfxes){
                String jh = item.getJh();
                String kc = item.getKc();
                LjZjzhfx ljZjzhfx =new LjZjzhfx();
                ljZjzhfx.setJh(jh);
                ljZjzhfx.setKc(kc);
                List<LjZjzhfx> zjzhfxList1 = ljZjzhfxMapper.selectLjZjzhfxList(ljZjzhfx);
                if(zjzhfxList1.size()==0) {
                    String zjzh = item.getZjzh();
                    if (StringUtils.isNotEmpty(zjzh)) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("prompt", zjzh + " 这是一个钻具组合信息，请把这个钻具组合信息拆分成竖表，" +
                                "字段为钻具名称(zjmc)、型号(xh)、长度(cd),最终输出json格式数据,其他内容不输出," +
                                "输出内容不换行，只要数据，反斜杠不输出，输出格式为：\"{\\\"data\\\":[{\\\"zjmc\\\":\\\"\\***\\\",\\\"xh\\\":\\\"*\\\",\\\"cd\\\":\\\"*\\\"}]}");
                        Gson gson = new GsonBuilder().setPrettyPrinting().create();
                        String json = gson.toJson(map);

                        String url = "http://10.68.249.59:33331/api/chat/1";

                        String result2 = HttpRequest.post(url).body(json).execute().body();
                        System.out.println(result2);
                        JSONObject jsonObject = JSON.parseObject(result2);
                        Object error = jsonObject.get("error");
                        if (error != null) {
                            System.out.println("错误信息: " + jsonObject.getString("error"));
                            continue;
                        }

                        // 解析API响应
//                        Gson gsonres = new GsonBuilder().setPrettyPrinting().create();
                        JsonObject apiResponse = JsonParser.parseString(result2).getAsJsonObject();
                        // 提取message.content字段

                        JsonObject message = apiResponse.getAsJsonObject("message");
                        String content = message.get("content").getAsString();

                        // 提取content中的JSON部分（去除Markdown代码块标记）
                        String jsonContent = extractJsonContent(content);


                        // 解析并格式化JSON内容
                        JsonReader reader = new JsonReader(new StringReader(jsonContent));
                        reader.setLenient(true);
                        JsonElement jsonElement = JsonParser.parseReader(reader);
//                        JsonElement jsonElement = JsonParser.parseString(jsonContent);
                        String formattedJson = gson.toJson(jsonElement);

                        // 输出格式化后的JSON
                        System.out.println(formattedJson);

                        // 示例：处理解析后的数据
                        JsonObject dataObject = JsonParser.parseString(jsonContent).getAsJsonObject();
                        JsonArray dataArray = dataObject.getAsJsonArray("data");
                        String zjzhmx = "";
                        String tsgj = "";

                        // 遍历数据数组
                        for (JsonElement element : dataArray) {
                            JsonObject it = element.getAsJsonObject();
                            String zjmc="";
                            System.out.println(it.get("zjmc"));
                            if(it.get("zjmc")!=null){
                                zjmc=it.get("zjmc")+"";
                            }
                            String xh ="";
                            System.out.println(it.get("xh"));
                            if(it.get("xh")!=null){
                                xh = it.get("xh")+"";
                            }
//                            String
//                            String cd = it.get("cd").getAsString();
                            //判断钻具组合模型
                            if (zjmc.contains("单弯螺杆") || zjmc.contains("无磁钻铤") || zjmc.contains("加重钻杆") || zjmc.contains("钻杆")) {

                                if (StringUtils.isEmpty(zjzhmx)) {
                                    zjzhmx = (xh + "+" + zjmc);
                                } else {
                                    zjzhmx = zjzhmx + "+" + (xh + "+" + zjmc);
                                }

                            }
                            //判断特殊钻具
                            if (zjmc.contains("随钻扩眼器") || zjmc.contains("微偏心扩眼器") || zjmc.contains("水力振荡器") || zjmc.contains("修壁器")) {

                                if (StringUtils.isEmpty(zjzhmx)) {
                                    tsgj = (xh + "+" + zjmc);
                                } else {
                                    tsgj = tsgj + "+" + (xh + "+" + zjmc);
                                }
                            }
                        }

                        LjZjzhfx zjzhfx=new LjZjzhfx();
                        zjzhfx.setZjzhmx(zjzhmx);
                        zjzhfx.setTsgj(tsgj);
                        zjzhfx.setZjzh(zjzh);
                        zjzhfx.setJh(jh);
                        zjzhfx.setKc(kc);
                        ljZjzhfxMapper.insertLjZjzhfx(zjzhfx);
//                        zjzhfxList.add(zjzhfx);
                    }
                }
            }
            try {
                Thread.sleep(1000); // 每次循环暂停1秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(zjzhfxList.size()>0){
            int i = ljZjzhfxMapper.batchLjZjzhfx(zjzhfxList);
            return i;
        }else {
            return 0;
        }

    }

    @Override
    public List<LjDzfc> getDzfcList(CommonParam param) {

        List<LjDzfc> list =new ArrayList<>();
        SjDzfc sjDzfc =new SjDzfc();
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            sjDzfc.setJhs(jhs);
        }


        //查询设计井信息
        List<SjDzfc> sjDzfcs = sjDzfcMapper.selectSjDzfcList(sjDzfc);
        for(SjDzfc item :sjDzfcs){
            LjDzfc ljDzfc =new LjDzfc();
            ljDzfc.setJh( item.getSjjh());
            ljDzfc.setCs(item.getSjdcs());
            ljDzfc.setDzfc(item.getDcZ());
            if(StringUtils.isNotEmpty(item.getSjyxts())){
                ljDzfc.setYxts(item.getSjyxts());
            }else {
                //查询邻井
                CommonParam paramYj=new CommonParam();
                String[] jhs={item.getYjjh1(),item.getYjjh2()};
                paramYj.setJhs(jhs);
                List<LjDcyx> dcyxList = ljQueryMapper.getDcyxList(paramYj);
                List<LjDcyx> collect = dcyxList.stream().filter(lj -> lj.getJh().equals(item.getYjjh1()) && equals(lj.getDjsd2(), item.getYjdcs1())).collect(Collectors.toList());
                List<LjDcyx> colect2 = dcyxList.stream().filter(lj -> lj.getJh().equals(item.getYjjh2()) && equals(lj.getDjsd2(), item.getYjdcs2())).collect(Collectors.toList());
                List<String> yxmclist=new ArrayList<>();
                List<String> yqsmclist=new ArrayList<>();
                if(colect2.size()>0){
                    List<LjDcyx> ysisNotnull = colect2.stream().filter(it -> StringUtils.isNotEmpty(it.getYxmc())).collect(Collectors.toList());
                    if(ysisNotnull.size()>0){
                        yxmclist.addAll(ysisNotnull.stream().map(LjDcyx::getYxmc).distinct().collect(Collectors.toList()));
                    }
                    List<LjDcyx> yqsisNotnull = colect2.stream().filter(it -> StringUtils.isNotEmpty(it.getYqcmc())).collect(Collectors.toList());
                    if(yqsisNotnull.size()>0){
                        yqsmclist.addAll(yqsisNotnull.stream().map(LjDcyx::getYqcmc).distinct().collect(Collectors.toList()));
                    }
                }
                if(collect.size()>0){
                    List<LjDcyx> ysisNotnull = collect.stream().filter(it -> StringUtils.isNotEmpty(it.getYxmc())).collect(Collectors.toList());
                    if(ysisNotnull.size()>0){
                        yxmclist.addAll(ysisNotnull.stream().map(LjDcyx::getYxmc).distinct().collect(Collectors.toList()));
                    }
                    List<LjDcyx> yqsisNotnull = collect.stream().filter(it -> StringUtils.isNotEmpty(it.getYqcmc())).collect(Collectors.toList());
                    if(yqsisNotnull.size()>0){
                        yqsmclist.addAll(yqsisNotnull.stream().map(LjDcyx::getYqcmc).distinct().collect(Collectors.toList()));
                    }
                }
                if(yxmclist.size()>0){
                    ljDzfc.setYxts(String.join(",",yxmclist));
                }else {
                    //查询构造表
                    Dzgzzb dzgzzb= new Dzgzzb();
                    dzgzzb.setDzfc(item.getDcZ());
                    List<Dzgzzb> dzgzzbs = dzgzzbMapper.selectDzgzzbList(dzgzzb);
                    if(dzgzzbs.size()>0){
                        Dzgzzb dzgzzb1 = dzgzzbs.get(0);
                        ljDzfc.setYxts(dzgzzb1.getZyyx());
                    }
                }
                if(yqsmclist.size()>0){
                    ljDzfc.setYqsts(String.join(",",yqsmclist));
                }
                if(StringUtils.isNotEmpty(ljDzfc.getYxts())){
                    String[] split = ljDzfc.getYxts().split("、");
                    Tsyxclxx tsyxclxx =new Tsyxclxx();

                    tsyxclxx.setTsyxs(split);
                    List<Tsyxclxx> tsyxclxxes = tsyxclxxMapper.selectTsyxclxxList(tsyxclxx);
                    if(tsyxclxxes.size()>0){
                        List<String> collect1 = tsyxclxxes.stream().map(Tsyxclxx::getWt).collect(Collectors.toList());
                        ljDzfc.setGzts(String.join(",",collect1));
                    }
                }
            }




            list.add(ljDzfc);
        }


        return list;
    }

    @Override
    public List<LjSzfxjg> getSztfxjgList(List<DjZtfx> djZtfxList, List<Djjc> djjcList, CommonParam param) {
        Map<String,Object> map = new HashMap<>();
        List<LjSzfxjg> ljSzfxjgList=new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#.00");
        List<SjInfo> sjInfoList = param.getSj();



        for(SjInfo info :sjInfoList){
            List<SjInfo> reList =new ArrayList<>();

            //钻头分析模块
            List<DjZtfx> collect = djZtfxList.stream().filter(ztfx -> equals(ztfx.getCc(), info.getZtcc()) && info.getKc().equals(ztfx.getKc())).collect(Collectors.toList());
            //按使用数量排序
            List<DjZtfx> ztslList=collect.stream()
                    .sorted(Comparator.comparingInt(DjZtfx::getZtsl).reversed()).collect(Collectors.toList());
            int size=0;
            if(ztslList.size()>3){
                size=3;
            }else {
                size=ztslList.size();
            }
            int ztsl=0;
            for(int i =0;i<size;i++){
                DjZtfx djZtfx = ztslList.get(i);
                SjInfo sjInfo=new SjInfo();
                sjInfo.setKc(djZtfx.getKc());
                sjInfo.setZtcc(djZtfx.getCc());
                sjInfo.setZtxh(djZtfx.getZtxh());
                sjInfo.setJc(djZtfx.getJcZw());
                sjInfo.setJs(djZtfx.getJxzsZw());
                sjInfo.setZb(0.0);
                sjInfo.setSl(djZtfx.getZtsl());
                sjInfo.setGnmk("钻头分析区块");
                sjInfo.setYtzl(djZtfx.getYtzl());
                ztsl=djZtfx.getZtsl();
                reList.add(sjInfo);
            }
            if(size==3){
                for(int i =3;i<ztslList.size();i++){
                    DjZtfx djZtfx = ztslList.get(i);
                    if(ztsl==djZtfx.getZtsl()){
                        SjInfo sjInfo=new SjInfo();
                        sjInfo.setKc(djZtfx.getKc());
                        sjInfo.setZtcc(djZtfx.getCc());
                        sjInfo.setZtxh(djZtfx.getZtxh());
                        sjInfo.setJc(djZtfx.getJcZw());
                        sjInfo.setJs(djZtfx.getJxzsZw());
                        sjInfo.setZb(0.0);
                        sjInfo.setSl(djZtfx.getZtsl());
                        sjInfo.setGnmk("钻头分析区块");
                        sjInfo.setYtzl(djZtfx.getYtzl());
                        reList.add(sjInfo);
                        ztsl=djZtfx.getZtsl();
                    }
                }
            }
            //按一趟钻率排序
            List<DjZtfx> zjlList=collect.stream()
                    .sorted(Comparator.comparingDouble(DjZtfx::getYtzl).reversed()).collect(Collectors.toList());
            if(zjlList.size()>3){
                size=3;
            }else {
                size=zjlList.size();
            }
            Double ytzl=0.0;
            for(int i =0;i<size;i++){
                DjZtfx djZtfx = zjlList.get(i);
                SjInfo sjInfo=new SjInfo();
                sjInfo.setKc(djZtfx.getKc());
                sjInfo.setZtcc(djZtfx.getCc());
                sjInfo.setZtxh(djZtfx.getZtxh());
                sjInfo.setJc(djZtfx.getJcZw());
                sjInfo.setJs(djZtfx.getJxzsZw());
                sjInfo.setZb(0.0);
                sjInfo.setSl(djZtfx.getZtsl());
                sjInfo.setGnmk("钻头分析区块");
                sjInfo.setYtzl(djZtfx.getYtzl());
                ytzl=djZtfx.getYtzl();
                reList.add(sjInfo);
            }

            if(size==3){
                for(int i =3;i<ztslList.size();i++){
                    DjZtfx djZtfx = ztslList.get(i);
                    if( equals(ytzl, djZtfx.getYtzl())){
                        SjInfo sjInfo=new SjInfo();
                        sjInfo.setKc(djZtfx.getKc());
                        sjInfo.setZtcc(djZtfx.getCc());
                        sjInfo.setZtxh(djZtfx.getZtxh());
                        sjInfo.setJc(djZtfx.getJcZw());
                        sjInfo.setJs(djZtfx.getJxzsZw());
                        sjInfo.setZb(0.0);
                        sjInfo.setSl(djZtfx.getZtsl());
                        sjInfo.setGnmk("钻头分析区块");
                        sjInfo.setYtzl(djZtfx.getYtzl());
                        reList.add(sjInfo);
                        ytzl=djZtfx.getYtzl();
                    }
                }
            }

            List<SjInfo> collect1 = reList.stream().distinct().collect(Collectors.toList());
            //计算得分
            calculateScores(collect1);

            // 按进尺降序排序
            List<SjInfo> jcSorted = collect1.stream()
                    .sorted(Comparator.comparingDouble(SjInfo::getJc).reversed())
                    .collect(Collectors.toList());

            LjSzfxjg ljSzfxjg=new LjSzfxjg();
            ljSzfxjg.setGnmk("钻头分析区块");
            ljSzfxjg.setFxfw(info.getKc()+"开");
            ljSzfxjg.setFxdx("钻头使用");
            ljSzfxjg.setScfx("钻头选型");
            ljSzfxjg.setYxyj("进尺最高");
            if(jcSorted.size()>=2){
                SjInfo sjInfo = jcSorted.get(0);
                SjInfo sjInfo2 = jcSorted.get(1);
                ljSzfxjg.setFxxy("钻头进尺最高是"+sjInfo.getZtxh()+"（"+sjInfo.getSl()+"只）、进尺"+sjInfo.getJc()+"、一趟钻率（"+sjInfo.getYtzl()+"%），其次钻头进尺最高是"+sjInfo2.getZtxh()+"（"+sjInfo2.getSl()+"只），进尺"+sjInfo2.getJc()+"、一趟钻率（"+sjInfo2.getYtzl()+"%）");
                ljSzfxjg.setZyjy(sjInfo.getZtxh());
                ljSzfxjg.setQcyj(sjInfo2.getZtxh());
                ljSzfxjg.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }else if(jcSorted.size()==1){
                SjInfo sjInfo = jcSorted.get(0);
                ljSzfxjg.setFxxy("钻头进尺最高是"+sjInfo.getZtxh()+"（"+sjInfo.getSl()+"只）、进尺"+sjInfo.getJc()+"、一趟钻率（"+sjInfo.getYtzl()+"%）");
                ljSzfxjg.setZyjy(sjInfo.getZtxh());
                ljSzfxjg.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }
            ljSzfxjgList.add(ljSzfxjg);

            // 按机速降序排序
            List<SjInfo> jsSorted = collect1.stream()
                    .sorted(Comparator.comparingDouble(SjInfo::getJs).reversed())
                    .collect(Collectors.toList());
            LjSzfxjg ljSzfxjgjs=new LjSzfxjg();
            ljSzfxjgjs.setGnmk("钻头分析区块");
            ljSzfxjgjs.setFxfw(info.getKc()+"开");
            ljSzfxjgjs.setFxdx("钻头使用");
            ljSzfxjgjs.setScfx("钻头选型");
            ljSzfxjgjs.setYxyj("机速最快");
            if(jsSorted.size()>=2){
                SjInfo sjInfo = jsSorted.get(0);
                SjInfo sjInfo2 = jsSorted.get(1);
                ljSzfxjgjs.setFxxy("钻头机速最快是"+sjInfo.getZtxh()+"（"+sjInfo.getSl()+"只）、机械转速为"+sjInfo.getJs()+"、一趟钻率（"+sjInfo.getYtzl()+"%），其次钻头数量使用最多是"+sjInfo2.getZtxh()+"（"+sjInfo2.getSl()+"只），机械转速为"+sjInfo2.getJs()+"、一趟钻率（"+sjInfo2.getYtzl()+"%）");
                ljSzfxjgjs.setZyjy(sjInfo.getZtxh());
                ljSzfxjgjs.setQcyj(sjInfo2.getZtxh());
                ljSzfxjgjs.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }else if(jsSorted.size()==1){
                SjInfo sjInfo = jsSorted.get(0);
                ljSzfxjgjs.setFxxy("钻头机速最快是"+sjInfo.getZtxh()+"（"+sjInfo.getSl()+"只）、机械转速为"+sjInfo.getJs()+"、一趟钻率（"+sjInfo.getYtzl()+"%）");
                ljSzfxjgjs.setZyjy(sjInfo.getZtxh());
                ljSzfxjgjs.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }
            ljSzfxjgList.add(ljSzfxjgjs);
            // 按数量降序排序
            List<SjInfo> slSorted = collect1.stream()
                    .sorted(Comparator.comparingInt(SjInfo::getSl).reversed())
                    .collect(Collectors.toList());

            LjSzfxjg ljSzfxjgSl=new LjSzfxjg();
            ljSzfxjgSl.setGnmk("钻头分析区块");
            ljSzfxjgSl.setFxfw(info.getKc()+"开");
            ljSzfxjgSl.setFxdx("钻头使用");
            ljSzfxjgSl.setScfx("钻头选型");
            ljSzfxjgSl.setYxyj("数量最多");
            if(slSorted.size()>=2){
                SjInfo sjInfo = slSorted.get(0);
                SjInfo sjInfo2 = slSorted.get(1);
                ljSzfxjgSl.setFxxy("钻头数量使用最多是"+sjInfo.getZtxh()+"（"+sjInfo.getSl()+"只）、一趟钻率（"+sjInfo.getYtzl()+"%），其次钻头数量使用最多是"+sjInfo2.getZtxh()+"（"+sjInfo2.getSl()+"只），一趟钻率（"+sjInfo2.getYtzl()+"%）");
                ljSzfxjgSl.setZyjy(sjInfo.getZtxh());
                ljSzfxjgSl.setQcyj(sjInfo2.getZtxh());
                ljSzfxjgSl.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }else if(slSorted.size()==1){
                SjInfo sjInfo = slSorted.get(0);
                ljSzfxjgSl.setFxxy("钻头数量使用最多是"+sjInfo.getZtxh()+"、一趟钻率（"+sjInfo.getYtzl()+"%）");
                ljSzfxjgSl.setZyjy(sjInfo.getZtxh());
                ljSzfxjgSl.setTjpf(Double.parseDouble(df.format(sjInfo.getTotalScore())));
            }
            ljSzfxjgList.add(ljSzfxjgSl);
        }


        return ljSzfxjgList;
    }

    @Override
    public List<Jsha> getFdcsList(CommonParam param) {
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
        }
        List<Jsha> jshaList=djdcInfoMapper.getFdcsList(param);
        return jshaList;
    }

    @Override
    public List<SjDcfxDzfc> getDzfcList2(CommonParam param) {
        List<SjDcfxDzfc> list =new ArrayList<>();
        SjDzfc sjDzfc =new SjDzfc();
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            sjDzfc.setJhs(jhs);
        }


        //查询设计井信息
        List<SjDzfc> sjDzfcs = sjDzfcMapper.selectSjDzfcList(sjDzfc);

        SjJygjGdsjgdcs sjJygjGdsjgdcs =new SjJygjGdsjgdcs();
        sjJygjGdsjgdcs.setJh(param.getJh());
        List<SjJygjGdsjgdcs> sjJygjGdsjgdcsList = sjJygjGdsjgdcsMapper.selectSjJygjGdsjgdcsList(sjJygjGdsjgdcs);


        List<Tsyxclxx> tsyxclxxes = tsyxclxxMapper.selectTsyxclxxList(new Tsyxclxx());

        List<Dzgzzb> dzgzzbs = dzgzzbMapper.selectDzgzzbList(new Dzgzzb());

        List<String> jhList=new ArrayList<>();
        jhList.addAll(sjDzfcs.stream().map(SjDzfc::getYjjh1).distinct().collect(Collectors.toList()));
        jhList.addAll(sjDzfcs.stream().map(SjDzfc::getYjjh2).distinct().collect(Collectors.toList()));
        //优先设计
        List<LjDcyx> dcyxList =new ArrayList<>();
        CommonParam commonParam =new CommonParam();
        if(jhList.size()>0){
            //根据井号去录井查询岩性
            Object[] stringArray = jhList.toArray();

            String[] stringArray2 = Arrays.copyOf(stringArray, stringArray.length, String[].class);
            commonParam.setJhs(stringArray2);
            dcyxList = ljQueryMapper.getDcyxList(commonParam);
        }
        //其次是邻井
        if(dcyxList.size()==0){
            //查询临井
            SjLjjw sjLjjw =new SjLjjw();
            sjLjjw.setJh(param.getJh());
            List<SjLjjw> sjLjjwList = sjLjjwMapper.selectSjLjjwList(sjLjjw);
            jhList.addAll(sjLjjwList.stream().map(SjLjjw::getLjjh).collect(Collectors.toList()));
            Object[] stringArray = jhList.toArray();
            String[] stringArray2 = Arrays.copyOf(stringArray, stringArray.length, String[].class);
            commonParam.setJhs(stringArray2);
            dcyxList = ljQueryMapper.getDcyxList(commonParam);
        }
        List<SjDcfxTsyx> sjDcfxTsyxList=new ArrayList<>();
        if(dcyxList.size()>0){
            for (SjDzfc item : sjDzfcs) {
                SjDcfxDzfc ljDzfc =new SjDcfxDzfc();
                ljDzfc.setJh(param.getJh());
                ljDzfc.setCs(item.getSjdcs());
                String dcD = item.getDcD();
                if (StringUtils.isEmpty(dcD)) {
                    dcD = item.getDcZ();
                }else {
                    dcD=dcD.trim();
                    if (StringUtils.isEmpty(dcD)) {
                        dcD = item.getDcZ();
                    }else {
                        dcD=dcD.trim();
                    }
                }
                final String dc=dcD;
                ljDzfc.setDzfc(dc);
                List<LjDcyx> dzList = dcyxList.stream().filter(dcyx -> dcyx.getDcmc().equals(dc)).collect(Collectors.toList());
                List<String> yxts =dzList.stream().map(LjDcyx::getYxmc).filter(StringUtils::isNotEmpty).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
                List<String> yqcts = dzList.stream().map(LjDcyx::getYqcmc).filter(StringUtils::isNotEmpty).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
                if(yxts.size()>0){
                    String join = String.join(",", yxts.stream().distinct().collect(Collectors.toList()));
                    ljDzfc.setYxts(String.join(",",Arrays.stream(join.split(",")).distinct().collect(Collectors.toList())));
                    //查询特殊岩性
                    commonParam.setDc(dc);
                    List<LjDcyx> dcyxList2 = ljQueryMapper.getDcyxList2(commonParam);
                    List<String> collect=new ArrayList<>();
                    List<LjDcyx> ljDcyxes1=new ArrayList<>();
                    for(LjDcyx ljDcyx:dcyxList2){
                        for(Tsyxclxx tsyxclxx:tsyxclxxes){
                            if(StringUtils.isNotEmpty(ljDcyx.getYxmc())){
                                if(ljDcyx.getYxmc().contains(tsyxclxx.getTsyx())){
                                    collect.add(tsyxclxx.getWt());
                                    ljDcyx.setWt(tsyxclxx.getWt());
                                    ljDcyxes1.add(ljDcyx);
                                }
                            }

                        }
                    }

                    if(collect.size()>0){
                        ljDzfc.setGzts(String.join( ",",collect.stream().distinct().collect(Collectors.toList())));
                    }else {
                        ljDzfc.setGzts("无");
                    }

                    Map<String, List<LjDcyx>> map = ljDcyxes1.stream().collect(
                            Collectors.groupingBy(
                                    LjDcyx::getYxmc
                            ));

                    for(String key:map.keySet()){
                        List<LjDcyx> ljDcyxes = map.get(key);
                        LjDcyx ljDcyx = ljDcyxes.stream().min(Comparator.comparing(LjDcyx::getYxdjsd1)).orElse(null);
                        if(ljDcyx!=null){
                            Double yxdjsd1 = ljDcyx.getYxdjsd1();
                            Double djsd1 = ljDcyx.getDjsd1();
                            Double aaa=yxdjsd1-djsd1;
                            Double bb=aaa/ljDcyx.getHd();
                            SjDcfxTsyx sjDcfxTsyx=new SjDcfxTsyx();
                            sjDcfxTsyx.setJh(param.getJh());
                            sjDcfxTsyx.setCw(ljDcyx.getDcmc());
                            sjDcfxTsyx.setTsyx(ljDcyx.getYxmc());
                            Double cc=item.getSjdcs()+(item.getSjhd()*bb);
                            sjDcfxTsyx.setJds(Double.parseDouble(String.format("%.2f",cc)));
                            sjDcfxTsyx.setWt(ljDcyx.getWt());
                            sjDcfxTsyxList.add(sjDcfxTsyx);
                        }

                    }
                }
                if(yqcts.size()>0){
                    String join = String.join(",", yqcts.stream().distinct().collect(Collectors.toList()));
                    ljDzfc.setYqsts(String.join(",",Arrays.stream(join.split(",")).distinct().collect(Collectors.toList())));
                }else {
                    ljDzfc.setYqsts("无");
                }


                //计算斜深
                Double sjdcs = item.getSjdcs();
                if(sjdcs!=null){
                    SjJygjGdsjgdcs sjJygjGdsjgdcs1 = sjJygjGdsjgdcsList.stream().filter(it -> equals(sjdcs, it.getCs())).findFirst().orElse(null);
                    if(sjJygjGdsjgdcs1==null){
//
//                        // 查找最近的较小值 (小于目标值的最大值)
                        SjJygjGdsjgdcs jskdmin=sjJygjGdsjgdcsList.stream().filter(it -> it.getCs()<sjdcs).collect(Collectors.toList()).stream().max(Comparator.comparing(SjJygjGdsjgdcs::getCs)).orElse(null);
                        SjJygjGdsjgdcs jskdmax=sjJygjGdsjgdcsList.stream().filter(it -> it.getCs()>sjdcs).collect(Collectors.toList()).stream().min(Comparator.comparing(SjJygjGdsjgdcs::getCs)).orElse(null);
                        if(jskdmin!=null && jskdmax!=null){
                            double jsxs = jsxs(sjdcs, jskdmin.getCs(), jskdmax.getCs(), jskdmin.getJs(), jskdmax.getJs());
                            ljDzfc.setXs(jsxs);
                        }
                    }else {
                        ljDzfc.setXs(sjJygjGdsjgdcs1.getJs());
                    }
                }
                list.add(ljDzfc);
            }
        }else {


            //最后构造
            for (SjDzfc item : sjDzfcs) {
                if(item.getSjdcs()==null){
                    continue;
                }else {

                }

                String dcD = item.getDcD();
                if (StringUtils.isEmpty(dcD)) {
                    dcD = item.getDcZ();
                }else {
                    dcD=dcD.trim();
                    if (StringUtils.isEmpty(dcD)) {
                        dcD = item.getDcZ();
                    }else {
                        dcD=dcD.trim();
                    }
                }

                final String dc=dcD;
                SjDcfxDzfc ljDzfc =new SjDcfxDzfc();
                ljDzfc.setJh(param.getJh());
                ljDzfc.setCs(item.getSjdcs());
                ljDzfc.setDzfc(dc);
                List<String> collect = dzgzzbs.stream().filter(dzgzzb -> dzgzzb.getDzfc().equals(dc)).map(dzgzzb -> StringUtils.isNotEmpty(dzgzzb.getZyyx()) ? dzgzzb.getZyyx().replaceAll("、", ",") : "").collect(Collectors.toList());
                if(collect.size()>0){
                    String join = String.join(",", collect.stream().distinct().collect(Collectors.toList()));
                    ljDzfc.setYxts(String.join(",",Arrays.stream(join.split(",")).distinct().collect(Collectors.toList())));
                    List<String> tsyx = tsyxclxxes.stream().filter(tsyxclxx -> tsyxclxx.getTsyx().indexOf(ljDzfc.getYxts()) != -1).map(Tsyxclxx::getWt).collect(Collectors.toList());
                    if(tsyx.size()>0){
                        ljDzfc.setGzts(String.join( ",",tsyx.stream().distinct().collect(Collectors.toList())));
                    }
                }
                //计算斜深
                Double sjdcs = item.getSjdcs();
                if(sjdcs!=null){
                    SjJygjGdsjgdcs sjJygjGdsjgdcs1 = sjJygjGdsjgdcsList.stream().filter(it -> equals(sjdcs, it.getCs())).findFirst().orElse(null);
                    if(sjJygjGdsjgdcs1==null){
//                        // 查找最近的较小值 (小于目标值的最大值)
                        SjJygjGdsjgdcs jskdmin=sjJygjGdsjgdcsList.stream().filter(it -> it.getCs()<sjdcs).collect(Collectors.toList()).stream().max(Comparator.comparing(SjJygjGdsjgdcs::getCs)).orElse(null);
                        SjJygjGdsjgdcs jskdmax=sjJygjGdsjgdcsList.stream().filter(it -> it.getCs()>sjdcs).collect(Collectors.toList()).stream().min(Comparator.comparing(SjJygjGdsjgdcs::getCs)).orElse(null);
                        if(jskdmin!=null && jskdmax!=null){
                            double jsxs = jsxs(sjdcs, jskdmin.getCs(), jskdmax.getCs(), jskdmin.getJs(), jskdmax.getJs());
                            ljDzfc.setXs(jsxs);
                        }
                    }else {
                        ljDzfc.setXs(sjJygjGdsjgdcs1.getJs());
                    }
                }
                list.add(ljDzfc);
            }

        }


        for(SjDcfxDzfc sjDcfxDzfc:list){

            if(StringUtils.isEmpty(sjDcfxDzfc.getYxts())){
                String dc = sjDcfxDzfc.getDzfc();
                List<String> collect = dzgzzbs.stream().filter(dzgzzb -> dzgzzb.getDzfc().equals(dc)).map(dzgzzb -> StringUtils.isNotEmpty(dzgzzb.getZyyx()) ? dzgzzb.getZyyx().replaceAll("、", ",") : "").collect(Collectors.toList());
                if(collect.size()>0){

                    sjDcfxDzfc.setYxts(String.join( ",",collect.stream().distinct().collect(Collectors.toList())));
                    List<String> tsyx = tsyxclxxes.stream().filter(tsyxclxx -> tsyxclxx.getTsyx().contains(sjDcfxDzfc.getYxts())).map(Tsyxclxx::getWt).collect(Collectors.toList());
                    if(tsyx.size()>0){
                        sjDcfxDzfc.setGzts(String.join( ",",tsyx));
                    }else {
                        sjDcfxDzfc.setGzts("无");
                    }
                }

            }
        }
        if(sjDcfxTsyxList.size()>0){
            SjZysx sjZysx=new SjZysx();

            sjZysx.setLb("特殊岩性风险");

            for(SjDcfxTsyx sjDcfxTsyx:sjDcfxTsyxList){
                sjZysx.setJh(sjDcfxTsyx.getJh());
                if(StringUtils.isNotEmpty(sjZysx.getZysx())){
                    sjZysx.setZysx(sjZysx.getZysx()+"； 层位："+sjDcfxTsyx.getCw()+"   岩性："+sjDcfxTsyx.getTsyx()+"   距顶深："+sjDcfxTsyx.getJds()+" 存在风险："+  sjDcfxTsyx.getWt());
                }else {
                    sjZysx.setZysx("层位："+sjDcfxTsyx.getCw()+"   岩性："+sjDcfxTsyx.getTsyx()+"   距顶深："+sjDcfxTsyx.getJds()+" 存在风险："+  sjDcfxTsyx.getWt());
                }
            }
            sjZysxMapper.insertSjZysx(sjZysx);
            sjDcfxTsyxMapper.deleteSjDcfxTsyxByJh(sjDcfxTsyxList.get(0).getJh());
            sjDcfxTsyxMapper.insertSjDcfxTsyxBatch(sjDcfxTsyxList);
        }
        list=list.stream().filter(item -> item.getCs()!=null).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<DjZqsjfx> getKjsjList(CommonParam param) {
        //查询临井
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
        }
        List<DjZqsjfx> list =djdcInfoMapper.getZqshfxList2(param);
        DecimalFormat df = new DecimalFormat("#.00");
        DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        for(DjZqsjfx item:list){
            String kssj =item.getKssj();
            String jssj =item.getJssj();
            String zwsj ="";
            String wasj ="";

            Jswa jswap=new Jswa();
            jswap.setKsrq(DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.parseDate(item.getKssj())));
            jswap.setJsrq(DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.parseDate(item.getJssj())));
            jswap.setJs(item.getJs());
            jswap.setJh(item.getJh());
            Jswa jswaZwsj = jswaMapper.selectZwsj(jswap);
            if(jswaZwsj!=null){

                String brzygz = jswaZwsj.getBrzygz();
                // 去除所有空白字符（包括空格、制表符、换行符等）
                String cleanedRecord = brzygz.replaceAll("\\s+", "");
                List<TimePointPair> timePointPairs = extractTimePointPairsBeforeDrilling2(cleanedRecord);
                if(timePointPairs.size()==0){
                    timePointPairs=extractTimePeriodsBeforeDrilling2(cleanedRecord);
                }

                for (TimePointPair pair : timePointPairs) {
                    System.out.println("前一个时间点：" + pair.getPreviousTime2() +
                            "，钻进时间点：" + pair.getPreviousTime() +
                            "，是否跨天：" + pair.isCrossDay2());

                    String formattedTime = pair.getPreviousTime().format(DateTimeFormatter.ISO_LOCAL_TIME);
                    if( pair.isCrossDay2()){
                        wasj= DateUtils.parseDateToStr("yyyy-MM-dd",jswaZwsj.getRq()) +" "+formattedTime;
                    }else {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(jswaZwsj.getRq());        // 设置为当前日期
                        calendar.add(Calendar.DAY_OF_YEAR, -1);  // 一天
                        // 获取明天的Date对象
                        Date tomorrow = calendar.getTime();
                        wasj= DateUtils.parseDateToStr("yyyy-MM-dd",tomorrow) +" "+formattedTime;
                    }
                }
            }
            item.setWasj(wasj);
        }




        return list;
    }

    @Override
    public List<Zsjfx> getZsjList(CommonParam param) {
        //查询邻井
        if(StringUtils.isNotEmpty(param.getJh())){
            Jsba jsba = jsbaMapper.selectJsbaByJh(param.getJh());
            if(jsba!=null){
                param.setJkhzb(jsba.getJkhzb());
                param.setJkzzb(jsba.getJkzzb());
                param.setJdhzb(jsba.getJdhzb());
                param.setJdzzb(jsba.getJdzzb());
            }else {
                return  new ArrayList<>();
            }
        }
        List<Zsjfx> list=djdcInfoMapper.getZsjList(param);
        //查询注水井情况
        for(Zsjfx zsjfx:list){
            if(StringUtils.isEmpty(zsjfx.getJh())){
                continue;
            }
            //查询日报数据
            Zsjrb zsjrb=djdcInfoMapper.getZsjrbList(zsjfx.getJh());
            if(zsjrb!=null){
                zsjfx.setCwmc(zsjrb.getCwmc());
                zsjfx.setSdfw(zsjrb.getSdfw());
                zsjfx.setJkyl(zsjrb.getYy());
                zsjfx.setRzl(zsjrb.getPzl());
                zsjfx.setRzl(zsjrb.getPzl());
                if(zsjrb.getScsc()>0){
                    zsjfx.setSftz("否");
                }else {
                    zsjfx.setSftz("是");
                }
            }
            //查询井组
            Zsjjz zsjjz =djdcInfoMapper.getZsjJz(zsjfx.getJh());
            if (zsjjz!=null){
                zsjfx.setZqlxmc(zsjjz.getZqlxmc());
            }
        }
        if(StringUtils.isNotEmpty(param.getSftz())){
            list=list.stream().filter(it->param.getSftz().equals(it.getSftz())).collect(Collectors.toList());
        }
        if(StringUtils.isNotEmpty(param.getZrlx())){
            list=list.stream().filter(it->param.getZrlx().equals(it.getZqlxmc())).collect(Collectors.toList());
        }


        return list;
    }

    @Override
    public Djjc selectZtsj(Djjc djjc) {
        return djdcInfoMapper.selectZtsj(djjc);
    }

    @Override
    public List<LjGzbj> getGzbjList(CommonParam param) {
        //查询临井
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
        }
        List<LjGzbj> gzbjList = djdcInfoMapper.getGzbjList(param);
        List<LjGzbj> collect = gzbjList.stream().filter(it -> it.getZb() != null).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<JsgaVo> getJsgaList(CommonParam param) {
        //查询临井
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
        }
        List<JsgaVo> list =djdcInfoMapper.getJsgaList(param);
        for(JsgaVo item:list){
            if(StringUtils.isNotEmpty(item.getFzqk())){
                String[] split = item.getFzqk().split("@");
                List<String> collect = Arrays.stream(split).distinct().collect(Collectors.toList());
                item.setFzqk(String.join(",",collect));
            }
            if(StringUtils.isNotEmpty(item.getFsjgjyy())){
                String[] split = item.getFsjgjyy().split("@");
                List<String> collect = Arrays.stream(split).distinct().collect(Collectors.toList());
                item.setFsjgjyy(String.join(",",collect));
            }
            if(StringUtils.isNotEmpty(item.getClgk())){
                String[] split = item.getClgk().split("@");
                List<String> collect = Arrays.stream(split).distinct().collect(Collectors.toList());
                item.setClgk(String.join(",",collect));
            }
        }




        return list;
    }

    @Override
    public List<Jskd> getJskdList(CommonParam param) {
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
        }
        List<Jskd> jskdList=djdcInfoMapper.getJskdList(param);
        return jskdList;
    }

    @Override
    public String jsljfzqk(CommonParam param) {
        String jh = param.getJh();
//        if(StringUtils.isNotEmpty(param.getJh())){
//            String[] jhs = param.getJh().split(",");
//            param.setJhs(jhs);
//        }
        Jsqa jsqa=djdcInfoMapper.jsljfzqk(param);
        String s="";
        if(jsqa!=null){
            s="邻井在"+jsqa.getJs()+"m"+jsqa.getCw()+"（层厚"+jsqa.getSjhd()+"m）距顶部"+jsqa.getBfb()+"%处发生"+jsqa.getFzqk();
        }
        return s;
    }

    @Override
    public String jsjtwz(CommonParam param) {
        return null;
    }

    @Override
    public String jsgtzjds(CommonParam param) {
        Double s=djdcInfoMapper.jsgtzjds(param);
        return s+"";
    }

    @Override
    public List<LjSzfxjg> getszfxjgList2() {
        return ljSzfxjgMapper.selectLjSzfxjgList(new LjSzfxjg());
    }

    @Override
    public List<Ljjw> getLjjwList2(CommonParam param) {
        return djdcInfoMapper.getLjjwList2(param);
    }

    @Override
    public JswaVo getJswaSum(CommonParam param) {
        if(StringUtils.isNotEmpty(param.getJh())){
            String[] jhs = param.getJh().split(",");
            param.setJhs(jhs);
        }

        return djdcInfoMapper.getJswaSum(param);
    }

    /**
     * 计算斜深
     * @param a 层位垂深
     * @param a1 轨迹中比层位垂深小的垂深
     * @param a2 轨迹中比层位垂深大的垂深
     * @param b1 轨迹中比层位垂深小的斜深
     * @param b2 轨迹中比层位垂深大的斜深
     * @return
     */
    public static double jsxs(Double a,Double a1,Double a2, Double b1, Double b2) {
        if (a == null || a1 == null || a2 == null || b1 == null || b2 == null) {
            return 0.0;
        }
        double b = b1+(b2-b1)*((a-a1)/(a2-a1));
        return b;
    }




    public static void calculateScores(List<SjInfo> items) {
        // 按进尺降序排序
        List<SjInfo> jcSorted = items.stream()
                .sorted(Comparator.comparingDouble(SjInfo::getJc).reversed())
                .collect(Collectors.toList());

        // 按机速降序排序
        List<SjInfo> jsSorted = items.stream()
                .sorted(Comparator.comparingDouble(SjInfo::getJs).reversed())
                .collect(Collectors.toList());

        // 按数量降序排序
        List<SjInfo> slSorted = items.stream()
                .sorted(Comparator.comparingInt(SjInfo::getSl).reversed())
                .collect(Collectors.toList());

        // 计算进尺得分（最高1分）
        if (!jcSorted.isEmpty()) {
            double maxJc = jcSorted.get(0).getJc();
            for (int i = 0; i < jcSorted.size(); i++) {
                SjInfo item = jcSorted.get(i);
                double score = 0.0;
                if (i == 0) {
                    score = 1.0;
                } else if (i == 1 && item.getJc() == maxJc) {
                    score = 1.0; // 并列第一
                } else if (i == 1) {
                    score = 0.8; // 第二名
                }
                item.setJcScore(score);
            }
        }

        // 计算机速得分（最高0.25分）
        if (!jsSorted.isEmpty()) {
            double maxJs = jsSorted.get(0).getJs();
            for (int i = 0; i < jsSorted.size(); i++) {
                SjInfo item = jsSorted.get(i);
                double score = 0.0;
                if (i == 0) {
                    score = 1;
                } else if (i == 1 && item.getJs() == maxJs) {
                    score = 1; // 并列第一
                } else if (i == 1) {
                    score = 0.8; // 第二名
                }
                item.setJsScore(score);
            }
        }

        // 计算数量得分（最高0.5分）
        if (!slSorted.isEmpty()) {
            int maxSl = slSorted.get(0).getSl();
            for (int i = 0; i < slSorted.size(); i++) {
                SjInfo item = slSorted.get(i);
                double score = 0.0;
                if (i == 0) {
                    score = 1;
                } else if (i == 1 && item.getSl() == maxSl) {
                    score = 1; // 并列第一
                } else if (i == 1) {
                    score = 0.8; // 第二名
                }
                item.setSlScore(score);
            }
        }

        // 计算综合得分
        for (SjInfo item : items) {
            double totalScore = item.getJcScore() + item.getJsScore() + item.getSlScore();
            item.setTotalScore(totalScore);
        }
    }


    public static boolean equals(Double a, Double b) {
        // 注意：要使用String类型的构造函数，防止精度丢失
        if(a==null){
           return false;
        }
        // 注意：要使用String类型的构造函数，防止精度丢失
        if(b==null){
            return false;
        }
        BigDecimal bd1 = new BigDecimal(Double.toString(a));
        BigDecimal bd2 = new BigDecimal(Double.toString(b));
        return bd1.compareTo(bd2) == 0;
    }

    /**
     * 从Markdown代码块中提取JSON内容
     */
    private static String extractJsonContent(String markdownContent) {
        // 去除开头的```json和结尾的```
        return markdownContent
                .replaceFirst("^```json", "")
                .replaceFirst("```$", "")
                .trim();
    }

    public static boolean isValidString(JsonObject jsonObj, String fieldName) {
        return jsonObj.has(fieldName)
                && !jsonObj.get(fieldName).isJsonNull()
                && jsonObj.get(fieldName).isJsonPrimitive()
                && jsonObj.get(fieldName).getAsJsonPrimitive().isString()
                && !jsonObj.get(fieldName).getAsString().isEmpty();
    }


    public static List<Map<String, Object>> processJson(String jsonString) throws ParseException {
        // 创建Gson实例
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        // 定义JSON数据的类型
        Type jsonType = new TypeToken<Map<String, Object>>() {}.getType();
        Map<String, Object> jsonMap = gson.fromJson(jsonString, jsonType);

        // 提取columns和result
        List<String> columns = (List<String>) jsonMap.get("columns");
        List<List<Object>> result = (List<List<Object>>) jsonMap.get("result");

        // 转换为键值对列表
        List<Map<String, Object>> records = new ArrayList<>();
        for (List<Object> row : result) {
            Map<String, Object> record = new LinkedHashMap<>();
            for (int i = 0; i < columns.size(); i++) {
                if (i < row.size()) {
                    record.put(columns.get(i), row.get(i));
                } else {
                    record.put(columns.get(i), null);
                }
            }
            records.add(record);
        }

        // 将日期字符串转换为Date对象
//        System.out.println("处理结果：");
//        for (int i = 0; i < records.size(); i++) {
//            Map<String, Object> firstRecord = records.get(i);
//            String dateStr = (String) firstRecord.get("ZYSJ");
//            if (dateStr != null) {
//                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
//                Date date = dateFormat.parse(dateStr);
//                firstRecord.put("ZYSJ",date);
//            }
//        }
        return records;

    }



}
