package cn.iocoder.yudao.module.pms.controller.admin.devicegroup;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.pms.ThingsModelDTO;
import cn.iocoder.yudao.module.pms.controller.admin.TableDataInfo;
import cn.iocoder.yudao.module.pms.controller.admin.iotprojecttask.vo.IotProjectTaskPageReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotDeviceDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.devicegroup.IotDeviceGroupDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.devicegroup.IotDeviceGroupDetailDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotprojecttask.IotProjectTaskDO;
import cn.iocoder.yudao.module.pms.dal.mysql.IotDeviceMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.iotdevicerunlog.IotDeviceRunLogMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.tdparams.IotTdParamsMapper;
import cn.iocoder.yudao.module.pms.service.IotDeviceService;
import cn.iocoder.yudao.module.pms.service.devicegroup.IotDeviceGroupDetailService;
import cn.iocoder.yudao.module.pms.service.devicegroup.IotDeviceGroupService;
import cn.iocoder.yudao.module.pms.service.iotprojecttask.IotProjectTaskService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - PMS成套")
@RestController
@RequestMapping("/rq/iot-device-group")
@Validated
public class IotDeviceGroupController {

    @Resource
    private IotDeviceGroupService iotDeviceGroupService;
    @Autowired
    private IotDeviceGroupDetailService iotDeviceGroupDetailService;
    @Autowired
    private DeptApi deptApi;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IotTdParamsMapper iotTdParamsMapper;
    @Value("${yanfan.url}")
    private String yanfanUrl;
    @Resource
    private IotDeviceService iotDeviceService;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private IotProjectTaskService iotProjectTaskService;
    @Resource
    private IotDeviceRunLogMapper iotDeviceRunLogMapper;

    private static final String[] ZYJ_PARAMS = {"一级排气温度", "二级排气温度", "三级排气温度", "四级排气温度1", "四级排气温度2", "四级排气温度3",
            "五级排气温度", "最终排气温度", "一级排气压力", "二级排气压力", "三级排气压力", "四级排气压力",
            "五级排气压力", "冷却水温度", "冷却水进口压力", "冷却水出口压力", "润滑油压力", "润滑油温度",
            "轴瓦温度1", "轴瓦温度2", "轴瓦温度3", "轴瓦温度4", "轴瓦温度5", "轴瓦温度6",
            "氮气纯度", "瞬时流量", "累计流量", "油压", "套压", "表套", "二套", "振动", "无油1#", "无油2#", "曲轴油位", "油泵状态", "风机状态", "急停状态"};
    @Autowired
    private IotDeviceMapper iotDeviceMapper;

    @PostMapping("/create")
    @Operation(summary = "创建PMS成套")
    @PreAuthorize("@ss.hasPermission('rq:iot-device-group:create')")
    public CommonResult<Long> createIotDeviceGroup(@Valid @RequestBody IotDeviceGroupSaveReqVO createReqVO) {
        return success(iotDeviceGroupService.createIotDeviceGroup(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新PMS成套")
    @PreAuthorize("@ss.hasPermission('rq:iot-device-group:update')")
    public CommonResult<Boolean> updateIotDeviceGroup(@Valid @RequestBody IotDeviceGroupSaveReqVO updateReqVO) {
        iotDeviceGroupService.updateIotDeviceGroup(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除PMS成套")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-device-group:delete')")
    public CommonResult<Boolean> deleteIotDeviceGroup(@RequestParam("id") Long id) {
        iotDeviceGroupService.deleteIotDeviceGroup(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得PMS成套")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-device-group:query')")
    public CommonResult<IotDeviceGroupRespVO> getIotDeviceGroup(@RequestParam("id") Long id) {
        IotDeviceGroupDO iotDeviceGroup = iotDeviceGroupService.getIotDeviceGroup(id);
        IotDeviceGroupRespVO bean = BeanUtils.toBean(iotDeviceGroup, IotDeviceGroupRespVO.class);
        List<IotDeviceGroupDetailDO> iotDeviceGroupDetailListByGroupId = iotDeviceGroupDetailService.getIotDeviceGroupDetailListByGroupId(iotDeviceGroup.getId());
        bean.setDetails(iotDeviceGroupDetailListByGroupId);
        return success(bean);
    }

    @GetMapping("/page")
    @Operation(summary = "获得PMS成套分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-device-group:query')")
    public CommonResult<PageResult<IotDeviceGroupRespVO>> getIotDeviceGroupPage(@Valid IotDeviceGroupPageReqVO pageReqVO) {
        PageResult<IotDeviceGroupDO> pageResult = iotDeviceGroupService.getIotDeviceGroupPage(pageReqVO);
        List<IotDeviceGroupRespVO> collect = pageResult.getList().stream().map(e -> {
            IotDeviceGroupRespVO bean = BeanUtil.toBean(e, IotDeviceGroupRespVO.class);
            List<IotDeviceGroupDetailDO> iotDeviceGroupDetailListByGroupId = iotDeviceGroupDetailService.getIotDeviceGroupDetailListByGroupId(e.getId());
            DeptRespDTO dept = deptApi.getDept(e.getDeptId());
            if (dept != null) {
                bean.setDeptName(dept.getName());
            }
            bean.setDetails(iotDeviceGroupDetailListByGroupId);
            List<Long> deviceIds = iotDeviceGroupDetailListByGroupId.stream().map(IotDeviceGroupDetailDO::getDeviceId).collect(Collectors.toList());
            List<IotDeviceDO> iotDeviceDOS = iotDeviceMapper.selectByIds(deviceIds);
            boolean b = iotDeviceDOS.stream().anyMatch(f -> Objects.nonNull(f.getIfInline())&&3 == f.getIfInline());
            bean.setIfOnline(b);
            return bean;
        }).collect(Collectors.toList());
        return success(new PageResult<>(collect, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出PMS成套 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-device-group:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotDeviceGroupExcel(@Valid IotDeviceGroupPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotDeviceGroupDO> list = iotDeviceGroupService.getIotDeviceGroupPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "PMS成套.xls", "数据", IotDeviceGroupRespVO.class,
                        BeanUtils.toBean(list, IotDeviceGroupRespVO.class));
    }


    @GetMapping("/device/group")
    @Operation(summary = "获得某设备的成套信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-device-group:query')")
    public CommonResult<PageResult<IotDeviceGroupDetailRespVO>> getDeviceGroup(@Valid IotDeviceGroupDetailPageReqVO reqVO) {
        PageResult<IotDeviceGroupDetailDO> deviceGroupList = iotDeviceGroupService.getDeviceGroupList(reqVO);
        if (Objects.isNull(deviceGroupList.getList())){
            return success(new PageResult<>(new ArrayList<>(),0L));
        }
        List<IotDeviceGroupDetailRespVO> collect = deviceGroupList.getList().stream().map(e -> {
            IotDeviceGroupDetailRespVO bean = BeanUtil.toBean(e, IotDeviceGroupDetailRespVO.class);
            IotDeviceGroupDO iotDeviceGroup = iotDeviceGroupService.getIotDeviceGroup(e.getGroupId());
            if (iotDeviceGroup != null) {
                bean.setGroupName(iotDeviceGroup.getName());
            }
            return bean;
        }).collect(Collectors.toList());
        return success(new PageResult<>(collect, deviceGroupList.getTotal()));
//        return success(deviceGroupList);
    }

    @GetMapping("/td/{id}")
    @Operation(summary = "获得某设备的成套信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-device-group:query')")
    public CommonResult<Map<String, Object>> getIotDeviceGroupDetail(@PathVariable("id") Long id) {
        List<IotDeviceGroupDetailDO> details = iotDeviceGroupDetailService.getIotDeviceGroupDetailListByGroupId(id);
        Map<String, Object> resultMap = new HashMap<>();
        Set<Long> groupDeptIds = new HashSet<>();
        Set<Long> deviceIds = new HashSet<>();
        details.forEach(e ->{
            AtomicBoolean nodata = new AtomicBoolean(false);
            IotDeviceDO iotDevice = iotDeviceService.getIotDevice(e.getDeviceId());
            if (ObjUtil.isNotEmpty(iotDevice.getYfDeviceId())) {
                TableDataInfo tableDataInfo = restTemplate.getForObject(yanfanUrl + "/prod-api/iot/device/listThingsModel?deviceId="+iotDevice.getYfDeviceId()+"&pageNum=1&pageSize=200", TableDataInfo.class);
                if (Objects.nonNull(tableDataInfo)) {
                    List<ThingsModelDTO> rows = JSON.parseArray(JSON.toJSONString(tableDataInfo.getRows()), ThingsModelDTO.class);
                    // 3000方以外的设备 只有增压机
                    if ("增压机".equals(iotDevice.getDeviceName())) {
                        List<IotDeviceGroupMonitorVO> monitors = new ArrayList<>();
                        if (CollUtil.isNotEmpty(rows)) {
                            rows.forEach(row -> {
                                if (!row.getModelName().contains("位置区码") && !row.getModelName().contains("小区ID") && !row.getModelName().contains("运营商")) {
                                    IotDeviceGroupMonitorVO monitor = new IotDeviceGroupMonitorVO();
                                    monitor.setModelName(row.getModelName());
                                    monitor.setValue(row.getValue());
                                    monitors.add(monitor);
                                }
                            });
                            // 增压机参数 列表 逆序
                            Collections.reverse(monitors);
                        }
                        resultMap.put("增压机", monitors);
                    }

                    // PSA 提纯撬 (氮气纯度 氮气压力 瞬时流量 累计流量 设备状态)
                    if ("提纯撬".equals(iotDevice.getDeviceName())) {
                        List<IotDeviceGroupMonitorVO> monitors = new ArrayList<>();
                        if (CollUtil.isNotEmpty(rows)) {
                            rows.forEach(row -> {
                                if (row.getModelName().contains("氮气纯度") || row.getModelName().contains("氮气压力") || row.getModelName().contains("瞬时流量") ||
                                        row.getModelName().contains("PSA累计流量") || row.getModelName().contains("运行状态")) {
                                    IotDeviceGroupMonitorVO monitor = new IotDeviceGroupMonitorVO();
                                    String originalName = row.getModelName();
                                    String psaPrefix = getModelNamePrefix(originalName, "PSA");
                                    // 去掉前缀，设置modelName
                                    if (StrUtil.isNotBlank(psaPrefix)) {
                                        // 使用replaceFirst去掉前缀
                                        String cleanedName = originalName.replaceFirst(psaPrefix, "");
                                        monitor.setModelName(cleanedName);
                                    } else {
                                        monitor.setModelName(originalName);
                                    }
                                    monitor.setValue(row.getValue());
                                    monitors.add(monitor);
                                }
                            });
                        } else {
                            // 没有返回数据 填充空值
                            IotDeviceGroupMonitorVO pure = new IotDeviceGroupMonitorVO();
                            pure.setModelName("氮气纯度");
                            pure.setValue("");
                            monitors.add(pure);
                            IotDeviceGroupMonitorVO pressure = new IotDeviceGroupMonitorVO();
                            pressure.setModelName("氮气压力");
                            pressure.setValue("");
                            monitors.add(pressure);
                            IotDeviceGroupMonitorVO instantFlow = new IotDeviceGroupMonitorVO();
                            instantFlow.setModelName("氮气瞬时流量");
                            instantFlow.setValue("");
                            monitors.add(instantFlow);
                            IotDeviceGroupMonitorVO totalFlow = new IotDeviceGroupMonitorVO();
                            totalFlow.setModelName("累计流量");
                            totalFlow.setValue("");
                            monitors.add(totalFlow);
                            IotDeviceGroupMonitorVO status = new IotDeviceGroupMonitorVO();
                            status.setModelName("运行状态");
                            status.setValue("");
                            monitors.add(status);
                        }
                        resultMap.put("PSA", monitors);
                    }
                    if ("空气处理撬".equals(iotDevice.getDeviceName())) {
                        List<IotDeviceGroupMonitorVO> monitors = new ArrayList<>();
                        if (CollUtil.isNotEmpty(rows)) {
                            rows.forEach(row -> {
                                if (row.getModelName().contains("进口温度") || "出口温度".equals(row.getModelName()) || row.getModelName().contains("出口压力")
                                        || row.getModelName().contains("风机运行状态")) {
                                    IotDeviceGroupMonitorVO monitor = new IotDeviceGroupMonitorVO();
                                    if (row.getModelName().contains("出口压力")) {
                                        monitor.setModelName("出口压力");
                                    } else {
                                        monitor.setModelName(row.getModelName());
                                    }
                                    monitor.setValue(row.getValue());
                                    monitors.add(monitor);
                                }
                            });
                        } else {
                            // 没有返回数据 填充空值
                            IotDeviceGroupMonitorVO enterTemp = new IotDeviceGroupMonitorVO();
                            enterTemp.setModelName("进口温度");
                            enterTemp.setValue("");
                            monitors.add(enterTemp);
                            IotDeviceGroupMonitorVO outTemp = new IotDeviceGroupMonitorVO();
                            outTemp.setModelName("出口温度");
                            outTemp.setValue("");
                            monitors.add(outTemp);
                            IotDeviceGroupMonitorVO outPress = new IotDeviceGroupMonitorVO();
                            outPress.setModelName("出口压力");
                            outPress.setValue("");
                            monitors.add(outPress);
                            /* IotDeviceGroupMonitorVO status = new IotDeviceGroupMonitorVO();
                            status.setModelName("冷干机运行状态");
                            status.setValue("");
                            monitors.add(status); */
                            IotDeviceGroupMonitorVO windStatus = new IotDeviceGroupMonitorVO();
                            windStatus.setModelName("风机运行状态");
                            windStatus.setValue("");
                            monitors.add(windStatus);
                        }
                        resultMap.put("空气处理撬", monitors);
                    }
                    if (iotDevice.getDeviceName().contains("中压")) {
                        List<IotDeviceGroupMonitorVO> monitors = new ArrayList<>();
                        if (CollUtil.isNotEmpty(rows)) {
                            rows.forEach(row -> {
                                if (row.getModelName().contains("排气压力") || row.getModelName().contains("排气温度") || row.getModelName().contains("系统压力") ||
                                        row.getModelName().contains("后轴承温度") || row.getModelName().contains("总运行时间") || row.getModelName().contains("设备状态")
                                        || row.getModelName().contains("总用电能")) {
                                    IotDeviceGroupMonitorVO monitor = new IotDeviceGroupMonitorVO();
                                    String originalName = row.getModelName();
                                    String prefix = getModelNamePrefix(originalName, "中压");
                                    // 去掉前缀，设置modelName
                                    if (StrUtil.isNotBlank(prefix)) {
                                        // 使用replaceFirst去掉前缀
                                        String cleanedName = originalName.replaceFirst(prefix, "");
                                        monitor.setModelName(cleanedName);
                                    } else {
                                        monitor.setModelName(originalName);
                                    }
                                    monitor.setValue(row.getValue());
                                    monitors.add(monitor);
                                }
                            });
                        } else {
                            // 没有返回数据 填充空值
                            IotDeviceGroupMonitorVO outPress = new IotDeviceGroupMonitorVO();
                            outPress.setModelName("排气压力");
                            outPress.setValue("");
                            monitors.add(outPress);
                            IotDeviceGroupMonitorVO outTemp = new IotDeviceGroupMonitorVO();
                            outTemp.setModelName("排气温度");
                            outTemp.setValue("");
                            monitors.add(outTemp);
                            IotDeviceGroupMonitorVO sysPress = new IotDeviceGroupMonitorVO();
                            sysPress.setModelName("系统压力");
                            sysPress.setValue("");
                            monitors.add(sysPress);
                            IotDeviceGroupMonitorVO backTemp = new IotDeviceGroupMonitorVO();
                            backTemp.setModelName("后轴承温度");
                            backTemp.setValue("");
                            monitors.add(backTemp);
                            IotDeviceGroupMonitorVO totalTime = new IotDeviceGroupMonitorVO();
                            totalTime.setModelName("总运行时间");
                            totalTime.setValue("");
                            monitors.add(totalTime);
                            IotDeviceGroupMonitorVO totalPower = new IotDeviceGroupMonitorVO();
                            totalPower.setModelName("总用电能");
                            totalPower.setValue("");
                            monitors.add(totalPower);
                            IotDeviceGroupMonitorVO status = new IotDeviceGroupMonitorVO();
                            status.setModelName("设备状态");
                            status.setValue("");
                            monitors.add(status);
                        }
                        resultMap.put("中压机", monitors);
                    }
                    if ("空压机".equals(iotDevice.getDeviceName())) {
                        List<IotDeviceGroupMonitorVO> monitors = new ArrayList<>();
                        Set<String> kongYaParts = new HashSet<>();
                        if (CollUtil.isNotEmpty(rows)) {
                            rows.forEach(row -> {
                                if (row.getModelName().contains("空压")) {
                                    // 获取 空压x 部分作为 key 值
                                    kongYaParts.add(getKongYaPart(row.getModelName()));
                                }
                                if (row.getModelName().contains("累计运行时间") || row.getModelName().contains("累计加载时间") || row.getModelName().contains("排气压力") ||
                                        row.getModelName().contains("排气温度") || row.getModelName().contains("环境温度") || row.getModelName().contains("系统压力")
                                        || row.getModelName().contains("喷油温度") || row.getModelName().contains("喷油压力") ||
                                        row.getModelName().contains("运行状态")) {
                                    IotDeviceGroupMonitorVO monitor = new IotDeviceGroupMonitorVO();
                                    // 属性名称去掉 空压x
                                    // 获取"空压x"前缀部分
                                    String originalName = row.getModelName();
                                    String kongYaPrefix = getKongYaPart(originalName);
                                    // 去掉前缀，设置modelName
                                    if (StrUtil.isNotBlank(kongYaPrefix)) {
                                        // 方法1：使用replaceFirst去掉前缀
                                        String cleanedName = originalName.replaceFirst(kongYaPrefix, "");
                                        monitor.setModelName(cleanedName);
                                    } else {
                                        monitor.setModelName(originalName);
                                    }
                                    monitor.setValue(row.getValue());
                                    monitors.add(monitor);
                                    // 排序 运行状态 加载状态 字段 置后
                                    monitors.sort(Comparator.comparingInt(m ->
                                            m.getModelName().contains("加载状态") ? 2 :
                                                    m.getModelName().contains("运行状态") ? 1 : 0
                                    ));
                                }
                            });
                        }
                        if (CollUtil.isNotEmpty(kongYaParts)) {
                            resultMap.put(new ArrayList<>(kongYaParts).get(0), monitors);
                        }
                    }
                    if ("液驱机".equals(iotDevice.getDeviceName())) {
                        List<IotDeviceGroupMonitorVO> monitors = new ArrayList<>();
                        if (CollUtil.isNotEmpty(rows)) {
                            rows.forEach(row -> {
                                if (row.getModelName().contains("入口压力") || row.getModelName().contains("出口温度") || row.getModelName().contains("冷却后温度") ||
                                        row.getModelName().contains("出口压力")) {
                                    IotDeviceGroupMonitorVO monitor = new IotDeviceGroupMonitorVO();
                                    String originalName = row.getModelName();
                                    String prefix = getModelNamePrefix(originalName, "液驱");
                                    // 去掉前缀，设置modelName
                                    if (StrUtil.isNotBlank(prefix)) {
                                        // 使用replaceFirst去掉前缀
                                        String cleanedName = originalName.replaceFirst(prefix, "");
                                        monitor.setModelName(cleanedName);
                                    } else {
                                        monitor.setModelName(originalName);
                                    }
                                    monitor.setValue(row.getValue());
                                    monitors.add(monitor);
                                }
                            });
                        } else {
                            // 没有返回数据 填充空值
                            IotDeviceGroupMonitorVO enterPressure = new IotDeviceGroupMonitorVO();
                            enterPressure.setModelName("入口压力");
                            enterPressure.setValue("");
                            monitors.add(enterPressure);
                            IotDeviceGroupMonitorVO onePressure = new IotDeviceGroupMonitorVO();
                            onePressure.setModelName("一级入口压力");
                            onePressure.setValue("");
                            monitors.add(onePressure);
                            IotDeviceGroupMonitorVO aOneOutTemp = new IotDeviceGroupMonitorVO();
                            aOneOutTemp.setModelName("A缸一级出口温度");
                            aOneOutTemp.setValue("");
                            monitors.add(aOneOutTemp);
                            IotDeviceGroupMonitorVO aOneColdTemp = new IotDeviceGroupMonitorVO();
                            aOneColdTemp.setModelName("A缸一级冷却后温度");
                            aOneColdTemp.setValue("");
                            monitors.add(aOneColdTemp);
                            IotDeviceGroupMonitorVO aTwoEnterPressure = new IotDeviceGroupMonitorVO();
                            aTwoEnterPressure.setModelName("A缸二级入口压力");
                            aTwoEnterPressure.setValue("");
                            monitors.add(aTwoEnterPressure);

                            IotDeviceGroupMonitorVO aTwoOutTemp = new IotDeviceGroupMonitorVO();
                            aTwoOutTemp.setModelName("A缸二级出口温度");
                            aTwoOutTemp.setValue("");
                            monitors.add(aTwoOutTemp);
                            IotDeviceGroupMonitorVO aTwoColdTemp = new IotDeviceGroupMonitorVO();
                            aTwoColdTemp.setModelName("A缸二级冷却后温度");
                            aTwoColdTemp.setValue("");
                            monitors.add(aTwoColdTemp);
                            IotDeviceGroupMonitorVO aThreeEnterPress = new IotDeviceGroupMonitorVO();
                            aThreeEnterPress.setModelName("A缸三级入口压力");
                            aThreeEnterPress.setValue("");
                            monitors.add(aThreeEnterPress);
                            IotDeviceGroupMonitorVO bOneOutTemp = new IotDeviceGroupMonitorVO();
                            bOneOutTemp.setModelName("B缸一级出口温度");
                            bOneOutTemp.setValue("");
                            monitors.add(bOneOutTemp);
                            IotDeviceGroupMonitorVO bOneColdTemp = new IotDeviceGroupMonitorVO();
                            bOneColdTemp.setModelName("B缸一级冷却后温度");
                            bOneColdTemp.setValue("");
                            monitors.add(bOneColdTemp);

                            IotDeviceGroupMonitorVO bTwoEnterPress = new IotDeviceGroupMonitorVO();
                            bTwoEnterPress.setModelName("B缸二级入口压力");
                            bTwoEnterPress.setValue("");
                            monitors.add(bTwoEnterPress);
                            IotDeviceGroupMonitorVO bTwoOutTemp = new IotDeviceGroupMonitorVO();
                            bTwoOutTemp.setModelName("B缸二级出口温度");
                            bTwoOutTemp.setValue("");
                            monitors.add(bTwoOutTemp);
                            IotDeviceGroupMonitorVO bTwoColdTemp = new IotDeviceGroupMonitorVO();
                            bTwoColdTemp.setModelName("B缸二级冷却后温度");
                            bTwoColdTemp.setValue("");
                            monitors.add(bTwoColdTemp);
                            IotDeviceGroupMonitorVO bThreeEnterPress = new IotDeviceGroupMonitorVO();
                            bThreeEnterPress.setModelName("B缸三级入口压力");
                            bThreeEnterPress.setValue("");
                            monitors.add(bThreeEnterPress);
                            IotDeviceGroupMonitorVO threeOutTemp = new IotDeviceGroupMonitorVO();
                            threeOutTemp.setModelName("三级出口温度");
                            threeOutTemp.setValue("");
                            monitors.add(threeOutTemp);
                            IotDeviceGroupMonitorVO totalOutTemp = new IotDeviceGroupMonitorVO();
                            totalOutTemp.setModelName("总出口温度");
                            totalOutTemp.setValue("");
                            monitors.add(totalOutTemp);
                            IotDeviceGroupMonitorVO totalOutPress = new IotDeviceGroupMonitorVO();
                            totalOutPress.setModelName("总出口压力");
                            totalOutPress.setValue("");
                            monitors.add(totalOutPress);
                        }
                        resultMap.put("液驱机", monitors);
                    }
                } else {
                    // yanfan 接口异常 返回空数据
                    nodata.set(true);
                }
            } else {
                // 设备没有 yanfan deviceId
                nodata.set(true);
            }
            if (nodata.get()) {
                if ("空气处理撬".equals(iotDevice.getDeviceName())) {
                    List<IotDeviceGroupMonitorVO> monitors = new ArrayList<>();
                    // 没有返回数据 填充空值
                    IotDeviceGroupMonitorVO enterTemp = new IotDeviceGroupMonitorVO();
                    enterTemp.setModelName("进口温度");
                    enterTemp.setValue("");
                    monitors.add(enterTemp);
                    IotDeviceGroupMonitorVO outTemp = new IotDeviceGroupMonitorVO();
                    outTemp.setModelName("出口温度");
                    outTemp.setValue("");
                    monitors.add(outTemp);
                    IotDeviceGroupMonitorVO outPress = new IotDeviceGroupMonitorVO();
                    outPress.setModelName("空气处理撬出口压力");
                    outPress.setValue("");
                    monitors.add(outPress);
                    /* IotDeviceGroupMonitorVO status = new IotDeviceGroupMonitorVO();
                    status.setModelName("冷干机运行状态");
                    status.setValue("");
                    monitors.add(status); */
                    IotDeviceGroupMonitorVO windStatus = new IotDeviceGroupMonitorVO();
                    windStatus.setModelName("风机运行状态");
                    windStatus.setValue("");
                    monitors.add(windStatus);
                    resultMap.put("空气处理撬", monitors);
                }
                if ("液驱机".equals(iotDevice.getDeviceName())) {
                    List<IotDeviceGroupMonitorVO> monitors = new ArrayList<>();
                    // 没有返回数据 填充空值
                    IotDeviceGroupMonitorVO enterPressure = new IotDeviceGroupMonitorVO();
                    enterPressure.setModelName("液驱入口压力");
                    enterPressure.setValue("");
                    monitors.add(enterPressure);
                    IotDeviceGroupMonitorVO onePressure = new IotDeviceGroupMonitorVO();
                    onePressure.setModelName("液驱一级入口压力");
                    onePressure.setValue("");
                    monitors.add(onePressure);
                    IotDeviceGroupMonitorVO aOneOutTemp = new IotDeviceGroupMonitorVO();
                    aOneOutTemp.setModelName("液驱A缸一级出口温度");
                    aOneOutTemp.setValue("");
                    monitors.add(aOneOutTemp);
                    IotDeviceGroupMonitorVO aOneColdTemp = new IotDeviceGroupMonitorVO();
                    aOneColdTemp.setModelName("液驱A缸一级冷却后温度");
                    aOneColdTemp.setValue("");
                    monitors.add(aOneColdTemp);
                    IotDeviceGroupMonitorVO aTwoEnterPressure = new IotDeviceGroupMonitorVO();
                    aTwoEnterPressure.setModelName("A缸二级入口压力");
                    aTwoEnterPressure.setValue("");
                    monitors.add(aTwoEnterPressure);

                    IotDeviceGroupMonitorVO aTwoOutTemp = new IotDeviceGroupMonitorVO();
                    aTwoOutTemp.setModelName("A缸二级出口温度");
                    aTwoOutTemp.setValue("");
                    monitors.add(aTwoOutTemp);
                    IotDeviceGroupMonitorVO aTwoColdTemp = new IotDeviceGroupMonitorVO();
                    aTwoColdTemp.setModelName("A缸二级冷却后温度");
                    aTwoColdTemp.setValue("");
                    monitors.add(aTwoColdTemp);
                    IotDeviceGroupMonitorVO aThreeEnterPress = new IotDeviceGroupMonitorVO();
                    aThreeEnterPress.setModelName("A缸三级入口压力");
                    aThreeEnterPress.setValue("");
                    monitors.add(aThreeEnterPress);
                    IotDeviceGroupMonitorVO bOneOutTemp = new IotDeviceGroupMonitorVO();
                    bOneOutTemp.setModelName("B缸一级出口温度");
                    bOneOutTemp.setValue("");
                    monitors.add(bOneOutTemp);
                    IotDeviceGroupMonitorVO bOneColdTemp = new IotDeviceGroupMonitorVO();
                    bOneColdTemp.setModelName("B缸一级冷却后温度");
                    bOneColdTemp.setValue("");
                    monitors.add(bOneColdTemp);

                    IotDeviceGroupMonitorVO bTwoEnterPress = new IotDeviceGroupMonitorVO();
                    bTwoEnterPress.setModelName("B缸二级入口压力");
                    bTwoEnterPress.setValue("");
                    monitors.add(bTwoEnterPress);
                    IotDeviceGroupMonitorVO bTwoOutTemp = new IotDeviceGroupMonitorVO();
                    bTwoOutTemp.setModelName("B缸二级出口温度");
                    bTwoOutTemp.setValue("");
                    monitors.add(bTwoOutTemp);
                    IotDeviceGroupMonitorVO bTwoColdTemp = new IotDeviceGroupMonitorVO();
                    bTwoColdTemp.setModelName("B缸二级冷却后温度");
                    bTwoColdTemp.setValue("");
                    monitors.add(bTwoColdTemp);
                    IotDeviceGroupMonitorVO bThreeEnterPress = new IotDeviceGroupMonitorVO();
                    bThreeEnterPress.setModelName("B缸三级入口压力");
                    bThreeEnterPress.setValue("");
                    monitors.add(bThreeEnterPress);
                    IotDeviceGroupMonitorVO threeOutTemp = new IotDeviceGroupMonitorVO();
                    threeOutTemp.setModelName("三级出口温度");
                    threeOutTemp.setValue("");
                    monitors.add(threeOutTemp);
                    IotDeviceGroupMonitorVO totalOutTemp = new IotDeviceGroupMonitorVO();
                    totalOutTemp.setModelName("总出口温度");
                    totalOutTemp.setValue("");
                    monitors.add(totalOutTemp);
                    IotDeviceGroupMonitorVO totalOutPress = new IotDeviceGroupMonitorVO();
                    totalOutPress.setModelName("总出口压力");
                    totalOutPress.setValue("");
                    monitors.add(totalOutPress);
                    resultMap.put("液驱机", monitors);
                }
                if (iotDevice.getDeviceName().contains("中压")) {
                    List<IotDeviceGroupMonitorVO> monitors = new ArrayList<>();
                    // 没有返回数据 填充空值
                    IotDeviceGroupMonitorVO outPress = new IotDeviceGroupMonitorVO();
                    outPress.setModelName("中压排气压力");
                    outPress.setValue("");
                    monitors.add(outPress);
                    IotDeviceGroupMonitorVO outTemp = new IotDeviceGroupMonitorVO();
                    outTemp.setModelName("中压排气温度");
                    outTemp.setValue("");
                    monitors.add(outTemp);
                    IotDeviceGroupMonitorVO sysPress = new IotDeviceGroupMonitorVO();
                    sysPress.setModelName("中压系统压力");
                    sysPress.setValue("");
                    monitors.add(sysPress);
                    IotDeviceGroupMonitorVO backTemp = new IotDeviceGroupMonitorVO();
                    backTemp.setModelName("中压后轴承温度");
                    backTemp.setValue("");
                    monitors.add(backTemp);
                    IotDeviceGroupMonitorVO totalTime = new IotDeviceGroupMonitorVO();
                    totalTime.setModelName("中压总运行时间");
                    totalTime.setValue("");
                    monitors.add(totalTime);
                    IotDeviceGroupMonitorVO totalPower = new IotDeviceGroupMonitorVO();
                    totalPower.setModelName("总用电能");
                    totalPower.setValue("");
                    monitors.add(totalPower);
                    IotDeviceGroupMonitorVO status = new IotDeviceGroupMonitorVO();
                    status.setModelName("设备状态");
                    status.setValue("");
                    monitors.add(status);
                    resultMap.put("中压机", monitors);
                }
                if ("提纯撬".equals(iotDevice.getDeviceName())) {
                    List<IotDeviceGroupMonitorVO> monitors = new ArrayList<>();
                    // 没有返回数据 填充空值
                    IotDeviceGroupMonitorVO pure = new IotDeviceGroupMonitorVO();
                    pure.setModelName("PSA氮气纯度");
                    pure.setValue("");
                    monitors.add(pure);
                    IotDeviceGroupMonitorVO pressure = new IotDeviceGroupMonitorVO();
                    pressure.setModelName("PSA氮气压力");
                    pressure.setValue("");
                    monitors.add(pressure);
                    IotDeviceGroupMonitorVO instantFlow = new IotDeviceGroupMonitorVO();
                    instantFlow.setModelName("PSA氮气瞬时流量");
                    instantFlow.setValue("");
                    monitors.add(instantFlow);
                    IotDeviceGroupMonitorVO totalFlow = new IotDeviceGroupMonitorVO();
                    totalFlow.setModelName("PSA累计流量");
                    totalFlow.setValue("");
                    monitors.add(totalFlow);
                    IotDeviceGroupMonitorVO status = new IotDeviceGroupMonitorVO();
                    status.setModelName("PSA运行状态");
                    status.setValue("");
                    monitors.add(status);
                    resultMap.put("PSA", monitors);
                }
                if ("增压机".equals(iotDevice.getDeviceName())) {
                    List<IotDeviceGroupMonitorVO> zyjParams = createDefaultMonitors(ZYJ_PARAMS);
                    resultMap.put("PS增压机", zyjParams);
                }
            }
            groupDeptIds.add(iotDevice.getDeptId());
            // 如果是增压机 设置增压机编号
            if ("增压机".equals(iotDevice.getDeviceName())) {
                resultMap.put("deviceCode", iotDevice.getDeviceCode());
                deviceIds.add(iotDevice.getId());
            }
        });
        // 查询增压机的累计运行时间
        if (CollUtil.isNotEmpty(deviceIds)) {
            BigDecimal totalRuntime = iotDeviceRunLogMapper.theMaxTotalRuntime(new ArrayList<>(deviceIds).get(0), "累计运行时间H");
            resultMap.put("totalRuntime", totalRuntime);
        }
        // 查询此成套对应的 部门 - 任务井信息 多个井用逗号分隔
        List<String> wellNames = new ArrayList<>();
        String wellNameStr = StrUtil.EMPTY;
        String deptName = StrUtil.EMPTY;
        if (CollUtil.isNotEmpty(groupDeptIds)) {
            List<Long> deptIdList = new ArrayList<>(groupDeptIds);
            IotProjectTaskPageReqVO pageReqVO = new IotProjectTaskPageReqVO();
            pageReqVO.setDeptId(deptIdList.get(0));
            List<IotProjectTaskDO> tasks = iotProjectTaskService.taskWellNames(pageReqVO);
            if (CollUtil.isNotEmpty(tasks)) {
                tasks.forEach(task -> {
                    wellNames.add(task.getWellName());
                });
            }
            if (CollUtil.isNotEmpty(wellNames)) {
                wellNameStr = StrUtil.join(",", wellNames);
                resultMap.put("wellName", wellNameStr);
            }
            // 查询部门名称
            DeptRespDTO dept = deptApi.getDept(deptIdList.get(0));
            deptName = dept.getName();
            resultMap.put("deptName", deptName);
        }
        // 查询成套名称
        IotDeviceGroupDO deviceGroup = iotDeviceGroupService.getIotDeviceGroup(id);
        String groupName = StrUtil.EMPTY;
        if (ObjUtil.isNotEmpty(deviceGroup)) {
            groupName = deviceGroup.getName();
            resultMap.put("groupName", groupName);
        }
        // 5个空压机 1个液驱压缩机 1个PSA 1个空气处理撬 1个中压机
        // 空压机参数 (累计运行时间 累计加载时间 排气压力 排气温度 环境温度 系统压力 喷油温度 喷油压力 运行状态 加载状态)
        // PSA参数 (氮气纯度 氮气压力 瞬时流量 累计流量 设备状态)

        // 液驱压缩机参数 (入口压力 一级入口压力 A缸一级出口温度 A缸一级冷却后温度 A缸二级入口压力 A缸二级出口温度
        // A缸二级冷却后温度 A缸三级入口压力 B缸一级出口温度 B缸一级冷却后温度 B缸二级入口压力 B缸二级出口温度
        // B缸二级冷却后温度 B缸三级入口压力 三级出口温度 总出口温度 总出口压力)

        // 空气处理撬参数 (进口温度 出口温度 出口压力 冷干机运行状态 风机运行状态)

        // 中压机参数 (排气压力 排气温度 系统压力 后轴承温度 总运行时间 设备状态 总用电能)

        return success(resultMap);
    }

    /**
     * 创建默认监控对象列表（值为空）
     * @param params 参数名称数组
     * @return 监控对象列表
     */
    private List<IotDeviceGroupMonitorVO> createDefaultMonitors(String[] params) {
        return Arrays.stream(params)
                .map(param -> {
                    IotDeviceGroupMonitorVO monitor = new IotDeviceGroupMonitorVO();
                    monitor.setModelName(param);
                    monitor.setValue(""); // 值留空
                    return monitor;
                })
                .collect(Collectors.toList());
    }

    /**
     * Java8风格：仅基于“空压”截取字符串，不依赖任何其他分隔符
     * @param input 原始字符串
     * @return 截取结果（无匹配返回空字符串）
     */
    private static String getKongYaPart(String input) {
        Pattern KONG_YA_PATTERN = Pattern.compile("空压\\d*");
        return Optional.ofNullable(input)          // 处理输入为null的情况
                .filter(str -> str.contains("空压")) // 仅判断是否包含“空压”
                .map(str -> {
                    Matcher matcher = KONG_YA_PATTERN.matcher(str);
                    // 找到第一个匹配的“空压+数字”子串，无则返回空
                    return matcher.find() ? matcher.group() : "";
                })
                .orElse(""); // 无“空压”/输入null时返回空字符串
    }

    /**
     * J仅基于“PSA”截取字符串，不依赖任何其他分隔符
     * @param input 原始字符串
     * @return 截取结果（无匹配返回空字符串）
     */
    private static String getModelNamePrefix(String input, String prefix) {
        Pattern PSA_PATTERN = Pattern.compile(prefix);
        return Optional.ofNullable(input)          // 处理输入为null的情况
                .filter(str -> str.contains(prefix)) // 仅判断是否包含“空压”
                .map(str -> {
                    Matcher matcher = PSA_PATTERN.matcher(str);
                    // 找到第一个匹配的“PSA”子串，无则返回空
                    return matcher.find() ? matcher.group() : "";
                })
                .orElse(""); // 无“PSA”/输入null时返回空字符串
    }

}
