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

import cn.hutool.http.HttpRequest;
import com.google.gson.*;
import com.ruoyi.project.zt.domian.*;
import com.ruoyi.project.zt.mapper.DjdcInfoMapper;
import com.ruoyi.project.zt.mapper.JstaMapper;
import com.ruoyi.project.zt.mapper.JswaMapper;
import com.ruoyi.project.zt.service.DjdcService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DjdcServiceImpl implements DjdcService {

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

    @Autowired
    private JswaMapper jswaMapper;


    @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())){
            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){
            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.equals("PDC钻头")){
                    String wpc = item.getWpc();
                    String npc = item.getNpc();
                    String wpcqk="";
                    String npcqk="";
                    if(StringUtils.isNotEmpty(wpc)){
                        for(int i=0 ;i<9;i++){
                            if(Integer.parseInt(wpc)==i){
                                if(i==0){
                                    wpcqk="外排齿：无磨损";
                                }else {
                                    wpcqk="外排齿：1/"+i+"磨损";
                                }
                                break;
                            }
                        }
                    }

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

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

                    if(StringUtils.isNotEmpty(zc)){
                        for(int i=1 ;i<9;i++){
                            if(Integer.parseInt(zc)==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.getValue());
                }
            }

        }
        return list;
    }

    @Override
    public List<DjZqsjfx> getZqshfxList(CommonParam param) {
        //查询临井
        List<DjZqsjfx> list =djdcInfoMapper.getZqshfxList(param);
        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));
            //查询周期
            Jsta jsta =new Jsta();
            jsta.setJh(item.getJh());
            jsta.setJd2(item.getJs());
            jsta.setJd1(item.getKsjs());
            List<Jsta> jstaList = jstaMapper.getList(jsta);
            Double zjzq =0.0;
            Double zwzq =0.0;
            Double js = item.getJs();
            for(Jsta it:jstaList){
                Double jd1=it.getJd1()==null?0.0:it.getJd1();
                Double jd2=it.getJd2()==null?0.0:it.getJd2();
                if(jd1==0&jd2==0){
                    continue;
                } else if(jd1.equals(js) && js.equals(jd2)){
                    zwzq=zwzq+it.getSjts();
                }else {
                    zjzq=zjzq+it.getSjts();
                }
            }
            item.setZjzq(zjzq);
            item.setZwzq(zwzq);
            item.setZjsl(item.getJc()/item.getZjzq());
            //查询钻井日志
            Jswa jswa =new Jswa();
            jswa.setJh(item.getJh());
            jswa.setJs(item.getJs());
            jswa.setKsjs(item.getKsjs());
            List<Jswa> jswaList=jswaMapper.getList(jswa);
            Double zjycsl=0.0;
            Double wjycsl=0.0;
            for(Jswa wa:jswaList){
                Double js1 = wa.getJs();
                Double rjc = wa.getRjc();
                if (rjc!=0 && js1<= js) {
                    //钻进
                    zjycsl=zjycsl+(wa.getSg()+wa.getXl()+wa.getZrtg()+wa.getZztg()+wa.getFzqk());
                }else if(rjc==0 && Objects.equals(js1, item.getJs())) {
                    //完井
                    wjycsl=wjycsl+(wa.getSg()+wa.getXl()+wa.getZrtg()+wa.getZztg()+wa.getFzqk());
                }
            }
            item.setZjycsl(zjycsl);
            item.setWjycsl(wjycsl);
        }


        return list;
    }

    @Override
    public List<DjZjzhfx> getZjzhfxList(CommonParam param) {
        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 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);
                //查询进尺和时效
                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;
    }



    /**
     * 从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();
    }




}
