package com.zjsgfa.project.zt.controller;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
import com.zjsgfa.common.utils.StringUtils;
import com.zjsgfa.common.utils.poi.ExcelUtil;
import com.zjsgfa.framework.web.domain.AjaxResult;
import com.zjsgfa.project.zjsgfa.domain.ClYxsj;
import com.zjsgfa.project.zt.domain.*;
import com.zjsgfa.project.zt.domain.vo.ApiResponse;
import com.zjsgfa.project.zt.domain.vo.JsgaVo;
import com.zjsgfa.project.zt.domain.vo.JswaVo;
import com.zjsgfa.project.zt.service.DjdcService;
import com.zjsgfa.project.zt.util.SSLUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/djdc")
public class DjdcController {




    @Autowired
    private DjdcService djdcService;


    @GetMapping("/getList")
    public AjaxResult getList(DjDcInfo info){
        return AjaxResult.success(djdcService.getList(info));
    }

    /**
     * 根据井号查询临井
     */
    @GetMapping("/ljListByJh")
    public AjaxResult ljListByJh(Ljinfo info){
        return AjaxResult.success(djdcService.ljListByJh(info));
    }





    /**
     * 获取井基础信息
     */
    @PostMapping("/api")
    public Object ff(@RequestBody CommonParam param) throws Exception{
        String path = param.getPath();
        Map<String,Object> map =new HashMap<>();
        switch (path) {
            case "getDjjcList":
                //获取钻头关键数据
                map.put("jh","井号");
                map.put("kc","开次");
                map.put("jd","井段");
                map.put("ztcc","钻头外径");
                map.put("ztxh","钻头型号");
                map.put("pz","喷嘴");
                map.put("mxqk","磨损情况");
                map.put("qzyy","起钻原因");
                map.put("cw","层位");
                map.put("zjymd","钻井液密度");
                map.put("lgby","泵压");
                map.put("pl","排量");
                map.put("jc","进尺");
                map.put("jxzs","机械钻速");
                map.put("zb","指标");
                List<Djjc> djjcList = djdcService.getDjjcList(param);
                AjaxResult success = AjaxResult.success(djjcList, map);
//                Gson gson = new GsonBuilder().setPrettyPrinting().create();

                // 将实体对象转换为JSON字符串
//                String json = gson.toJson(success);
//                String convert = JsonToMarkdown.convert(json);
//                System.out.println(convert);
                return success;

            case "getZqshfxList":
                //获取邻井周期分析
                map.put("jh","井号");
                map.put("kc","开次");
                map.put("jtm","井筒名");
                map.put("ksjs","开始井深");
                map.put("js","结束井深");
                map.put("jc","进尺");
                map.put("cw","到达层位");
                map.put("zjzq","钻进实际周期");
                map.put("zjycsl","钻进异常周期");
                map.put("zjsczq","钻进生产周期");
                map.put("zjsl","钻进速率");
                map.put("zwzq","中完实际周期");

                map.put("wjsczq","完井（中完）生产周期");
                map.put("wjycsl","完井异常周期");
                map.put("zjycms","钻井异常描述");
                map.put("wjycms","中完（完井异常描述）");
                return AjaxResult.success( djdcService.getZqshfxList(param),map);
            case "getZjzhfxList":
                //获取钻具组合分析
                map.put("jh","井号");
                map.put("kc","开次");
                map.put("jd","井段");
                map.put("jc","进尺");
                map.put("zjzhmx","钻具组合模型");
                map.put("tsgj","特殊工具");
                map.put("zjzh","钻具组合明细");
                map.put("zb","时效");
                return AjaxResult.success( djdcService.getZjzhfxList(param),map);
            case "getLjjwList":
                //获取邻近井位
                map.put("jh","井号");
                map.put("jx","井型");
                map.put("jb","井别");
                map.put("wjjs","井深");
                map.put("wjczjs","垂深");
                map.put("wzcw","完钻层位");
                map.put("kc","总开次");
                map.put("zjzq","钻井周期");
                map.put("wjzq","完井周期");
                map.put("jkhzb","井口横坐标");
                map.put("jkzzb","井口纵坐标");
                map.put("jkhjl","井口横距离");
                map.put("jkzjl","井口纵距离");
                map.put("jdhzb","井底横坐标");
                map.put("jdzzb","井底纵坐标");
                map.put("jkjl","井口距离");
                map.put("jdjl","井底距离");
                map.put("jdzjl","井底纵距离");
                map.put("jdhjl","井底横距离");
                AjaxResult result = djdcService.getLjjwList(param);

// 从 AjaxResult 中提取数据并转换为 List<Ljjw>
                Object data = result.get("data"); // 或者使用 result.getData()，取决于 AjaxResult 的具体实现
                List<Ljjw> ljjwList = (List<Ljjw>) data;
                String md = listToMarkdownTable(ljjwList);

                return md;
//                return AjaxResult.success("",md,map);
            case "getLjjwList2":
                //获取邻近井位
                map.put("jh","井号");
                map.put("jx","井型");
                map.put("jb","井别");
                map.put("wjjs","井深");
                map.put("wjczjs","垂深");
                map.put("wzcw","完钻层位");
                map.put("kc","总开次");
                map.put("zjzq","钻井周期");
                map.put("wjzq","完井周期");
                map.put("jkhzb","井口横坐标");
                map.put("jkzzb","井口纵坐标");
                map.put("jkhjl","井口横距离");
                map.put("jkzjl","井口纵距离");
                map.put("jdhzb","井底横坐标");
                map.put("jdzzb","井底纵坐标");
                map.put("jkjl","井口距离");
                map.put("jdjl","井底距离");
                map.put("jdzjl","井底纵距离");
                map.put("jdhjl","井底横距离");
//                List<Ljjw> ljjwList2= djdcService.getLjjwList(param);
                return djdcService.getLjjwList(param);
            case "getJsqaList":
                //获取复杂情况
                map.put("jh","井号");
                map.put("fzbh","复杂编号");
                map.put("fzqk","复杂情况");
                map.put("fsrq","事故时间－发生");
                map.put("fssj","事故时间－发生");
                map.put("jcrq","事故时间－解除");
                map.put("jcsj","事故时间－解除");
                map.put("sssj","事故时间－损失");
                map.put("fsjgjyy","发生经过");
                map.put("clgk","处理概况");
                map.put("zjjjss","直接损失");
                map.put("js","井深");
                return AjaxResult.success( djdcService.getJsqaList(param),map);
            case "getDjZtfxList":
                //获取钻头分析
                map.put("kc","开次");
                map.put("ztxh","钻头型号");
                map.put("cc","外径");
                map.put("ztsl","钻头数量（钻头使用频次）");
                map.put("ytzl","一趟钻率");
                map.put("etzl","二趟钻率");
//                map.put("stzl","三趟钻率");
//                map.put("sitzl","四趟钻率");
//                map.put("wtzl","五趟钻率");
                map.put("jcZw","进尺中位数");
                map.put("jcMax","进尺最大值");
                map.put("jxzsZw","机械钻速中位数");
                map.put("jxzsMax","机械钻速最大值");
                map.put("qsjsZw","起出井深中位数");
                return AjaxResult.success( djdcService.getDjZtfxList(param),map);
            case "calZtzhdf":
                //计算钻头综合得分和实钻分析结果
                return AjaxResult.success( djdcService.calZtzhdf(param));
            case "getSzfxjgListDmxdy":
                //查询实钻分析结果 大模型调用
                Map<String, Object> map1 = djdcService.calZtzhdf(param);
                Object data1 = map1.get("szfxjg");
                List<LjSzfxjg> list1 = (List<LjSzfxjg>) data1;

                return AjaxResult.success( djdcService.calZtzhdf(param));
            case  "getzhzhdfList":
                //获取钻头综合得分
                map.put("kc","开次");
                map.put("ztxh","钻头型号");
                map.put("cc","钻头尺寸");
                map.put("jcdf","进尺得分");
                map.put("jsdf","机速得分");
                map.put("zbdf","指标得分");
                map.put("sldf","数量得分");
                map.put("zhdf","综合得分");
                return AjaxResult.success( djdcService.getzhzhdfList(param),map);
            case  "getszfxjgList":
                //获取实钻分析结果
                map.put("gnmk","功能模块");
                map.put("fxfw","分析范围");
                map.put("fxdx","分析对象");
                map.put("fxxy","分析现象");
                map.put("fxjl","分析结论");
                map.put("scfx","输出方向");
                map.put("yxyj","优选依据");
                map.put("zyjy","最优建议");
                map.put("qcyj","其次建议");
                map.put("tjpf","推荐评分");
                map.put("xxcs","详细参数");
                return AjaxResult.success( djdcService.getszfxjgList(param),map);
            case  "getZtzhzzdfList":
                //获取钻头最终得分
                map.put("kc","开次");
                map.put("ztxh","钻头型号");
                map.put("cc","钻头尺寸");
                map.put("jcdf","进尺得分");
                map.put("jsdf","机速得分");
//                map.put("zbdf","指标得分");
//                map.put("sldf","数量得分");
                map.put("zhdf","综合得分");
                return AjaxResult.success( djdcService.getZtzhzzdfList(param),map);
            case  "getDzfcList":
                //获取地质分成
                return AjaxResult.success( djdcService.getDzfcList2(param),map);
            case  "getFdcsList":
                //获取分段方案参数
                return AjaxResult.success( djdcService.getFdcsList(param));
            case  "getKjsjList":
                //获取
                return AjaxResult.success( djdcService.getKjsjList(param));
            case  "getZsjList":
                //获取注水井
                return AjaxResult.success( djdcService.getZsjList(param));
            case  "getGzbjList":
                //获取高指标井
                return AjaxResult.success( djdcService.getGzbjList(param));
            case  "getJsgaList":
                //获取高指标井
                return AjaxResult.success( djdcService.getJsgaList(param));
            case  "getJskdList":
                //获取定向井测斜数据
                return AjaxResult.success( djdcService.getJskdList(param));
            default:
                return AjaxResult.success();
        }
    }


    /**
     * 导出地质简介基本数据列表
     */
//    @PreAuthorize("@ss.hasPermi('system:jsba:export')")
//    @Log(title = "地质简介基本数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CommonParam param) throws Exception {

        String path = param.getExportPath();
        switch (path) {
            case "exportLjjw":
                //导出邻井查询
                AjaxResult result = djdcService.getLjjwList(param);
                Object data = result.get("data");
                List<Ljjw> ljjwList = (List<Ljjw>) data;
                ExcelUtil<Ljjw> util = new ExcelUtil<Ljjw>(Ljjw.class);
                util.exportExcel(response, ljjwList, "Sheet1");
                break;
            case "exportZqshfx":
                //导出周期分析
                List<DjZqsjfx> zqshfxList = djdcService.getZqshfxList(param);
                exportZqshfx(response,zqshfxList);
                break;
            case "exportZtgjsj":
                //导出钻头关键数据
                List<Djjc> djjcList = djdcService.getDjjcList(param);
                ExcelUtil<Djjc> utilzt = new ExcelUtil<Djjc>(Djjc.class);
                utilzt.exportExcel(response, djjcList, "Sheet1");
                break;
            case "exportQkztfx":
                //导出区块钻头分析
                List<DjZtfx> djZtfxList = djdcService.getDjZtfxList(param);
                ExcelUtil<DjZtfx> utilzqk = new ExcelUtil<DjZtfx>(DjZtfx.class);
                utilzqk.exportExcel(response, djZtfxList, "Sheet1");
                break;
            case "exportZtdf":
                //导出钻头得分
                Map<String, Object> map = djdcService.calZtzhdf(param);
                List<LjZtzhdf> ztzhdf =(List<LjZtzhdf>) map.get("ztzhdf");
                ExcelUtil<LjZtzhdf> utilZtdf = new ExcelUtil<LjZtzhdf>(LjZtzhdf.class);
                utilZtdf.exportExcel(response, ztzhdf, "Sheet1");
                break;
            case "exportZzztdf":
                //导出最终钻头得分
                Map<String, Object> map2 = djdcService.calZtzhdf(param);
                List<LjZtdfzh> ljZtdfzhList =(List<LjZtdfzh>) map2.get("zjzhdf");
                ExcelUtil<LjZtdfzh> utilZzztdf = new ExcelUtil<LjZtdfzh>(LjZtdfzh.class);
                utilZzztdf.exportExcel(response, ljZtdfzhList, "Sheet1");
                break;
            case "exportSzfxjg":
                //导出实钻分析结果
                Map<String, Object> map3 = djdcService.calZtzhdf(param);
                List<LjSzfxjg> ljSzfxjgList =(List<LjSzfxjg>) map3.get("szfxjg");
                ExcelUtil<LjSzfxjg> utilSzfxjg = new ExcelUtil<LjSzfxjg>(LjSzfxjg.class);
                utilSzfxjg.exportExcel(response, ljSzfxjgList, "Sheet1");
                break;
            case "exportFdcsList":
                //导出实钻分析结果
                List<Jsha> fdcsList = djdcService.getFdcsList(param);
                exportFdcs(response,fdcsList);
                break;
            case "exportKsjList":
                //导出实钻分析结果
                List<DjZqsjfx> kjsjList = djdcService.getKjsjList(param);
                ExcelUtil<DjZqsjfx> kssjEx = new ExcelUtil<DjZqsjfx>(DjZqsjfx.class);
                kssjEx.exportExcel(response, kjsjList, "Sheet1");
                break;
            case "exportZsjList":
                //导出
                List<Zsjfx> zsjList = djdcService.getZsjList(param);
                ExcelUtil<Zsjfx> zsjfxExcelUtil = new ExcelUtil<Zsjfx>(Zsjfx.class);
                zsjfxExcelUtil.exportExcel(response, zsjList, "Sheet1");
                break;
            case "exportJsgaList":
                //导出
                List<JsgaVo> jsgaList = djdcService.getJsgaList(param);
                ExcelUtil<JsgaVo> jsgaExcelUtil = new ExcelUtil<JsgaVo>(JsgaVo.class);
                jsgaExcelUtil.exportExcel(response, jsgaList, "Sheet1");
                break;
            case "exportJskdList":
                //导出
                List<Jskd> jskdList = djdcService.getJskdList(param);
                ExcelUtil<Jskd> jskdExcelUtil = new ExcelUtil<Jskd>(Jskd.class);
                jskdExcelUtil.exportExcel(response, jskdList, "Sheet1");
                break;
            default:
                break;
        }

    }


    /**
     * 计算邻井复杂情况
     * @return
     */
    @GetMapping("/jsljfzqk")
    public String jsljfzqk(CommonParam param) {
        return djdcService.jsljfzqk(param);
    }

    /**
     * 计算具体位置
     * @return
     */
    @GetMapping("/jsjtwz")
    public String jsjtwz(CommonParam param) {
        return djdcService.jsjtwz(param);
    }

    /**
     * 计算馆陶组距底深
     * @return
     */
    @GetMapping("/jsgtzjds")
    public String jsgtzjds(CommonParam param) {
        return djdcService.jsgtzjds(param);
    }


    /**
     * 实钻分析结果长城大模型调用
     * @param
     * @return
     */
    @PostMapping(value = "/zskwd")
    public AjaxResult zskwd(@RequestBody LjSzfxjg ljSzfxjg,HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("stream", false);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("field_name","data");
        map2.put("type","input");
        String s =JSON.toJSONString (ljSzfxjg.getList());
        map2.put("value",s);
//        map2.put("value",commonParam.getDmxnr());
        List<Map> listMap =new ArrayList<>();
        listMap.add(map2);
        map.put("content",listMap);
        String url = "https://agent.ai.sinopec.com/aicoapi/gateway/v2/workflow/api_run/6d7d9423836f46f0862c62eb17bf56e2";
        String key="c8hXPRzzhakAyTW8brMGkH4DPpUqw0zk";
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(map);
        String result2 = HttpRequest.post(url).body(json).execute().body();
        System.out.println(result2);
//        // 解析API响应
        String textPresentation ="由于您没有提供具体的各开次时效最大的前5口钻具组合分析统计结果数据，我无法进行实际的数据分析和推荐。不过，我可以为您提供一个通用的分析框架和示例输出，您可以根据实际数据填充具体内容。\\n\\n通用分析框架：\\n\\n1. 数据分析：\\n- 对于每个开次（如一开、二开、三开等），查看时效最高的5个钻具组合\\n- 比较它们的机械钻速、钻头寿命、稳定性等关键指标\\n- 分析地层特点与钻具组合的匹配程度\\n\\n2. 选择最优钻具组合：\\n- 优先选择时效最高的组合\\n- 在时效相近时，选择稳定性更好的组合\\n- 考虑钻头寿命与更换频率的平衡\\n\\n3. 理由阐明：\\n- 该组合在类似地层中表现最佳\\n- 机械钻速与钻压、转速等参数匹配最优\\n- 振动控制良好，减少非生产时间\\n\\n示例输出（请用实际数据替换）：\\n\\n```json\\n{\\n  \\\"bit_recommendations\\\": {\\n    \\\"section_1\\\": {\\n      \\\"recommended_bit\\\": \\\"Φ444.5mm PDC钻头 + Φ203.2mm钻铤×6根 + Φ177.8mm钻铤×9根 + 随钻震击器\\\",\\n      \\\"rationale\\\": \\\"该组合在一开表层钻井中平均机械钻速达到35m/h，比第二名的28m/h高出25%，且振动幅度控制在安全范围内，起下钻次数最少。\\\"\\n    },\\n    \\\"section_2\\\": {\\n      \\\"recommended_bit\\\": \\\"Φ311.2mm 混合钻头 + Φ228.6mm钻铤×9根 + Φ203.2mm钻铤×6根 + 螺杆钻具\\\",\\n      \\\"rationale\\\": \\\"在二开井段硬夹层地层中，该组合时效达到22m/h，钻头寿命达180小时，无需中途更换，综合时效比使用牙轮钻头提高40%。\\\"\\n    },\\n    \\\"section_3\\\": {\\n      \\\"recommended_bit\\\": \\\"Φ215.9mm 5刀翼PDC钻头 + Φ165.1mm钻铤×12根 + 随钻测斜仪 + 涡轮增压器\\\",\\n      \\\"rationale\\\": \\\"针对三开深部复杂地层，该组合在保持18m/h钻速的同时，有效控制井斜在1°以内，减少纠斜时间，综合时效最优。\\\"\\n    }\\n  }\\n}\\n```\\n\\n请提供具体的各开次前5名钻具组合的详细统计数据（包括但不限于：钻头类型、钻具组合、机械钻速、钻头寿命、振动数据等），我可以为您做出更精确的分析和推荐。";
//        try {
//            // 创建ObjectMapper实例
//            ObjectMapper objectMapper = new ObjectMapper();
//            // 解析JSON为ApiResponse对象
//            ApiResponse res = objectMapper.readValue(json, ApiResponse.class);
//            // 提取"文本呈现"的内容
//            textPresentation = res.getData().getInnerData().getTextPresentation();
//            // 打印结果
//            System.out.println("文本呈现内容：\n" + textPresentation);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return AjaxResult.success(textPresentation);
    }

    /**
     * 实钻分析结果长城大模型调用
     * @param
     * @return
     */
    @PostMapping(value = "/szfxjgccdy")
    public AjaxResult ccdmxdy(@RequestBody LjSzfxjg ljSzfxjg,HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("stream", false);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("field_name","data");
        map2.put("type","input");
        String s =JSON.toJSONString (ljSzfxjg.getList());
        map2.put("value",s);
        List<Map> listMap =new ArrayList<>();
        listMap.add(map2);
        map.put("content",listMap);
        String url = "https://agent.ai.sinopec.com/aicoapi/gateway/v2/workflow/api_run/6d7d9423836f46f0862c62eb17bf56e2";
        String key="c8hXPRzzhakAyTW8brMGkH4DPpUqw0zk";
//        dymxcom(map,url,key,response);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(map);
        String result2 = HttpRequest.post(url).header("Authorization","Bearer "+key).body(json).execute().body();
        System.out.println(result2);
//        // 解析API响应
//        String textPresentation ="由于您没有提供具体的各开次时效最大的前5口钻具组合分析统计结果数据，我无法进行实际的数据分析和推荐。不过，我可以为您提供一个通用的分析框架和示例输出，您可以根据实际数据填充具体内容。\\n\\n通用分析框架：\\n\\n1. 数据分析：\\n- 对于每个开次（如一开、二开、三开等），查看时效最高的5个钻具组合\\n- 比较它们的机械钻速、钻头寿命、稳定性等关键指标\\n- 分析地层特点与钻具组合的匹配程度\\n\\n2. 选择最优钻具组合：\\n- 优先选择时效最高的组合\\n- 在时效相近时，选择稳定性更好的组合\\n- 考虑钻头寿命与更换频率的平衡\\n\\n3. 理由阐明：\\n- 该组合在类似地层中表现最佳\\n- 机械钻速与钻压、转速等参数匹配最优\\n- 振动控制良好，减少非生产时间\\n\\n示例输出（请用实际数据替换）：\\n\\n```json\\n{\\n  \\\"bit_recommendations\\\": {\\n    \\\"section_1\\\": {\\n      \\\"recommended_bit\\\": \\\"Φ444.5mm PDC钻头 + Φ203.2mm钻铤×6根 + Φ177.8mm钻铤×9根 + 随钻震击器\\\",\\n      \\\"rationale\\\": \\\"该组合在一开表层钻井中平均机械钻速达到35m/h，比第二名的28m/h高出25%，且振动幅度控制在安全范围内，起下钻次数最少。\\\"\\n    },\\n    \\\"section_2\\\": {\\n      \\\"recommended_bit\\\": \\\"Φ311.2mm 混合钻头 + Φ228.6mm钻铤×9根 + Φ203.2mm钻铤×6根 + 螺杆钻具\\\",\\n      \\\"rationale\\\": \\\"在二开井段硬夹层地层中，该组合时效达到22m/h，钻头寿命达180小时，无需中途更换，综合时效比使用牙轮钻头提高40%。\\\"\\n    },\\n    \\\"section_3\\\": {\\n      \\\"recommended_bit\\\": \\\"Φ215.9mm 5刀翼PDC钻头 + Φ165.1mm钻铤×12根 + 随钻测斜仪 + 涡轮增压器\\\",\\n      \\\"rationale\\\": \\\"针对三开深部复杂地层，该组合在保持18m/h钻速的同时，有效控制井斜在1°以内，减少纠斜时间，综合时效最优。\\\"\\n    }\\n  }\\n}\\n```\\n\\n请提供具体的各开次前5名钻具组合的详细统计数据（包括但不限于：钻头类型、钻具组合、机械钻速、钻头寿命、振动数据等），我可以为您做出更精确的分析和推荐。";
        String textPresentation ="";
//        try {
//            // 创建ObjectMapper实例
//            ObjectMapper objectMapper = new ObjectMapper();
//            // 全局忽略未知字段
//            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//            // 解析JSON为ApiResponse对象
//            ApiResponse res = objectMapper.readValue(json, ApiResponse.class);
//            // 提取"文本呈现"的内容
//            textPresentation = res.getData().getInnerData().getTextPresentation();
//            // 打印结果
//            System.out.println("文本呈现内容：\n" + textPresentation);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        // 解析为顶层JsonObject
        JsonObject root = gson.fromJson(result2, JsonObject.class);

        // 逐层获取"文本呈现"内容
        // 1. 获取外层data节点
        JsonObject outerData = root.getAsJsonObject("data");
        // 2. 获取内层data节点
        JsonObject innerData = outerData.getAsJsonObject("data");
        // 3. 获取"文本呈现"字段的值
        textPresentation = innerData.get("文本呈现").getAsString();

        // 打印结果
        System.out.println("文本呈现内容：\n" + textPresentation);


        // 进阶：提取"文本呈现"中嵌套的JSON示例（如bit_recommendations）
        // 1. 从文本中截取JSON部分（通过```json标记分割）
//        String[] textParts = textPresentation.split("```json");
//        if (textParts.length > 1) {
//            String jsonPart = textParts[1].split("```")[0].trim();
//            // 2. 解析截取的JSON字符串
//            JsonObject recommendations = gson.fromJson(jsonPart, JsonObject.class);
//            // 3. 获取一开推荐的钻头
//            String section1Bit = recommendations
//                    .getAsJsonObject("bit_recommendations")
//                    .getAsJsonObject("section_1")
//                    .get("recommended_bit")
//                    .getAsString();
//
//            System.out.println("\n一开推荐钻头：" + section1Bit); // 输出 P5354
//        }
        return AjaxResult.success(textPresentation);
    }

    public static void main(String[] args) {
        String json="{\"code\":200,\"msg\":\"成功\",\"data\":{\"event\":\"workflow_finished\",\"session_id\":\"1ef1627eedc6498bbd197a1697a0c7fb\",\"step_id\":\"\",\"created\":1763347609215,\"data\":{\"usage\":{\"completion_tokens\":881,\"max_token\":\"8k\",\"prompt_tokens\":886,\"total_tokens\":1767},\"文本呈现\":\"### 数据分析\\n\\n首先，我们需要对输入的数据进行详细分析，以便为每个开次选择最优的钻具组合。输入数据包含了多个开次（如一开、二开）的钻头使用情况，主要关注以下几个方面：\\n1. **钻头进尺最高**：反映了钻头在单次使用中的钻进能力。\\n2. **钻头机速最快**：反映了钻头的机械钻速，即单位时间内的钻进速度。\\n3. **钻头数量使用最多**：反映了该钻头的使用频率和可靠性。\\n4. **一趟钻率**：反映了钻头在一次下井中完成钻进任务的能力，高一趟钻率通常意味着更高的效率和更少的起下钻时间。\\n\\n#### 一开（1开）数据分析：\\n- **P5354钻头**：\\n  - 进尺最高：359.0米（5只钻头，一趟钻率100%）。\\n  - 机速最快：机械转速126.88（5只钻头，一趟钻率100%）。\\n  - 数量使用最多：5只钻头，一趟钻率100%。\\n  - 其他：在所有指标中表现最优，且一趟钻率高达100%，说明其效率和可靠性非常高。\\n\\n#### 二开（2开）数据分析：\\n- **HT2565钻头**：\\n  - 进尺最高：2758.3米（4只钻头，一趟钻率25%）。\\n  - 机速最快：机械转速40.465（4只钻头，一趟钻率25%）。\\n  - 数量使用最多：4只钻头（与HT2555并列），一趟钻率25%。\\n- **HT2555钻头**：\\n  - 进尺最高：422.0米（4只钻头，一趟钻率25%）。\\n  - 机速最快：机械转速26.925（4只钻头，一趟钻率25%）。\\n  - 数量使用最多：4只钻头（与HT2565并列），一趟钻率25%。\\n- 对比：\\n  - HT2565在进尺和机速上显著优于HT2555（进尺2758.3 vs 422.0，机速40.465 vs 26.925）。\\n  - 一趟钻率两者相同（25%），但HT2565的绝对进尺和机速更高，说明其时效更高。\\n\\n### 选择最优钻头\\n#### 一开（1开）：\\n- **最优钻头**：P5354。\\n  - 理由：\\n    - 在所有指标（进尺、机速、数量）中表现最优。\\n    - 一趟钻率100%，说明其高效且可靠，能够一次性完成钻进任务，减少起下钻时间。\\n    - 机械转速高达126.88，远高于其他钻头（二开的HT2565仅为40.465），说明其钻进速度极快。\\n\\n#### 二开（2开）：\\n- **最优钻头**：HT2565。\\n  - 理由：\\n    - 进尺最高（2758.3米），远高于HT2555的422.0米，说明其单次钻进能力更强。\\n    - 机速最快（40.465），高于HT2555的26.925，说明其钻进速度更快。\\n    - 虽然一趟钻率较低（25%），但其绝对进尺和机速的优势足以弥补这一点，综合时效更高。\\n\\n### 输出结果\\n```json\\n{\\n  \\\"bit_recommendations\\\": {\\n    \\\"section_1\\\": {\\n      \\\"recommended_bit\\\": \\\"P5354\\\",\\n      \\\"reason\\\": \\\"P5354在一开中表现最优，进尺最高（359.0米）、机速最快（126.88）、数量使用最多（5只），且一趟钻率100%，综合时效最高。\\\"\\n    },\\n    \\\"section_2\\\": {\\n      \\\"recommended_bit\\\": \\\"HT2565\\\",\\n      \\\"reason\\\": \\\"HT2565在二开中进尺最高（2758.3米）、机速最快（40.465），虽然一趟钻率为25%，但其绝对进尺和机速的优势使其综合时效最高。\\\"\\n    }\\n  }\\n}\\n```\"},\"url_list\":[],\"search_results\":[],\"usage\":{\"total_tokens\":1767,\"prompt_tokens\":886,\"completion_tokens\":881,\"max_token\":\"8k\"}}}";
        Gson gson = new Gson();
        // 解析为顶层JsonObject
        JsonObject root = gson.fromJson(json, JsonObject.class);

        // 逐层获取"文本呈现"内容
        // 1. 获取外层data节点
        JsonObject outerData = root.getAsJsonObject("data");
        // 2. 获取内层data节点
        JsonObject innerData = outerData.getAsJsonObject("data");
        // 3. 获取"文本呈现"字段的值
        String textPresentation = innerData.get("文本呈现").getAsString();

        // 打印结果
        System.out.println("文本呈现内容：\n" + textPresentation);

    }




    // 保留原有其他方法（如export、dymxcom、listToMarkdownTable等）...

    /**
     * 周期分析长城大模型调用
     * @param
     * @return
     */
    @PostMapping("/zqfxccdy")
    public void zqfxccdy(@RequestBody DjZqsjfx djZqsjfx,HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("stream", true);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("field_name", "data");
        map2.put("type", "input");
        List<DjZqsjfx> list = djZqsjfx.getList();
        for (DjZqsjfx item : list) {
            double zjzq = item.getZjzq() != null ? item.getZjzq() : 0;
            double zwzq = item.getZwzq() != null ? item.getZwzq() : 0;
            item.setHj(zjzq + zwzq);
        }


        //按开次分组，取出各开次钻进实际周期+中完实际周期和值最小的5口井
        Map<String, List<DjZqsjfx>> result = list.stream()
                .collect(Collectors.groupingBy(DjZqsjfx::getKc)) // 按开次(kc)分组
                .entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey, // 保持开次作为key
                        entry -> entry.getValue().stream()
                                .sorted(Comparator.comparingDouble(item ->
                                        (item.getZjzq() != null ? item.getZjzq() : 0) +
                                                (item.getZwzq() != null ? item.getZwzq() : 0)))
                                .limit(5)
                                .collect(Collectors.toList())
                ));
        List<DjZqsjfx> list1 = new ArrayList<>();
        for (Map.Entry<String, List<DjZqsjfx>> entry : result.entrySet()) {
            List<DjZqsjfx> value = entry.getValue();
            value.forEach(item -> {
                double a = (item.getZjzq() != null ? item.getZjzq() : 0) +
                        (item.getZwzq() != null ? item.getZwzq() : 0);
                item.setZjzqsj(a);
                item.setWjycms(null);
                item.setZjycms(null);
            });
            list1.addAll(value);
        }
        String list1Str = JSON.toJSONString(list1);
        System.out.println(list1Str);

        Map<String, Object> map3 = new HashMap<>();
        map3.put("list1", list1Str);


        Map<String, Object> statistics = new HashMap<>();

        // 3. 提取所有hj值并排序（用于计算中位数、快速定位最值）
        List<Double> sortedHjList = list.stream()
                .map(DjZqsjfx::getHj) // 提取hj字段
                .sorted() // 自然排序（升序）
                .collect(Collectors.toList()); // 收集到列表，便于后续索引访问

        // 4. 计算最大值及对应数据
        // 4.1 用DoubleStream的max()获取最大值（Optional<Double>，避免空值）
        OptionalDouble maxHjOpt = list.stream()
                .mapToDouble(DjZqsjfx::getHj) // 转为DoubleStream（支持数值统计）
                .max();
        // 4.2 提取最大值（因列表非空，用orElseThrow避免空指针）
        double maxHj = maxHjOpt.orElseThrow(() -> new RuntimeException("无最大值数据"));
        // 4.3 筛选出hj=maxHj的所有对象
        List<DjZqsjfx> maxDataList = list.stream()
                .filter(item -> Math.abs(item.getHj() - maxHj) < 1e-6) // 浮点数精度对比（1e-6=0.000001）
                .collect(Collectors.toList());

        // 5. 计算最小值及对应数据（逻辑与最大值一致）
        OptionalDouble minHjOpt = list.stream()
                .mapToDouble(DjZqsjfx::getHj)
                .min();
        double minHj = minHjOpt.orElseThrow(() -> new RuntimeException("无最小值数据"));
        List<DjZqsjfx> minDataList = list.stream()
                .filter(item -> Math.abs(item.getHj() - minHj) < 1e-6)
                .collect(Collectors.toList());

        // 6. 计算平均值
        OptionalDouble avgHjOpt = list.stream()
                .mapToDouble(DjZqsjfx::getHj)
                .average(); // DoubleStream的average()返回OptionalDouble
        double avgHj = avgHjOpt.orElseThrow(() -> new RuntimeException("无平均值数据"));

        // 7. 计算中位数及对应数据
        double medianHj;
        int dataSize = sortedHjList.size();
        if (dataSize % 2 == 1) {
            // 奇数个数据：取中间索引的元素（索引=size/2，如5个元素取第2个，0开始）
            medianHj = sortedHjList.get(dataSize / 2);
        } else {
            // 偶数个数据：取中间两个元素的平均值（如6个元素取第2、3个的平均）
            double midLeft = sortedHjList.get(dataSize / 2 - 1);
            double midRight = sortedHjList.get(dataSize / 2);
            medianHj = (midLeft + midRight) / 2;
        }
        // 筛选中位数对应的所有数据（注意：若中位数是平均值，可能无完全匹配数据）
        List<DjZqsjfx> medianDataList = list.stream()
                .filter(item -> Math.abs(item.getHj() - medianHj) < 1e-6)
                .collect(Collectors.toList());

        // 8. 打印结果
        System.out.println("=== hj字段统计结果 ===");
        System.out.println("1. 最大值：" + maxHj + "，对应数据：" + maxDataList);
        System.out.println("2. 最小值：" + minHj + "，对应数据：" + minDataList);
        System.out.println("3. 平均值：" + String.format("%.2f", avgHj) + "（保留2位小数）");
        System.out.println("4. 中位数：" + medianHj + "，对应数据：" +
                (medianDataList.isEmpty() ? "无完全匹配数据" : medianDataList));

        statistics.put("min", minHj);
        statistics.put("max", maxHj);
        statistics.put("avg", avgHj);
        statistics.put("median", medianHj);

        statistics.put("maxDataList", maxDataList);
        statistics.put("minDataList", minDataList);
        statistics.put("medianDataList", medianDataList);


        map3.put("list2", statistics);
        System.out.println(statistics);

        //查询jsqa复杂事故
        CommonParam param = new CommonParam();

        String join = String.join(",", list.stream().map(DjZqsjfx::getJh).distinct().collect(Collectors.toList()));
        param.setJh(join);
        List<Jsqa> jsqas = djdcService.getJsqaList(param);
        List<Jsqa> jsqaList = new ArrayList<>();
        for (Jsqa jsqa : jsqas) {
            Jsqa jsqa1 = new Jsqa();
            jsqa1.setJh(jsqa.getJh());
            jsqa1.setFsjgjyy(jsqa.getFsjgjyy());
            jsqaList.add(jsqa1);
        }
        map3.put("list3", jsqaList);


        JswaVo jswaVo = djdcService.getJswaSum(param);
        map3.put("list4", jswaVo);


        Map<String, String> map4 = new HashMap<>();
        map4.put("jh", "井号");
        map4.put("kc", "开次");
        map4.put("ksjs", "开始井深");
        map4.put("js", "结束井深");
        map4.put("jc", "进尺");
        map4.put("cw", "到达层位");
        map4.put("zjzq", "钻进实际周期");
        map4.put("zjycsl", "钻进异常周期");
        map4.put("zjsczq", "钻进生产周期");
        map4.put("zjsl", "钻进速率");
        map4.put("zwzq", "中完实际周期");
        map4.put("wjsczq", "完井（中完）生产周期");
        map4.put("wjycsl", "完井异常周期");
        map4.put("zjycms", "钻井异常描述");
        map4.put("wjycms", "中完（完井异常描述）");
        map4.put("zjzqsj", "和值");
        map4.put("zb", "指标");
        map4.put("fsjgjyy", "异常描述");
        map4.put("sg", "事故次数");
        map4.put("xl", "修理次数");
        map4.put("zztg", "组织停工次数");
        map4.put("zrtg", "自然停工次数");
        map4.put("fzqk", "复杂情况次数");

        map4.put("sgsum", "事故时间合计");
        map4.put("xlsum", "修理时间合计");
        map4.put("zztgsum", "组织停工时间合计");
        map4.put("zrtgsum", "自然停工时间合计");
        map4.put("fzqksum", "复杂情况时间合计");
        map4.put("zhj", "总时间合计");
        map3.put("ZDSM", map4);
        System.out.println(map3);

        List<Map> mapList=new ArrayList<>();
        mapList.add(map3);
        String list1Map2 = JSON.toJSONString(mapList);

        map2.put("value", list1Map2);


        List<Map> listMap = new ArrayList<>();
        listMap.add(map2);
        map.put("content", listMap);
        String url = "https://agent.ai.sinopec.com/aicoapi/gateway/v2/workflow/api_run/0093ad2f62d34b7e9510a860b78508ab";
        String key = "lpzt1Oxvja1zWOEnzdD5WK4iVBXbgcYg";
        dymxcom(map, url, key, response);


    }


    /**
     *钻具组合长城大模型调用
     * @param
     * @return
     */
    @PostMapping("/zjzhccdy")
    public void zjzhccdy(@RequestBody DjZjzhfx djZjzhfx,HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("stream", true);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("field_name","data");
        map2.put("type","input");
        List<DjZjzhfx> list = djZjzhfx.getList();

// 按照开次(kc)分组，并取每组中zb最高的前5条记录
        Map<String, List<DjZjzhfx>> result = list.stream()
                .collect(Collectors.groupingBy(DjZjzhfx::getKc))  // 按kc分组
                .entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,  // 保留key(即kc)
                        entry -> entry.getValue().stream()  // 对每组内的元素
                                .sorted(Comparator.comparing(DjZjzhfx::getZb).reversed())  // 按zb降序排序
                                .limit(5)  // 取前5个
                                .collect(Collectors.toList())
                ));
        List<DjZjzhfx> list2 = new ArrayList<>();
        for (Map.Entry<String, List<DjZjzhfx>> entry : result.entrySet()) {
            list2.addAll(entry.getValue());
        }
        Map<String,Object> map3=new HashMap<>();
        String list1Str = JSON.toJSONString(list2);
        map3.put("list1",list1Str);


        Map<String, String> map4 = new HashMap<>();
        map4.put("jh", "井号");
        map4.put("kc", "开次");
        map4.put("ksjs", "开始井深");
        map4.put("js", "结束井深");
        map4.put("jd", "井段");
        map4.put("zjzhmx", "钻具组合模型");
        map4.put("tsgj", "特殊工具");
        map4.put("zjzh", "钻具组合明细");
        map4.put("zb", "时效");
        map4.put("zhj", "总时间合计");
        map3.put("ZDSM", map4);
        System.out.println(map3);
        List<Map> mapList=new ArrayList<>();
        mapList.add(map3);
        String list1Map2 = JSON.toJSONString(mapList);
        map2.put("value",list1Map2);

        List<Map> listMap =new ArrayList<>();
        listMap.add(map2);
        map.put("content",listMap);
        String url = "https://agent.ai.sinopec.com/aicoapi/gateway/v2/workflow/api_run/41204ba1e1544e639ac842bc432651fb";
        String key="g7qoMEhICC8F3uKkLum0J5kJcrmYnp8O";
        dymxcom(map,url,key,response);
    }



    /**
     * 分段参数长城大模型调用
     * @param
     * @return
     */
    @PostMapping("/fdcsccdy")
    public void fdcsccdy(@RequestBody Jsha jsha,HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("stream", true);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("field_name","data");
        map2.put("type","input");
        List<Jsha> list = jsha.getList();
        Map<String, List<Jsha>> result = list.stream()
                .collect(Collectors.groupingBy(Jsha::getKc));
        List<Map> list1 =new ArrayList<>();
        for(String kc : result.keySet()){
            List<Jsha> jshas = result.get(kc);
            //排序
            List<Jsha> collect = jshas.stream().filter(it->it.getJxzs()!=null).sorted(Comparator.comparing(Jsha::getJxzs).reversed()).limit(5).collect(Collectors.toList());
            Map<String,Object> map1=new HashMap<>();
            map1.put("开次",kc);
            map1.put("平均值",collect.stream().mapToDouble(Jsha::getJxzs).average().getAsDouble());
            map1.put("机速最高",JSON.toJSONString (collect));
            List<Jsha> collect2 = collect.stream().sorted(Comparator.comparing(Jsha::getJxzs)).limit(5).collect(Collectors.toList());
            map1.put("机速最低",JSON.toJSONString (collect2));
            list1.add(map1);
        }


        List<Map> list2 =new ArrayList<>();
        for(String kc : result.keySet()){
            List<Jsha> jshas = result.get(kc);
            //排序
            List<Jsha> collect = jshas.stream().sorted(Comparator.comparing(Jsha::getGllyl).reversed()).limit(5).collect(Collectors.toList());
            Map<String,Object> map1=new HashMap<>();
            map1.put("开次",kc);
            map1.put("平均值",jshas.stream().mapToDouble(Jsha::getGllyl).average().getAsDouble());
            map1.put("机速最高",JSON.toJSONString (collect));
            List<Jsha> collect2 = jshas.stream().sorted(Comparator.comparing(Jsha::getGllyl)).limit(5).collect(Collectors.toList());
            map1.put("机速最低",JSON.toJSONString (collect2));
            list2.add(map1);
        }
        Map<String,Object> map3 =new HashMap<>();
        map3.put("list1",JSON.toJSONString (list1));
        map3.put("list2",JSON.toJSONString (list2));


        Map<String,Object> map4 =new HashMap<>();
        map4.put("jh", "井号");
        map4.put("kc", "开次");
        map4.put("jc", "进尺");
        map4.put("jxzs", "机械转速");
        map4.put("zy", "钻压");
        map4.put("zs", "转速");
        map4.put("gj", "缸径");
        map4.put("bs", "泵速");
        map4.put("pl", "排量");
        map4.put("lgby", "立管泵压");
        map4.put("ztyj", "钻头压降");
        map4.put("hkyh", "环空压耗");
        map4.put("cjl", "冲击力");
        map4.put("pssd", "喷射速度");
        map4.put("ztsgl", "钻头水功率");
        map4.put("bsgl", "比水功");
        map4.put("sfsdzg", "上返速度钻杆");
        map4.put("sfsdzt", "上返速度钻铤");
        map4.put("gllyl", "功率利用率");
        map3.put("ZDSM", map4);
        List<Map> listMap2 =new ArrayList<>();
        listMap2.add(map3);
        String s =JSON.toJSONString (listMap2);
        System.out.println(s);
        map2.put("value",s);
        List<Map> listMap =new ArrayList<>();
        listMap.add(map2);
        map.put("content",listMap);
        String url = "https://agent.ai.sinopec.com/aicoapi/gateway/v2/workflow/api_run/e08c44442d9f48c58bf01ed893c65e12";
        String key="g7qoMEhICC8F3uKkLum0J5kJcrmYnp8O";
        dymxcom(map,url,key,response);
    }


    /**
     * 高指标井长城大模型调用
     * @param
     * @return
     */
    @PostMapping("/gzbjccdy")
    public void gzbjccdy(@RequestBody LjGzbj ljGzbj,HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("stream", true);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("field_name","data");
        map2.put("type","input");
        List<LjGzbj> list = ljGzbj.getList();
        String s =JSON.toJSONString (list);
        System.out.println(s);
        map2.put("value",s);
        List<Map> listMap =new ArrayList<>();
        listMap.add(map2);
        map.put("content",listMap);
        String url = "https://agent.ai.sinopec.com/aicoapi/gateway/v2/workflow/api_run/0985ddac64974702829c1d37b4acac05";
        String key="g7qoMEhICC8F3uKkLum0J5kJcrmYnp8O";
        dymxcom(map,url,key,response);
    }



    /**
     * 典型地质岩性长城大模型调用
     * @param
     * @return
     */
    @PostMapping("/dxyxcsccdy")
    public void dxyxcsccdy(@RequestBody ClYxsj clYxsj, HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("stream", true);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("field_name","data");
        map2.put("type","input");
        List<ClYxsj> list = clYxsj.getList();
        String s =JSON.toJSONString (list);
        System.out.println(s);
        map2.put("value",s);
        List<Map> listMap =new ArrayList<>();
        listMap.add(map2);
        map.put("content",listMap);
        String url = "https://agent.ai.sinopec.com/aicoapi/gateway/v2/workflow/api_run/56b56b6f0e224f8184b18309dab9c58c";
        String key="g7qoMEhICC8F3uKkLum0J5kJcrmYnp8O";
        dymxcom(map,url,key,response);
    }





    /**
     * 钻井液指标分析长城大模型调用
     * @param
     * @return
     */
    @PostMapping("/zjyzbccdy")
    public void zjyzbccdy(@RequestBody JsgaVo jsgaVo, HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("stream", true);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("field_name","data");
        map2.put("type","input");
        List<JsgaVo> list = jsgaVo.getList();
        Map<String, List<JsgaVo>> result = list.stream().filter(it->StringUtils.isNotEmpty(it.getDccw()))
                .collect(Collectors.groupingBy(JsgaVo::getDccw));

        List< Map<String,Object> > mapList =new ArrayList<>();
        for (String key:result.keySet()) {
            List<JsgaVo> jskdList = result.get(key);
            List<JsgaVo> collect = jskdList.stream().filter(it -> StringUtils.isNotEmpty(it.getFzqk())).collect(Collectors.toList());
           if(collect.size()>0){
               List<JsgaVo> collect1 = collect.stream().sorted(Comparator.comparing(JsgaVo::getJd).reversed()).collect(Collectors.toList());
               Map<String,Object> map1=new HashMap<>();
               JsgaVo jsgaVo1 = collect1.get(0);
               map1.put("层位",key);
               map1.put("取样井深",jsgaVo1.getJd());
               map1.put("钻井液密度",jsgaVo1.getMd());
               map1.put("复杂情况",jsgaVo1.getFzqk());
               map1.put("发生经过",jsgaVo1.getFsjgjyy());
               map1.put("起始井深",jsgaVo1.getQsjs());
               map1.put("钻至井深",jsgaVo1.getZzjs());
               map1.put("进尺",jsgaVo1.getJc());
               map1.put("机械转速",jsgaVo1.getJxzs());
               map1.put("处理概括",jsgaVo1.getClgk());
               mapList.add(map1);
           }

        }
        String s =JSON.toJSONString (mapList);
        System.out.println(s);
        map2.put("value",s);
        List<Map> listMap =new ArrayList<>();
        listMap.add(map2);
        map.put("content",listMap);
        String url = "https://agent.ai.sinopec.com/aicoapi/gateway/v2/workflow/api_run/d309947b9bee461692b286a4f898e4a6";
        String key="g7qoMEhICC8F3uKkLum0J5kJcrmYnp8O";
        dymxcom(map,url,key,response);
    }




    /**
     * 钻井液指标分析长城大模型调用
     * @param
     * @return
     */
    @PostMapping("/cxsjccdy")
    public void cxsjccdy(@RequestBody Jskd jskd, HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("stream", true);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("field_name","data");
        map2.put("type","input");
        List<Jskd> list = jskd.getList();
        Map<String, List<Jskd>> result = list.stream()
                .collect(Collectors.groupingBy(Jskd::getJh));

        List< Map<String,Object> > mapList =new ArrayList<>();
        for (String key:result.keySet()) {
            List<Jskd> jskdList = result.get(key);
            List<Jskd> collect = jskdList.stream().filter(it -> StringUtils.isNotEmpty(it.getZrzjx()) && it.getLjczjs()>1500 && StringUtils.isNotEmpty(it.getGldc())).collect(Collectors.toList());
            Map<String, List<Jskd>> resultcw = collect.stream()
                    .collect(Collectors.groupingBy(Jskd::getGldc));
            for (String keycw:resultcw.keySet()) {
                List<Jskd> jskdListcw = resultcw.get(keycw);
                Map<String,Object> cwMap=new HashMap<>();
                cwMap.put("井号",key);
                cwMap.put("层位",keycw);
                if(jskdListcw.size()>0){

                }
                Map<String, List<Jskd>> resultzjx = jskdListcw.stream()
                        .collect(Collectors.groupingBy(Jskd::getZrzjx));
                for (String keyzjx:resultzjx.keySet()){
                    List<Jskd> jskdList1 = resultzjx.get(keyzjx);
                    cwMap.put(keyzjx,jskdList1.size());
                }
                mapList.add(cwMap);
            }
        }
        String s =JSON.toJSONString (mapList);
        System.out.println(s);
        map2.put("value",s);
        List<Map> listMap =new ArrayList<>();
        listMap.add(map2);
        map.put("content",listMap);
        String url = "https://agent.ai.sinopec.com/aicoapi/gateway/v2/workflow/api_run/c49e9b4c7f5a4b55863841dedf0be739";
        String key="g7qoMEhICC8F3uKkLum0J5kJcrmYnp8O";
        dymxcom(map,url,key,response);
    }


    /**
     * 处理单个分组，排序并获取前5条数据
     */
    private List<DjZqsjfx> processGroup(List<DjZqsjfx> group) {
        return group.stream()
                // 按异常周期总和降序排序
                .sorted(Comparator.comparingDouble(this::calculateTotalExceptionPeriod).reversed())
                // 取前5条
                .limit(5)
                // 收集为列表
                .collect(Collectors.toList());
    }

    /**
     * 计算钻进异常周期与中完异常周期的总和
     * 处理null值，null时按0计算
     */
    private double calculateTotalExceptionPeriod(DjZqsjfx item) {
        double zjycsl = item.getZjycsl() != null ? item.getZjycsl() : 0;
        double wjycsl = item.getWjycsl() != null ? item.getWjycsl() : 0;
        return zjycsl + wjycsl;
    }


    public void dymxcom(  Map<String, Object> map,String url,String key,HttpServletResponse response) throws IOException {

        // 设置响应头，支持SSE
        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Connection", "keep-alive");

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(map);
        String result2 = HttpRequest.post(url).header("Authorization","Bearer "+key).body(json).execute().body();
        System.out.println(result2);

        // 2. 解析json.txt内容：按行拆分（处理换行符，兼容Windows(\r\n)和Linux(\n)）
        List<String> lines = Arrays.asList(result2.split("\\r?\\n"));
        PrintWriter writer = response.getWriter();

        try {
            // 3. 封装SSE事件块：每2行（event:ADD + data:{...}）组成一个完整SSE事件
            for (int i = 0; i < lines.size(); i += 2) {
                if (i + 1 >= lines.size()) break; // 避免数组越界

                String eventLine = lines.get(i); // 对应 "event:ADD"
                String dataLine = lines.get(i + 1); // 对应 "data:{...}"

                // 4. 拼接SSE事件（每个事件以2个换行符结束）
                String sseEvent = eventLine + "\n" + dataLine + "\n\n";
                writer.write(sseEvent);
                writer.flush(); // 立即推送，避免缓冲区滞留

                // 可选：模拟实时推送延迟（实际场景可根据外部接口数据生成节奏调整）
//                Thread.sleep(500);
            }

            // 5. 推送结束事件（可选，告知前端流已结束）
            writer.write("event:close\ndata:{\"status\":\"finished\"}\n\n");
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

    public void exportZqshfx(HttpServletResponse response,List<DjZqsjfx> list)throws IOException {
        Workbook exl = null;
        OutputStream out = null;
        InputStream in  = null;
        try {
            in =this.getClass().getResourceAsStream("/static/excel/zqfxdcmb.xlsx");
            exl = WorkbookFactory.create(in);
            out = response.getOutputStream();
            response.reset();
            String filename = URLEncoder.encode("导入模板.xlsx", "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

            Sheet sheet = exl.getSheet("Sheet1");
            CellStyle cellStyle = exl.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
            cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
            cellStyle.setBorderTop(BorderStyle.THIN);//上边框
            cellStyle.setBorderRight(BorderStyle.THIN);//右边框
            cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
            cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
            Font cellFont = exl.createFont();
            cellFont.setFontHeightInPoints((short)9);    // 字体大小
            cellFont.setFontName("宋体");             // 字体应用到当前单元格上
            cellStyle.setFont(cellFont);
            cellStyle.setWrapText(true);//设置自动换行

            int lastRow = sheet.getLastRowNum()+1;
            for(DjZqsjfx item:list){
                Row row = sheet.createRow(lastRow);
                row.setHeightInPoints(18);
                int m = 0;
                Cell cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getJh()+"");
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getKc()+"");
//                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getJtm()+"");
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getKsjs()+"");
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getJs()+"");
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getJc()+"");
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getCw()+"");
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getZjzq()+"");
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getZjycsl()+"");
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getZjsczq()+"");
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getZjsl()+"");
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getZwzq()+"");
                if(item.getWjycsl()!=null){
                    cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getWjycsl());

                }else {
                    cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue("");
                }

                if(item.getWjsczq()!=null){
                    cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getWjsczq());
                }else {
                    cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue("");

                }

                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getZjycms());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getWjycms());
                lastRow++;
            }
            exl.write(out);
            exl.close();
        }catch (Exception e){
            e.getMessage();
            throw new IOException();
        }finally{
            if (exl != null) {
                try {
                    exl.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }



    public void exportFdcs(HttpServletResponse response,List<Jsha> list)throws IOException {
        Workbook exl = null;
        OutputStream out = null;
        InputStream in  = null;
        try {
            in =this.getClass().getResourceAsStream("/static/excel/ljfdcs.xlsx");
            exl = WorkbookFactory.create(in);
            out = response.getOutputStream();
            response.reset();
            String filename = URLEncoder.encode("导入模板.xlsx", "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

            Sheet sheet = exl.getSheet("Sheet1");
            CellStyle cellStyle = exl.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
            cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
            cellStyle.setBorderTop(BorderStyle.THIN);//上边框
            cellStyle.setBorderRight(BorderStyle.THIN);//右边框
            cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
            cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
            Font cellFont = exl.createFont();
            cellFont.setFontHeightInPoints((short)9);    // 字体大小
            cellFont.setFontName("宋体");             // 字体应用到当前单元格上
            cellStyle.setFont(cellFont);
            cellStyle.setWrapText(true);//设置自动换行

            int lastRow = sheet.getLastRowNum()+1;
            for(Jsha item:list){
                Row row = sheet.createRow(lastRow);
                row.setHeightInPoints(18);
                int m = 0;
                Cell cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getJh());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getKc());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getZy());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getZs());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getGj());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getBs());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getPl());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getLgby());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getZtyj());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getHkyh());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getCjl());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getPssd());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getZtsgl());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getBsgl());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getSfsdzg());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getSfsdzt());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(item.getGllyl());
                lastRow++;
            }
            exl.write(out);
            exl.close();
        }catch (Exception e){
            e.getMessage();
            throw new IOException();
        }finally{
            if (exl != null) {
                try {
                    exl.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }




    // 生成Markdown表格
    public static String listToMarkdownTable(List<Ljjw> ljjwList) {
        StringBuilder markdownTable = new StringBuilder();

        // 获取Ljjw类的所有字段
        Field[] fields = Ljjw.class.getDeclaredFields();

        // 生成表头
        markdownTable.append("|");
        for (Field field : fields) {

        }
        markdownTable.append("井号".replace("|", "\\|")).append("|");
        markdownTable.append("井口横坐标".replace("|", "\\|")).append("|");
        markdownTable.append("井口纵坐标".replace("|", "\\|")).append("|");
        markdownTable.append("井底横坐标".replace("|", "\\|")).append("|");
        markdownTable.append("井底纵坐标".replace("|", "\\|")).append("|");
        markdownTable.append("井型".replace("|", "\\|")).append("|");
        markdownTable.append("井别".replace("|", "\\|")).append("|");
        markdownTable.append("斜深".replace("|", "\\|")).append("|");
        markdownTable.append("垂深".replace("|", "\\|")).append("|");
        markdownTable.append("完钻层位".replace("|", "\\|")).append("|");
        markdownTable.append("总开次".replace("|", "\\|")).append("|");
        markdownTable.append("完井周期".replace("|", "\\|")).append("|");
        markdownTable.append("钻井周期".replace("|", "\\|")).append("|");
        markdownTable.append("井口距离".replace("|", "\\|")).append("|");
        markdownTable.append("井底距离".replace("|", "\\|")).append("|");
        markdownTable.append("井口纵距离".replace("|", "\\|")).append("|");
        markdownTable.append("井口横距离".replace("|", "\\|")).append("|");
        markdownTable.append("井底纵距离".replace("|", "\\|")).append("|");
        markdownTable.append("井底横距离".replace("|", "\\|")).append("|");
        markdownTable.append("\n");

        // 生成表头分隔线
        markdownTable.append("|");
        for (Field field : fields) {
            markdownTable.append("---|");
        }
        markdownTable.append("\n");

        // 生成数据行
        for (Ljjw ljjw : ljjwList) {
            markdownTable.append("|");
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    Object value = field.get(ljjw);
                    String valueStr = value != null ? value.toString() : "";
                    // 处理字段值中的|字符
                    valueStr = valueStr.replace("|", "\\|");
                    markdownTable.append(valueStr).append("|");
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            markdownTable.append("\n");
        }

        return markdownTable.toString();
    }


    /**
     * 调用大模型解析钻具组合
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping("/dyAiModelJxZjzh")
    public AjaxResult dyAiModelJxZjzh(@RequestBody CommonParam param) throws Exception{
        return AjaxResult.success(djdcService.dyAiModelJxZjzh(param));
    }

    /**
     * 调用长城大模型
     * @param param
     * @return
     */
    @PostMapping("/dyAiModel")
    public AjaxResult dyAiModel(CommonParam param){

        Map<String,Object> map=new HashMap<>();
        map.put("prompt",param.getZjzh()+" 这是一个钻具组合信息，请把这个钻具组合信息拆分成竖表，字段为钻具名称(zjmc)、型号(xh)、长度(cd),最终输出json格式数据,其他内容不输出,输出内容不换行，只要数据，反斜杠不输出");

        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);
        // 解析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");

        // 遍历数据数组
        for (JsonElement element : dataArray) {
            JsonObject item = element.getAsJsonObject();
            String zjmc = item.get("zjmc").getAsString();
            String xh = item.get("xh").getAsString();
            String cd = item.get("cd").getAsString();
            System.out.printf("组件名称: %s, 型号: %s, 长度: %s%n", zjmc, xh, cd);
        }


        return AjaxResult.success();
    }



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





}
