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

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

import com.zjsgfa.common.utils.DateUtils;
import com.zjsgfa.project.zjsgfa.domain.SjZjyFdxnb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zjsgfa.project.zjsgfa.mapper.SjSggyZjyFdxnbMapper;
import com.zjsgfa.project.zjsgfa.domain.SjSggyZjyFdxnb;
import com.zjsgfa.project.zjsgfa.service.ISjSggyZjyFdxnbService;

/**
 * 设计信息-施工概要-分段钻井液性能设计Service业务层处理
 * 
 * @author
 * @date 2025-08-20
 */
@Service
public class SjSggyZjyFdxnbServiceImpl implements ISjSggyZjyFdxnbService 
{
    @Autowired
    private SjSggyZjyFdxnbMapper sjSggyZjyFdxnbMapper;

    /**
     * 查询设计信息-施工概要-分段钻井液性能设计
     * 
     * @param id 设计信息-施工概要-分段钻井液性能设计主键
     * @return 设计信息-施工概要-分段钻井液性能设计
     */
    @Override
    public SjSggyZjyFdxnb selectSjSggyZjyFdxnbById(Long id)
    {
        return sjSggyZjyFdxnbMapper.selectSjSggyZjyFdxnbById(id);
    }

    private static int extractStartNumber(String jd) {
        if (jd == null || !jd.contains("～")) {
            return 0; // 处理异常情况
        }
        String numberPart = jd.split("～")[0];
        try {
            return Integer.parseInt(numberPart.trim());
        } catch (NumberFormatException e) {
            return 0; // 处理转换失败情况
        }
    }
    /**
     * 查询设计信息-施工概要-分段钻井液性能设计列表
     * 
     * @param sjSggyZjyFdxnb 设计信息-施工概要-分段钻井液性能设计
     * @return 设计信息-施工概要-分段钻井液性能设计
     */
    @Override
    public Map<String, Object> selectSjSggyZjyFdxnbList(SjSggyZjyFdxnb sjSggyZjyFdxnb)
    {
        List<SjSggyZjyFdxnb> list = sjSggyZjyFdxnbMapper.selectSjSggyZjyFdxnbList(sjSggyZjyFdxnb);
        List<Map<String, String>> fixedItems = Arrays.asList(
                new HashMap<String, String>() {{ put("name", "密度(g/cm³)"); put("field", "md"); }},
                new HashMap<String, String>() {{ put("name", "马氏漏斗黏度(s)"); put("field", "msldnd"); }},
                new HashMap<String, String>() {{ put("name", "API滤失量(ml)"); put("field", "apilsl"); }},
                new HashMap<String, String>() {{ put("name", "API泥饼(mm)"); put("field", "apinb"); }},
                new HashMap<String, String>() {{ put("name", "静切力(Pa)"); put("field", "jql"); }},
                new HashMap<String, String>() {{ put("name", "pH值"); put("field", "ph"); }},
                new HashMap<String, String>() {{ put("name", "含砂量(%)"); put("field", "hsl"); }},
                new HashMap<String, String>() {{ put("name", "总固含(%)"); put("field", "zgh"); }},
                new HashMap<String, String>() {{ put("name", "摩阻系数"); put("field", "mzxs"); }},
                new HashMap<String, String>() {{ put("name", "动切力(Pa)"); put("field", "dql"); }},
                new HashMap<String, String>() {{ put("name", "塑性黏度(mPa·s)"); put("field", "sxnd"); }},
                new HashMap<String, String>() {{ put("name", "HTHP失水 (ml)"); put("field", "hthpss"); }},
                new HashMap<String, String>() {{ put("name", "HTHP泥饼 (mm)"); put("field", "hthpnb"); }},
                new HashMap<String, String>() {{ put("name", "MBT"); put("field", "mbt"); }},
                new HashMap<String, String>() {{ put("name", "id"); put("field", "id"); }}
        );

        // 提取井段（去重，按顺序排列）
//        List<String> wellSegments = list.stream()
//                .map(SjSggyZjyFdxnb::getJd)
//                .distinct().sorted((s1, s2) -> {
//                    // 提取第一个数值
//                    int num1 = extractStartNumber(s1);
//                    int num2 = extractStartNumber(s2);
//                    return Integer.compare(num1, num2);
//                })
//                .collect(Collectors.toList());
        List<String> wellSegments = list.stream().sorted(Comparator.comparing(SjSggyZjyFdxnb::getFirstNumber))
                .map(SjSggyZjyFdxnb::getJd)
                .distinct()
                .collect(Collectors.toList());
        // 表格数据：每行对应一个固定项目，每列对应一个井段
        List<Map<String, String>> tableData = new ArrayList<>();

        for (Map<String, String> item : fixedItems) {
            String itemName = item.get("name"); // 项目名称（如"密度(g/cm³)"）
            String fieldName = item.get("field"); // 实体类字段名（如"md"）

            Map<String, String> row = new HashMap<>();
            row.put("项目", itemName); // 第一列固定为项目名称
            row.put("field", fieldName); // 第一列固定为项目名称

            // 遍历每个井段，填充对应字段的值
            for (String segment : wellSegments) {
                // 找到当前井段的数据对象
                SjSggyZjyFdxnb segmentData = list.stream()
                        .filter(d -> segment.equals(d.getJd()))
                        .findFirst()
                        .orElse(null);

                // 通过反射获取字段值（避免大量if-else）
                String value = "";
                if (segmentData != null) {
                    try {
                        Field field = SjSggyZjyFdxnb.class.getDeclaredField(fieldName);
                        field.setAccessible(true);
                        Object fieldValue = field.get(segmentData);
                        value = fieldValue != null ? fieldValue.toString() : "";
                    } catch (Exception e) {
                        value = "";
                    }
                }
                row.put(segment, value); // 列名为井段，值为字段值
            }
            tableData.add(row);
        }

        Map<String,Object> map =new HashMap<>();
        map.put("jds",wellSegments);
        map.put("data",tableData);
        return map;

    }

    /**
     * 新增设计信息-施工概要-分段钻井液性能设计
     * 
     * @param sjSggyZjyFdxnb 设计信息-施工概要-分段钻井液性能设计
     * @return 结果
     */
    @Override
    public int insertSjSggyZjyFdxnb(SjSggyZjyFdxnb sjSggyZjyFdxnb)
    {
        return sjSggyZjyFdxnbMapper.insertSjSggyZjyFdxnb(sjSggyZjyFdxnb);
    }

    /**
     * 修改设计信息-施工概要-分段钻井液性能设计
     * 
     * @param sjSggyZjyFdxnb 设计信息-施工概要-分段钻井液性能设计
     * @return 结果
     */
    @Override
    public int updateSjSggyZjyFdxnb(SjSggyZjyFdxnb sjSggyZjyFdxnb)
    {
        sjSggyZjyFdxnb.setUpdateTime(DateUtils.getNowDate());
        return sjSggyZjyFdxnbMapper.updateSjSggyZjyFdxnb(sjSggyZjyFdxnb);
    }

    /**
     * 批量删除设计信息-施工概要-分段钻井液性能设计
     * 
     * @param ids 需要删除的设计信息-施工概要-分段钻井液性能设计主键
     * @return 结果
     */
    @Override
    public int deleteSjSggyZjyFdxnbByIds(Long[] ids)
    {
        return sjSggyZjyFdxnbMapper.deleteSjSggyZjyFdxnbByIds(ids);
    }

    /**
     * 删除设计信息-施工概要-分段钻井液性能设计信息
     * 
     * @param id 设计信息-施工概要-分段钻井液性能设计主键
     * @return 结果
     */
    @Override
    public int deleteSjSggyZjyFdxnbById(Long id)
    {
        return sjSggyZjyFdxnbMapper.deleteSjSggyZjyFdxnbById(id);
    }

    @Override
    public int insertSjSggyZjyFdxnbBatch(List<SjSggyZjyFdxnb> list) {
        if(list.size()>0){
            sjSggyZjyFdxnbMapper.deleteSjSggyZjyFdxnbByJh(list.get(0).getJh());
        }

        return sjSggyZjyFdxnbMapper.insertSjSggyZjyFdxnbBatch(list);
    }
}
