package com.ruoyi.ems.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.huashe.common.utils.DateUtils;
import com.huashe.common.utils.uuid.Seq;
import com.ruoyi.ems.domain.CheckItemResult;
import com.ruoyi.ems.domain.EmsDevice;
import com.ruoyi.ems.domain.EmsObjAttrValue;
import com.ruoyi.ems.domain.InspectionPlan;
import com.ruoyi.ems.domain.InspectionReport;
import com.ruoyi.ems.domain.InspectionReportDetail;
import com.ruoyi.ems.domain.InspectionRule;
import com.ruoyi.ems.domain.ManualReportSubmit;
import com.ruoyi.ems.mapper.InspectionPlanMapper;
import com.ruoyi.ems.mapper.InspectionReportDetailMapper;
import com.ruoyi.ems.mapper.InspectionReportMapper;
import com.ruoyi.ems.mapper.InspectionRuleMapper;
import com.ruoyi.ems.model.QueryDevice;
import com.ruoyi.ems.service.IEmsDeviceService;
import com.ruoyi.ems.service.IEmsObjAttrValueService;
import com.ruoyi.ems.service.IInspectionPlanService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * 巡检计划Service实现
 */
@Service
public class InspectionPlanServiceImpl implements IInspectionPlanService {

    private static final Logger log = LoggerFactory.getLogger(InspectionPlanServiceImpl.class);

    /** 计划类型常量 */
    private static final int PLAN_TYPE_MANUAL = 1;  // 手动巡检
    private static final int PLAN_TYPE_AUTO = 2;    // 自动巡检

    /** 目标类型常量 */
    private static final int TARGET_TYPE_AREA = 0;
    private static final int TARGET_TYPE_FACS = 1;
    private static final int TARGET_TYPE_DEVICE = 2;

    /** 检查类型常量 */
    private static final int CHECK_TYPE_RANGE = 1;
    private static final int CHECK_TYPE_EQUAL = 2;
    private static final int CHECK_TYPE_NOT_NULL = 3;
    private static final int CHECK_TYPE_ONLINE = 4;

    /** 计划状态常量 */
    private static final int PLAN_STATUS_PENDING = 0;
    private static final int PLAN_STATUS_RUNNING = 1;
    private static final int PLAN_STATUS_COMPLETED = 2;

    /** 结果状态常量 */
    private static final int RESULT_NORMAL = 0;
    private static final int RESULT_ABNORMAL = 1;
    private static final int RESULT_PARTIAL = 2;

    @Autowired
    private InspectionPlanMapper planMapper;

    @Autowired
    private InspectionRuleMapper ruleMapper;

    @Autowired
    private InspectionReportMapper reportMapper;

    @Autowired
    private InspectionReportDetailMapper detailMapper;

    @Autowired
    private IEmsDeviceService deviceService;

    @Autowired
    private IEmsObjAttrValueService attrValueService;

    @Override
    public InspectionPlan selectById(Long id) {
        InspectionPlan plan = planMapper.selectById(id);
        if (plan != null) {
            plan.setRules(ruleMapper.selectByPlanCode(plan.getPlanCode()));
            parseTargetCodes(plan);
        }
        return plan;
    }

    @Override
    public InspectionPlan selectByPlanCode(String planCode) {
        InspectionPlan plan = planMapper.selectByPlanCode(planCode);
        if (plan != null) {
            plan.setRules(ruleMapper.selectByPlanCode(planCode));
            parseTargetCodes(plan);
        }
        return plan;
    }

    @Override
    public List<InspectionPlan> selectList(InspectionPlan plan) {
        return planMapper.selectList(plan);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(InspectionPlan plan) {
        // 生成计划代码
        plan.setPlanCode("IP" + DateUtils.dateTimeNow() + Seq.getId(Seq.uploadSeqType));
        plan.setPlanStatus(PLAN_STATUS_PENDING);

        int cnt = planMapper.insert(plan);

        // 保存规则（仅自动巡检需要）
        if (plan.getPlanType() == PLAN_TYPE_AUTO && CollectionUtils.isNotEmpty(plan.getRules())) {
            for (int i = 0; i < plan.getRules().size(); i++) {
                InspectionRule rule = plan.getRules().get(i);
                rule.setPlanCode(plan.getPlanCode());
                rule.setRuleCode("IR" + Seq.getId());
                rule.setRuleOrder(i + 1);
                if (rule.getEnabled() == null) {
                    rule.setEnabled(1);
                }
            }
            ruleMapper.insertBatch(plan.getRules());
        }

        return cnt;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(InspectionPlan plan) {
        int cnt = planMapper.update(plan);

        // 更新规则（仅自动巡检且传递了规则数据时才处理）
        if (plan.getPlanType() != null
            && plan.getPlanType() == PLAN_TYPE_AUTO
            && plan.getRules() != null) {

            ruleMapper.deleteByPlanCode(plan.getPlanCode());
            if (CollectionUtils.isNotEmpty(plan.getRules())) {
                for (int i = 0; i < plan.getRules().size(); i++) {
                    InspectionRule rule = plan.getRules().get(i);
                    rule.setPlanCode(plan.getPlanCode());
                    if (StringUtils.isBlank(rule.getRuleCode())) {
                        rule.setRuleCode("IR" + Seq.getId());
                    }
                    rule.setRuleOrder(i + 1);
                    if (rule.getEnabled() == null) {
                        rule.setEnabled(1);
                    }
                }
                ruleMapper.insertBatch(plan.getRules());
            }
        }

        return cnt;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(Long[] ids) {
        for (Long id : ids) {
            InspectionPlan plan = planMapper.selectById(id);
            if (plan != null) {
                ruleMapper.deleteByPlanCode(plan.getPlanCode());
            }
        }
        return planMapper.deleteByIds(ids);
    }

    /**
     * 执行自动巡检
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public InspectionReport executeAutoInspection(String planCode, String executor) {
        log.info("开始执行自动巡检任务: planCode={}, executor={}", planCode, executor);

        InspectionPlan plan = selectByPlanCode(planCode);
        if (plan == null) {
            log.error("巡检计划不存在: {}", planCode);
            throw new RuntimeException("巡检计划不存在");
        }

        // 校验计划类型
        if (plan.getPlanType() != PLAN_TYPE_AUTO) {
            throw new RuntimeException("该计划不是自动巡检类型，请使用提交报告功能");
        }

        // 更新计划状态为执行中
        planMapper.updateStatus(planCode, PLAN_STATUS_RUNNING);

        InspectionReport report = null;
        try {
            // 获取需要巡检的设备列表
            List<EmsDevice> devices = getInspectionDevices(plan);
            log.info("获取到巡检设备数量: {}", devices != null ? devices.size() : 0);

            if (CollectionUtils.isEmpty(devices)) {
                planMapper.updateStatus(planCode, PLAN_STATUS_COMPLETED);
                throw new RuntimeException("未找到需要巡检的设备");
            }

            // 获取启用的巡检规则
            List<InspectionRule> rules = ruleMapper.selectEnabledByPlanCode(planCode);
            log.info("获取到启用的巡检规则数量: {}", rules != null ? rules.size() : 0);

            // 如果没有规则，创建默认规则（检查设备在线状态）
            if (CollectionUtils.isEmpty(rules)) {
                log.warn("没有配置巡检规则，将使用默认规则（设备在线状态检查）");
                rules = createDefaultRules();
            }

            // 创建巡检报告
            report = createReport(plan, executor);
            log.info("创建巡检报告: {}", report.getReportCode());

            // 执行巡检
            List<InspectionReportDetail> details = new ArrayList<>();
            int normalCount = 0;
            int abnormalCount = 0;

            for (EmsDevice device : devices) {
                try {
                    InspectionReportDetail detail = checkDevice(device, rules, report.getReportCode());
                    details.add(detail);

                    if (detail.getResultStatus() == RESULT_NORMAL) {
                        normalCount++;
                    } else {
                        abnormalCount++;
                    }
                } catch (Exception e) {
                    log.error("检查设备异常: deviceCode={}, error={}", device.getDeviceCode(), e.getMessage(), e);
                    InspectionReportDetail errorDetail = createErrorDetail(device, report.getReportCode(), e.getMessage());
                    details.add(errorDetail);
                    abnormalCount++;
                }
            }

            // 保存报告明细
            if (CollectionUtils.isNotEmpty(details)) {
                log.info("保存报告明细数量: {}", details.size());
                detailMapper.insertBatch(details);
            }

            // 更新报告统计
            report.setTotalCount(devices.size());
            report.setNormalCount(normalCount);
            report.setAbnormalCount(abnormalCount);
            report.setFinishTime(new Date());

            if (abnormalCount == 0) {
                report.setResultStatus(RESULT_NORMAL);
            } else if (normalCount == 0) {
                report.setResultStatus(RESULT_ABNORMAL);
            } else {
                report.setResultStatus(RESULT_PARTIAL);
            }

            // 生成结果摘要
            Map<String, Object> summary = new HashMap<>();
            summary.put("totalDevices", devices.size());
            summary.put("normalDevices", normalCount);
            summary.put("abnormalDevices", abnormalCount);
            summary.put("checkRules", rules.size());
            report.setResultSummary(JSON.toJSONString(summary));

            reportMapper.update(report);
            log.info("自动巡检执行完成: reportCode={}, total={}, normal={}, abnormal={}",
                report.getReportCode(), devices.size(), normalCount, abnormalCount);

            // 更新计划状态
            planMapper.updateStatus(planCode, PLAN_STATUS_COMPLETED);

            // 返回完整报告
            report.setDetails(details);
            return report;

        } catch (Exception e) {
            log.error("自动巡检执行异常: planCode={}, error={}", planCode, e.getMessage(), e);
            planMapper.updateStatus(planCode, PLAN_STATUS_PENDING);
            throw new RuntimeException("巡检执行失败: " + e.getMessage(), e);
        }
    }

    /**
     * 提交手动巡检报告
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public InspectionReport submitManualReport(ManualReportSubmit submit) {
        log.info("提交手动巡检报告: planCode={}, submitter={}", submit.getPlanCode(), submit.getSubmitter());

        // 校验参数
        if (StringUtils.isBlank(submit.getPlanCode())) {
            throw new RuntimeException("计划代码不能为空");
        }
        if (StringUtils.isBlank(submit.getManualRemark())) {
            throw new RuntimeException("巡检报告内容不能为空");
        }

        InspectionPlan plan = selectByPlanCode(submit.getPlanCode());
        if (plan == null) {
            throw new RuntimeException("巡检计划不存在");
        }

        // 校验计划类型
        if (plan.getPlanType() != PLAN_TYPE_MANUAL) {
            throw new RuntimeException("该计划不是手动巡检类型");
        }

        // 校验计划状态（只有待执行状态可以提交）
        if (plan.getPlanStatus() != PLAN_STATUS_PENDING) {
            throw new RuntimeException("该计划已完成或已取消，无法提交报告");
        }

        // 创建巡检报告
        InspectionReport report = new InspectionReport();
        report.setReportCode("IR" + DateUtils.dateTimeNow() + Seq.getId(Seq.uploadSeqType));
        report.setPlanCode(plan.getPlanCode());
        report.setPlanName(plan.getPlanName());
        report.setPlanType(plan.getPlanType());
        report.setAreaCode(plan.getAreaCode());
        report.setAreaName(plan.getAreaName());
        report.setTargetType(plan.getTargetType());
        report.setExecuteTime(new Date());
        report.setFinishTime(new Date());
        report.setExecutor(StringUtils.isNotBlank(submit.getSubmitter()) ? submit.getSubmitter() : plan.getExecutor());
        report.setResultStatus(submit.getResultStatus() != null ? submit.getResultStatus() : RESULT_NORMAL);
        report.setManualRemark(submit.getManualRemark());

        // 手动巡检不统计设备数量（由人工填写报告）
        report.setTotalCount(0);
        report.setNormalCount(0);
        report.setAbnormalCount(0);

        // 生成结果摘要
        Map<String, Object> summary = new HashMap<>();
        summary.put("type", "manual");
        summary.put("targetNames", plan.getTargetNames());
        summary.put("submitter", submit.getSubmitter());
        summary.put("submitTime", DateUtils.dateTimeNow());

        if (StringUtils.isNotBlank(submit.getRemark())) {
            summary.put("remark", submit.getRemark());
        }
        report.setResultSummary(JSON.toJSONString(summary));

        // 保存报告
        reportMapper.insert(report);

        // 更新计划状态为已完成
        planMapper.updateStatus(submit.getPlanCode(), PLAN_STATUS_COMPLETED);

        log.info("手动巡检报告提交成功: reportCode={}, planCode={}", report.getReportCode(), submit.getPlanCode());

        return report;
    }

    // ===================== 以下为私有辅助方法 =====================

    /**
     * 创建默认巡检规则
     */
    private List<InspectionRule> createDefaultRules() {
        List<InspectionRule> rules = new ArrayList<>();
        InspectionRule rule = new InspectionRule();
        rule.setRuleCode("DEFAULT_ONLINE");
        rule.setRuleName("设备在线状态检查");
        rule.setDeviceModel(null);
        rule.setAttrKey("deviceStatus");
        rule.setAttrName("设备状态");
        rule.setCheckType(CHECK_TYPE_ONLINE);
        rule.setExpectValue("1");
        rule.setEnabled(1);
        rules.add(rule);
        return rules;
    }

    /**
     * 创建异常报告明细
     */
    private InspectionReportDetail createErrorDetail(EmsDevice device, String reportCode, String errorMsg) {
        InspectionReportDetail detail = new InspectionReportDetail();
        detail.setReportCode(reportCode);
        detail.setDeviceCode(device.getDeviceCode());
        detail.setDeviceName(device.getDeviceName() != null ? device.getDeviceName() : device.getDeviceCode());
        detail.setDeviceModel(device.getDeviceModel());
        detail.setDeviceModelName(device.getDeviceModelName());
        detail.setLocation(device.getLocation() != null ? device.getLocation() : "");
        detail.setAreaPath(device.getAreaPath() != null ? device.getAreaPath() : "");
        detail.setCheckTime(new Date());
        detail.setResultStatus(RESULT_ABNORMAL);

        CheckItemResult errorResult = new CheckItemResult();
        errorResult.setRuleCode("ERROR");
        errorResult.setRuleName("系统检查");
        errorResult.setStatus(RESULT_ABNORMAL);
        errorResult.setMessage("检查异常: " + errorMsg);

        List<CheckItemResult> checkResults = new ArrayList<>();
        checkResults.add(errorResult);
        detail.setCheckItems(JSON.toJSONString(checkResults));
        detail.setCheckItemList(checkResults);

        return detail;
    }

    /**
     * 根据计划获取需要巡检的设备列表
     */
    private List<EmsDevice> getInspectionDevices(InspectionPlan plan) {
        List<EmsDevice> devices = new ArrayList<>();
        List<String> targetCodes = plan.getTargetCodeList();

        log.info("获取巡检设备, targetType={}, targetCodes={}", plan.getTargetType(), targetCodes);

        if (CollectionUtils.isEmpty(targetCodes)) {
            log.warn("目标代码列表为空");
            return devices;
        }

        switch (plan.getTargetType()) {
            case TARGET_TYPE_AREA:
                for (String areaCode : targetCodes) {
                    try {
                        QueryDevice query = new QueryDevice();
                        query.setAreaCode(areaCode);
                        List<EmsDevice> areaDevices = deviceService.selectByAreaTree(query);
                        log.info("区域{}下设备数量: {}", areaCode, areaDevices != null ? areaDevices.size() : 0);
                        if (CollectionUtils.isNotEmpty(areaDevices)) {
                            devices.addAll(areaDevices);
                        }
                    } catch (Exception e) {
                        log.error("获取区域设备异常: areaCode={}, error={}", areaCode, e.getMessage());
                    }
                }
                break;

            case TARGET_TYPE_FACS:
                for (String facsCode : targetCodes) {
                    try {
                        QueryDevice query = new QueryDevice();
                        query.setRefFacs(facsCode);
                        List<EmsDevice> facsDevices = deviceService.selectDetailList(query);
                        log.info("设施{}下设备数量: {}", facsCode, facsDevices != null ? facsDevices.size() : 0);
                        if (CollectionUtils.isNotEmpty(facsDevices)) {
                            devices.addAll(facsDevices);
                        }
                    } catch (Exception e) {
                        log.error("获取设施设备异常: facsCode={}, error={}", facsCode, e.getMessage());
                    }
                }
                break;

            case TARGET_TYPE_DEVICE:
                for (String deviceCode : targetCodes) {
                    try {
                        EmsDevice device = deviceService.selectDetailByCode(deviceCode);
                        if (device != null) {
                            devices.add(device);
                        } else {
                            log.warn("设备不存在: {}", deviceCode);
                        }
                    } catch (Exception e) {
                        log.error("获取设备异常: deviceCode={}, error={}", deviceCode, e.getMessage());
                    }
                }
                break;

            default:
                log.warn("未知的目标类型: {}", plan.getTargetType());
        }

        // 去重
        if (CollectionUtils.isNotEmpty(devices)) {
            devices = devices.stream()
                .filter(d -> d != null && StringUtils.isNotBlank(d.getDeviceCode()))
                .collect(Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(EmsDevice::getDeviceCode))),
                    ArrayList::new
                ));
        }

        log.info("最终获取到设备数量: {}", devices.size());
        return devices;
    }

    /**
     * 检查单个设备
     */
    private InspectionReportDetail checkDevice(EmsDevice device, List<InspectionRule> rules, String reportCode) {
        InspectionReportDetail detail = new InspectionReportDetail();
        detail.setReportCode(reportCode);
        detail.setDeviceCode(device.getDeviceCode());
        detail.setDeviceName(device.getDeviceName() != null ? device.getDeviceName() : device.getDeviceCode());
        detail.setDeviceModel(device.getDeviceModel());
        detail.setDeviceModelName(device.getDeviceModelName());
        detail.setLocation(device.getLocation() != null ? device.getLocation() : "");
        detail.setAreaPath(device.getAreaPath() != null ? device.getAreaPath() : "");
        detail.setCheckTime(new Date());

        List<CheckItemResult> checkResults = new ArrayList<>();
        boolean hasAbnormal = false;

        // 获取设备属性值
        Map<String, String> attrValueMap = new HashMap<>();
        if (StringUtils.isNotBlank(device.getDeviceModel())) {
            try {
                List<EmsObjAttrValue> attrValues = attrValueService.selectByObjCode(device.getDeviceModel(), device.getDeviceCode());
                if (CollectionUtils.isNotEmpty(attrValues)) {
                    attrValueMap = attrValues.stream()
                        .filter(v -> v.getAttrKey() != null && v.getAttrValue() != null)
                        .collect(Collectors.toMap(EmsObjAttrValue::getAttrKey, EmsObjAttrValue::getAttrValue, (v1, v2) -> v2));
                }
            } catch (Exception e) {
                log.warn("获取设备属性值异常: deviceCode={}, error={}", device.getDeviceCode(), e.getMessage());
            }
        }

        // 应用每个规则
        for (InspectionRule rule : rules) {
            if (StringUtils.isNotBlank(rule.getDeviceModel()) &&
                !StringUtils.equals(rule.getDeviceModel(), device.getDeviceModel())) {
                continue;
            }

            try {
                CheckItemResult result = checkRule(rule, device, attrValueMap);
                checkResults.add(result);

                if (result.getStatus() == RESULT_ABNORMAL) {
                    hasAbnormal = true;
                }
            } catch (Exception e) {
                log.warn("检查规则异常: ruleCode={}, deviceCode={}, error={}",
                    rule.getRuleCode(), device.getDeviceCode(), e.getMessage());
                CheckItemResult errorResult = new CheckItemResult();
                errorResult.setRuleCode(rule.getRuleCode());
                errorResult.setRuleName(rule.getRuleName());
                errorResult.setStatus(RESULT_ABNORMAL);
                errorResult.setMessage("检查异常: " + e.getMessage());
                checkResults.add(errorResult);
                hasAbnormal = true;
            }
        }

        if (checkResults.isEmpty()) {
            CheckItemResult defaultResult = new CheckItemResult();
            defaultResult.setRuleCode("NO_RULE");
            defaultResult.setRuleName("无适用规则");
            defaultResult.setAttrKey("deviceStatus");
            defaultResult.setAttrName("设备状态");
            defaultResult.setActualValue(device.getDeviceStatus() != null ? device.getDeviceStatus().toString() : "未知");
            defaultResult.setStatus(RESULT_NORMAL);
            defaultResult.setMessage("无适用检查规则");
            checkResults.add(defaultResult);
        }

        detail.setResultStatus(hasAbnormal ? RESULT_ABNORMAL : RESULT_NORMAL);
        detail.setCheckItems(JSON.toJSONString(checkResults));
        detail.setCheckItemList(checkResults);

        return detail;
    }

    /**
     * 检查单个规则
     */
    private CheckItemResult checkRule(InspectionRule rule, EmsDevice device, Map<String, String> attrValueMap) {
        CheckItemResult result = new CheckItemResult();
        result.setRuleCode(rule.getRuleCode());
        result.setRuleName(rule.getRuleName() != null ? rule.getRuleName() : "未命名规则");
        result.setAttrKey(rule.getAttrKey());
        result.setAttrName(rule.getAttrName() != null ? rule.getAttrName() : rule.getAttrKey());
        result.setCheckType(rule.getCheckType());

        String actualValue = null;

        if ("deviceStatus".equals(rule.getAttrKey())) {
            actualValue = device.getDeviceStatus() != null ? device.getDeviceStatus().toString() : null;
        } else {
            actualValue = attrValueMap.get(rule.getAttrKey());
        }

        result.setActualValue(actualValue != null ? actualValue : "无数据");

        Integer checkType = rule.getCheckType();
        if (checkType == null) {
            checkType = CHECK_TYPE_NOT_NULL;
        }

        switch (checkType) {
            case CHECK_TYPE_RANGE:
                result.setExpectRange(formatRange(rule.getMinValue(), rule.getMaxValue()));
                checkRange(result, actualValue, rule.getMinValue(), rule.getMaxValue());
                break;
            case CHECK_TYPE_EQUAL:
                result.setExpectRange("= " + (rule.getExpectValue() != null ? rule.getExpectValue() : ""));
                checkEqual(result, actualValue, rule.getExpectValue());
                break;
            case CHECK_TYPE_NOT_NULL:
                result.setExpectRange("非空");
                checkNotNull(result, actualValue);
                break;
            case CHECK_TYPE_ONLINE:
                result.setExpectRange("在线(1)");
                checkOnline(result, actualValue, rule.getExpectValue());
                break;
            default:
                result.setStatus(RESULT_NORMAL);
                result.setMessage("未知检查类型: " + checkType);
        }

        return result;
    }

    private String formatRange(String minValue, String maxValue) {
        String min = StringUtils.isNotBlank(minValue) ? minValue : "-∞";
        String max = StringUtils.isNotBlank(maxValue) ? maxValue : "+∞";
        return min + " ~ " + max;
    }

    private void checkRange(CheckItemResult result, String actualValue, String minValue, String maxValue) {
        if (StringUtils.isBlank(actualValue)) {
            result.setStatus(RESULT_ABNORMAL);
            result.setMessage("属性值为空");
            return;
        }

        try {
            BigDecimal actual = new BigDecimal(actualValue);
            BigDecimal min = StringUtils.isNotBlank(minValue) ? new BigDecimal(minValue) : null;
            BigDecimal max = StringUtils.isNotBlank(maxValue) ? new BigDecimal(maxValue) : null;

            boolean inRange = true;
            if (min != null && actual.compareTo(min) < 0) {
                inRange = false;
            }
            if (max != null && actual.compareTo(max) > 0) {
                inRange = false;
            }

            result.setStatus(inRange ? RESULT_NORMAL : RESULT_ABNORMAL);
            result.setMessage(inRange ? "正常" : "超出范围");
        } catch (NumberFormatException e) {
            result.setStatus(RESULT_ABNORMAL);
            result.setMessage("数值格式错误: " + actualValue);
        }
    }

    private void checkEqual(CheckItemResult result, String actualValue, String expectValue) {
        if (StringUtils.equals(actualValue, expectValue)) {
            result.setStatus(RESULT_NORMAL);
            result.setMessage("正常");
        } else {
            result.setStatus(RESULT_ABNORMAL);
            result.setMessage("值不匹配，期望: " + expectValue);
        }
    }

    private void checkNotNull(CheckItemResult result, String actualValue) {
        if (StringUtils.isNotBlank(actualValue)) {
            result.setStatus(RESULT_NORMAL);
            result.setMessage("正常");
        } else {
            result.setStatus(RESULT_ABNORMAL);
            result.setMessage("属性值为空");
        }
    }

    private void checkOnline(CheckItemResult result, String actualValue, String expectValue) {
        String expect = StringUtils.isNotBlank(expectValue) ? expectValue : "1";
        if (StringUtils.equals(actualValue, expect)) {
            result.setStatus(RESULT_NORMAL);
            result.setMessage("在线");
        } else {
            result.setStatus(RESULT_ABNORMAL);
            result.setMessage("离线或异常");
        }
    }

    private InspectionReport createReport(InspectionPlan plan, String executor) {
        InspectionReport report = new InspectionReport();
        report.setReportCode("IR" + DateUtils.dateTimeNow() + Seq.getId(Seq.uploadSeqType));
        report.setPlanCode(plan.getPlanCode());
        report.setPlanName(plan.getPlanName() != null ? plan.getPlanName() : "");
        report.setPlanType(plan.getPlanType());
        report.setAreaCode(plan.getAreaCode());
        report.setAreaName(plan.getAreaName() != null ? plan.getAreaName() : "");
        report.setTargetType(plan.getTargetType());
        report.setExecuteTime(new Date());
        report.setExecutor(StringUtils.isNotBlank(executor) ? executor :
            (StringUtils.isNotBlank(plan.getExecutor()) ? plan.getExecutor() : "system"));
        report.setResultStatus(RESULT_NORMAL);
        report.setTotalCount(0);
        report.setNormalCount(0);
        report.setAbnormalCount(0);

        reportMapper.insert(report);
        return report;
    }

    private void parseTargetCodes(InspectionPlan plan) {
        if (StringUtils.isNotBlank(plan.getTargetCodes())) {
            try {
                plan.setTargetCodeList(JSONArray.parseArray(plan.getTargetCodes(), String.class));
            } catch (Exception e) {
                log.warn("解析目标代码失败: {}", plan.getTargetCodes());
                plan.setTargetCodeList(new ArrayList<>());
            }
        } else {
            plan.setTargetCodeList(new ArrayList<>());
        }
    }
}