package com.ygtx.gxt.task;

import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.framework.web.service.SysPermissionService;
import com.ygtx.gxt.domain.*;
import com.ygtx.gxt.service.*;
import com.ygtx.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 设备连续安全运行奖励任务
 * 每天0点执行一次，对符合安全运行天数的设备进行奖励分值发放
 *
 * @author ouyj
 * @date 2026-01-08
 */
@EnableScheduling
@Component("equipmentSafeOperationRewardTask")
public class EquipmentSafeOperationRewardTask {

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

    @Autowired
    private IGxtEquipmentService equipmentService;

    @Autowired
    private IGxtRepairOrderService repairOrderService;

    @Autowired
    private IGxtWorkOrderService workOrderService;

    @Autowired
    private IGxtSafeOperationRewardService safeOperationRewardService;

    @Autowired
    private IGxtMonthScoreService monthScoreService;

    @Autowired
    private IGxtUserScoreService userScoreService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private IGxtOrderScoreDetailService orderScoreDetailService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IGxtRepairOrderFlowService repairOrderFlowService;

    @Autowired
    private IGxtWorkOrderFlowService workOrderFlowService;

    // 限制每次查询的最大工单数量，防止数据量过大导致性能问题
    private static final int MAX_ORDERS_PER_QUERY = 1;

    /**
     * 每天凌晨0点执行定时任务
     * 循环设备表GxtEquipment，计算连续安全运行奖励
     */
    //@Scheduled(cron = "0 0 0 * * ?") // 每天凌晨0点执行一次
    public void processSafeOperationRewards() {
        log.info("开始执行设备连续安全运行奖励任务");

        // 设置系统用户上下文
        setSystemUserContext();

        try {
            // 查询所有设备
            GxtEquipment equipmentQuery = new GxtEquipment();
            List<GxtEquipment> equipments = equipmentService.selectGxtEquipmentList(equipmentQuery);

            int processedCount = 0;
            for (GxtEquipment equipment : equipments) {
                //if(equipment.getEquipmentId() == 59L){
                    try {
                        processEquipmentSafeOperationReward(equipment);
                        processedCount++;
                    } catch (Exception e) {
                        log.error("处理设备 {} 连续安全运行奖励时发生异常", equipment.getEquipmentCode(), e);
                    }
                //}
            }

            log.info("设备连续安全运行奖励任务执行完成，共处理 {} 个设备", processedCount);
        } catch (Exception e) {
            log.error("执行设备连续安全运行奖励任务时发生异常", e);
        }
    }

    public void processDeductionForStoppedOrders() {
        log.info("开始执行工单扣分任务");

        // 设置系统用户上下文
        setSystemUserContext();

        try {
            // 查询满足条件的维修工单（状态为待结单的滞留维修工单）
            List<GxtRepairOrder> repairOrdersToDeduct = repairOrderService.selectPendingRepairOrdersForDeduction();
            log.info("找到 {} 个需要扣分的待结单维修工单", repairOrdersToDeduct.size());

            // 对维修工单进行扣分处理
            for (GxtRepairOrder repairOrder : repairOrdersToDeduct) {
                try {
                    processPendingRepairOrderDeduction(repairOrder);
                } catch (Exception e) {
                    log.error("处理待结单维修工单 {} 扣分时发生异常", repairOrder.getWorkOrderProjectNo(), e);
                }
            }

            log.info("工单扣分任务执行完成");
        } catch (Exception e) {
            log.error("执行工单扣分任务时发生异常", e);
        }
    }

    /**
     * 处理单个设备的连续安全运行奖励
     * 
     * @param equipment 设备信息
     */
    private void processEquipmentSafeOperationReward(GxtEquipment equipment) {
        log.debug("开始处理设备 {} 的连续安全运行奖励", equipment.getEquipmentCode());
        
        // 获取最近一次中断事件的工单
        GxtRepairOrder lastBreakOrder = getLastBreakOrder(equipment.getEquipmentId());
        Date lastBreakTime = lastBreakOrder != null ? lastBreakOrder.getOccurTime() : null;
        
        // 判断是否可以处理维修工单奖励
        boolean canProcessRepairOrders = canProcessOrders(lastBreakOrder, 1);
        
        // 判断是否可以处理维保工单奖励
        boolean canProcessWorkOrders = canProcessOrders(lastBreakOrder, 2);
        
        List<GxtRepairOrder> validRepairOrders = new ArrayList<>();
        List<GxtWorkOrder> validWorkOrders = new ArrayList<>();
        
        // 只有在允许的情况下才查询相应类型的工单
        if (canProcessRepairOrders) {
            // 查询该设备所有完成时间 > 最近中断时间的有效维修工单
            validRepairOrders = repairOrderService.selectValidRepairOrdersAfterBreak(
                equipment.getEquipmentId(), lastBreakTime);
        }
        
        if (canProcessWorkOrders) {
            // 查询该设备所有完成时间 > 最近中断时间的有效维保工单
            validWorkOrders = workOrderService.selectValidWorkOrdersAfterBreak(
                equipment.getEquipmentId(), lastBreakTime);
        }
        
        log.debug("设备 {} 找到 {} 个有效维修工单和 {} 个有效维保工单", 
            equipment.getEquipmentCode(), validRepairOrders.size(), validWorkOrders.size());
        
        // 获取奖励配置
        GxtSafeOperationReward rewardQuery = new GxtSafeOperationReward();
        rewardQuery.setStatus(0);
        List<GxtSafeOperationReward> rewardConfigs = safeOperationRewardService.selectGxtSafeOperationRewardList(rewardQuery);
        if (rewardConfigs.isEmpty()) {
            log.warn("未找到任何启用的安全运行奖励配置");
            return;
        }
        
        // 按照safeDuration升序排序
        rewardConfigs.sort(Comparator.comparingInt(GxtSafeOperationReward::getSafeDuration));
        
        // 处理维修工单奖励
        if (canProcessRepairOrders) {
            for (GxtRepairOrder repairOrder : validRepairOrders) {
                processOrderReward(repairOrder, rewardConfigs, 1, lastBreakOrder); // 1表示维修工单
            }
        }
        
        // 处理维保工单奖励
        if (canProcessWorkOrders) {
            for (GxtWorkOrder workOrder : validWorkOrders) {
                processOrderReward(workOrder, rewardConfigs, 2, lastBreakOrder); // 2表示维保工单
            }
        }
    }

    /**
     * 更新月度统计数据以反映运行得分奖励
     * 
     * @param repairOrder 维修工单
     * @param rewardScore 奖励分数
     */
    private void updateMonthlyScoreDataForRunScore(GxtRepairOrder repairOrder, BigDecimal rewardScore) {
        try {
            // 使用当前日期所在的月份（因为奖励是在当前时间发放的）
            SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM");
            String monthPeriod = sdf.format(new Date());

            // 获取场站ID
            Long deptId = repairOrder.getPcsStationPid();

            // 获取月度统计信息
            GxtMonthScore queryScore = new GxtMonthScore();
            queryScore.setDeptId(deptId);
            queryScore.setMonthPeriod(monthPeriod);
            List<GxtMonthScore> scoreList = monthScoreService.selectGxtMonthScoreList(queryScore);
            GxtMonthScore monthScore = null;
            if (!scoreList.isEmpty()) {
                monthScore = scoreList.get(0);
            }

            if (monthScore == null) {
                // 如果没有月度统计记录，创建新的记录
                monthScore = new GxtMonthScore();
                monthScore.setDeptId(deptId);
                monthScore.setMonthPeriod(monthPeriod);
                monthScore.setStatus(0); // 初始状态
                monthScore.setPersionId(SecurityUtils.getUserId());
                monthScore.setCreateBy(SecurityUtils.getUsername());
                monthScore.setCreateTime(new Date());
                monthScoreService.insertGxtMonthScore(monthScore);
                
                // 重新查询刚插入的记录
                scoreList = monthScoreService.selectGxtMonthScoreList(queryScore);
                if (!scoreList.isEmpty()) {
                    monthScore = scoreList.get(0);
                }
            }

            if (monthScore != null) {
                // 更新用户评分统计
                updateUserScoresForRunScore(monthScore, repairOrder, rewardScore);
            }
        } catch (Exception e) {
            log.error("更新维修工单 {} 的月度统计数据时发生异常", repairOrder.getWorkOrderProjectNo(), e);
        }
    }

    /**
     * 更新月度统计数据以反映运行得分奖励
     * 
     * @param workOrder 维保工单
     * @param rewardScore 奖励分数
     */
    private void updateMonthlyScoreDataForRunScore(GxtWorkOrder workOrder, BigDecimal rewardScore) {
        try {
            // 使用当前日期所在的月份（因为奖励是在当前时间发放的）
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM");
            String monthPeriod = sdf.format(new Date());

            // 获取场站ID
            Long deptId = workOrder.getPcsStationPid();

            // 获取月度统计信息
            GxtMonthScore queryScore = new GxtMonthScore();
            queryScore.setDeptId(deptId);
            queryScore.setMonthPeriod(monthPeriod);
            List<GxtMonthScore> scoreList = monthScoreService.selectGxtMonthScoreList(queryScore);
            GxtMonthScore monthScore = null;
            if (!scoreList.isEmpty()) {
                monthScore = scoreList.get(0);
            }

            if (monthScore == null) {
                // 如果没有月度统计记录，创建新的记录
                monthScore = new GxtMonthScore();
                monthScore.setDeptId(deptId);
                monthScore.setMonthPeriod(monthPeriod);
                monthScore.setStatus(0); // 初始状态
                monthScore.setPersionId(SecurityUtils.getUserId());
                monthScore.setCreateBy(SecurityUtils.getUsername());
                monthScore.setCreateTime(new Date());
                monthScoreService.insertGxtMonthScore(monthScore);
                
                // 重新查询刚插入的记录
                scoreList = monthScoreService.selectGxtMonthScoreList(queryScore);
                if (!scoreList.isEmpty()) {
                    monthScore = scoreList.get(0);
                }
            }

            if (monthScore != null) {
                // 更新用户评分统计
                updateUserScoresForRunScore(monthScore, workOrder, rewardScore);
            }
        } catch (Exception e) {
            log.error("更新维保工单 {} 的月度统计数据时发生异常", workOrder.getWorkOrderProjectNo(), e);
        }
    }

    /**
     * 更新用户评分统计以反映运行得分奖励
     * 
     * @param monthScore 月度统计信息
     * @param order 维修工单
     * @param rewardScore 奖励分数
     */
    private void updateUserScoresForRunScore(GxtMonthScore monthScore, GxtRepairOrder order, BigDecimal rewardScore) {
        try {
            List<GxtRepairOrderPerson> persons = order.getRepairOrderPersonList();
            if (persons == null || persons.isEmpty()) {
                // 如果工单中的人员列表为空，尝试从数据库查询
                persons = repairOrderService.selectRepairOrderPersonListByOrderId(order.getId());
            }

            if (persons != null) {
                for (GxtRepairOrderPerson person : persons) {
                    Long userId = person.getUserId();
                    SysUser sysUser = userMapper.selectUserById(userId);
                    
                    // 使用userName、monthPeriod、monthScoreId精确查询用户评分记录
                    GxtUserScore userScoreQuery = new GxtUserScore();
                    userScoreQuery.setUserName(sysUser.getUserName());
                    userScoreQuery.setMonthPeriod(monthScore.getMonthPeriod());
                    userScoreQuery.setMonthScoreId(monthScore.getId());
                    List<GxtUserScore> userScores = userScoreService.selectGxtUserScoreList(userScoreQuery);
                    
                    if (!userScores.isEmpty()) {
                        // 找到现有记录，直接更新
                        GxtUserScore userScore = userScores.get(0);
                        BigDecimal currentRepairTotal = (userScore.getRepairTotalScore() != null) ?
                                userScore.getRepairTotalScore() : BigDecimal.ZERO;

                        BigDecimal newRepairScore = currentRepairTotal.add(rewardScore);
                        userScore.setRepairTotalScore(newRepairScore);

                        // 更新最终评分
                        BigDecimal maintenanceScore = (userScore.getMaintenanceTotalScore() != null) ?
                                userScore.getMaintenanceTotalScore() : BigDecimal.ZERO;

                        BigDecimal finalScore = maintenanceScore.add(newRepairScore);
                        userScore.setFinalScore(finalScore);
                        userScore.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                        userScore.setUpdateTime(new Date());

                        userScoreService.updateGxtUserScore(userScore);

                        log.debug("更新用户 {} 月度统计得分: {} -> {}", person.getNickName(), currentRepairTotal, newRepairScore);
                    } else {
                        // 没有找到记录，创建新记录
                        GxtUserScore newUserScore = new GxtUserScore();
                        newUserScore.setMonthScoreId(monthScore.getId());
                        newUserScore.setUserName(sysUser.getUserName());
                        newUserScore.setNickName(person.getNickName());
                        newUserScore.setMonthPeriod(monthScore.getMonthPeriod());
                        
                        // 设置维修工单得分
                        BigDecimal repairScore = rewardScore;
                        newUserScore.setRepairTotalScore(rewardScore);
                        
                        // 维保得分默认为0
                        newUserScore.setMaintenanceTotalScore(BigDecimal.ZERO);
                        newUserScore.setFinalScore(rewardScore);
                        newUserScore.setStatus(0);
                        newUserScore.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                        newUserScore.setCreateTime(new Date());
                        // 插入新记录
                        userScoreService.insertGxtUserScore(newUserScore);
                        
                        log.debug("创建用户 {} 月度统计得分: {}", person.getNickName(), repairScore);
                    }
                }
            }
        } catch (Exception e) {
            log.error("更新维修工单人员月度统计数据时发生异常", e);
        }
    }

    /**
     * 更新用户评分统计以反映运行得分奖励
     * 
     * @param monthScore 月度统计信息
     * @param order 维保工单
     * @param rewardScore 奖励分数
     */
    private void updateUserScoresForRunScore(GxtMonthScore monthScore, GxtWorkOrder order, BigDecimal rewardScore) {
        try {
            List<GxtWorkOrderPerson> persons = order.getWorkOrderPersonList();
            if (persons == null || persons.isEmpty()) {
                // 如果工单中的人员列表为空，尝试从数据库查询
                persons = workOrderService.selectWorkOrderPersonListByOrderId(order.getId());
            }

            if (persons != null) {
                for (GxtWorkOrderPerson person : persons) {
                    Long userId = person.getUserId();
                    SysUser sysUser = userMapper.selectUserById(userId);
                    
                    // 使用userName、monthPeriod、monthScoreId精确查询用户评分记录
                    GxtUserScore userScoreQuery = new GxtUserScore();
                    userScoreQuery.setUserName(sysUser.getUserName());
                    userScoreQuery.setMonthPeriod(monthScore.getMonthPeriod());
                    userScoreQuery.setMonthScoreId(monthScore.getId());
                    List<GxtUserScore> userScores = userScoreService.selectGxtUserScoreList(userScoreQuery);
                    
                    if (!userScores.isEmpty()) {
                        // 找到现有记录，直接更新
                        GxtUserScore userScore = userScores.get(0);
                        BigDecimal currentMaintenanceTotal = (userScore.getMaintenanceTotalScore() != null) ?
                                userScore.getMaintenanceTotalScore() : BigDecimal.ZERO;

                        BigDecimal newMaintenanceScore = currentMaintenanceTotal.add(rewardScore);
                        userScore.setMaintenanceTotalScore(newMaintenanceScore);

                        // 更新最终评分
                        BigDecimal repairScore = (userScore.getRepairTotalScore() != null) ?
                                userScore.getRepairTotalScore() : BigDecimal.ZERO;

                        BigDecimal finalScore = repairScore.add(newMaintenanceScore);
                        userScore.setFinalScore(finalScore);
                        userScore.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                        userScore.setUpdateTime(new Date());
                        
                        userScoreService.updateGxtUserScore(userScore);
                        
                        log.debug("更新用户 {} 月度统计得分: {} -> {}", person.getNickName(), currentMaintenanceTotal, newMaintenanceScore);
                    } else {
                        // 没有找到记录，创建新记录
                        GxtUserScore newUserScore = new GxtUserScore();
                        newUserScore.setMonthScoreId(monthScore.getId());
                        newUserScore.setUserName(sysUser.getUserName());
                        newUserScore.setNickName(person.getNickName());
                        newUserScore.setMonthPeriod(monthScore.getMonthPeriod());
                        
                        // 设置维保工单得分
                        BigDecimal maintenanceScore = rewardScore;
                        newUserScore.setMaintenanceTotalScore(maintenanceScore);
                        
                        // 维修得分默认为0
                        newUserScore.setRepairTotalScore(BigDecimal.ZERO);
                        newUserScore.setFinalScore(maintenanceScore);
                        newUserScore.setStatus(0);
                        newUserScore.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                        newUserScore.setCreateTime(new Date());
                        // 插入新记录
                        userScoreService.insertGxtUserScore(newUserScore);
                        
                        log.debug("创建用户 {} 月度统计得分: {}", person.getNickName(), maintenanceScore);
                    }
                }
            }
        } catch (Exception e) {
            log.error("更新维保工单人员月度统计数据时发生异常", e);
        }
    }

    /**
     * 根据安全运行天数获取适用的奖励配置
     * 
     * @param rewardConfigs 奖励配置列表
     * @param daysBetween 安全运行天数
     * @return 适用的奖励配置
     */
    private GxtSafeOperationReward getApplicableRewardConfig(List<GxtSafeOperationReward> rewardConfigs, int daysBetween) {
        GxtSafeOperationReward applicableReward = null;

        for (GxtSafeOperationReward config : rewardConfigs) {
            if (config.getSafeDuration() <= daysBetween) {
                applicableReward = config;
            } else {
                // 因为已经按safeDuration升序排序，所以第一个大于daysBetween的配置就是边界
                break;
            }
        }

        return applicableReward;
    }

    /**
     * 处理维保工单扣分
     *
     * @param workOrder 维保工单
     */
    /*private void processWorkOrderDeduction(GxtWorkOrder workOrder) {
        try {
            List<GxtWorkOrderPerson> persons = workOrder.getWorkOrderPersonList();
            if (persons == null || persons.isEmpty()) {
                // 如果工单中的人员列表为空，尝试从数据库查询
                persons = workOrderService.selectWorkOrderPersonListByOrderId(workOrder.getId());
            }

            if (persons == null || persons.isEmpty()) {
                log.warn("维保工单 {} 人员列表为空，无法进行扣分", workOrder.getId());
                return;
            }

            for (GxtWorkOrderPerson person : persons) {
                GxtUserScore userScore = userScoreService.selectGxtUserScoreByUserIdAndYearMonth(person.getUserId(), workOrder.getWorkOrderDate());
                if (userScore == null) {
                    userScore = new GxtUserScore();
                    userScore.setUserId(person.getUserId());
                    userScore.setYearMonth(DateUtils.formatDate(workOrder.getWorkOrderDate(), "yyyyMM"));
                    userScore.setMaintenanceTotalScore(BigDecimal.ZERO);
                    userScore.setRepairTotalScore(BigDecimal.ZERO);
                    userScore.setFinalScore(BigDecimal.ZERO);
                    userScore.setStatus(0);
                    userScore.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                    userScore.setCreateTime(new Date());
                    userScoreService.insertGxtUserScore(userScore);
                }

                BigDecimal deductionScore = BigDecimal.valueOf(workOrder.getDeductionScore());
                userScore.setMaintenanceTotalScore(userScore.getMaintenanceTotalScore().subtract(deductionScore));
                userScore.setFinalScore(userScore.getFinalScore().subtract(deductionScore));
                userScore.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                userScore.setUpdateTime(new Date());
                userScoreService.updateGxtUserScore(userScore);

                log.debug("扣分用户 {} 月度统计得分: {}", person.getNickName(), userScore.getFinalScore());
            }
        } catch (Exception e) {
            log.error("处理维保工单扣分时发生异常", e);
        }
    }*/

    /**
     * 为维修工单人员更新运行得分
     * 
     * @param repairOrder 维修工单
     * @param rewardScore 奖励分数
     */
    private void updatePersonRunScoreForRepairOrder(GxtRepairOrder repairOrder, BigDecimal rewardScore) {
        try {
            List<GxtRepairOrderPerson> persons = repairOrder.getRepairOrderPersonList();
            if (persons == null || persons.isEmpty()) {
                // 如果工单中的人员列表为空，尝试从数据库查询
                persons = repairOrderService.selectRepairOrderPersonListByOrderId(repairOrder.getId());
            }

            if (persons == null || persons.isEmpty()) {
                log.warn("维修工单 {} 没有找到相关人员", repairOrder.getWorkOrderProjectNo());
                return;
            }

            List<GxtRepairOrderPerson> updatedPersons = new ArrayList<>();
            for (GxtRepairOrderPerson person : persons) {
                Double currentRunScore = person.getRunScore();
                Double newRunScore = (currentRunScore != null ? currentRunScore : 0.0) + rewardScore.doubleValue();
                
                GxtRepairOrderPerson updatedPerson = new GxtRepairOrderPerson();
                updatedPerson.setId(person.getId());
                updatedPerson.setRunScore(newRunScore);
                updatedPerson.setScore(person.getScore() != null ? person.getScore().add(rewardScore) : rewardScore);
                updatedPerson.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                updatedPerson.setUpdateTime(new Date());
                
                updatedPersons.add(updatedPerson);
                
                log.debug("维修工单 {} 人员 {} 运行得分更新: {} -> {}",
                    repairOrder.getWorkOrderProjectNo(), person.getNickName(), currentRunScore, newRunScore );
            }

            // 批量更新人员得分
            int result = repairOrderService.updateRepairOrderPersonList(updatedPersons);
            log.info("维修工单 {} 共更新 {} 名人员的运行得分和总得分", repairOrder.getWorkOrderProjectNo(), updatedPersons.size());
            
            // 添加工单个人分数明细数据
            addOrderScoreDetailsForRunScoreRepair(repairOrder, persons, rewardScore, 2); // 2代表运行得分

            /*double totalScore = persons.stream()
                    .mapToDouble(person -> person.getTotalScore() != null ? person.getTotalScore() : 0.0)
                    .sum();
            repairOrder.setScore(new BigDecimal(String.valueOf(totalScore)));

            repairOrderService.updateGxtRepairOrderForScore(repairOrder);*/
        } catch (Exception e) {
            log.error("更新维修工单 {} 人员运行得分时发生异常", repairOrder.getWorkOrderProjectNo(), e);
        }
    }

    /**
     * 为维保工单人员更新运行得分
     * 
     * @param workOrder 维保工单
     * @param rewardScore 奖励分数
     */
    private void updatePersonRunScoreForWorkOrder(GxtWorkOrder workOrder, BigDecimal rewardScore) {
        try {
            List<GxtWorkOrderPerson> persons = workOrder.getWorkOrderPersonList();
            if (persons == null || persons.isEmpty()) {
                // 如果工单中的人员列表为空，尝试从数据库查询
                persons = workOrderService.selectWorkOrderPersonListByOrderId(workOrder.getId());
            }

            if (persons == null || persons.isEmpty()) {
                log.warn("维保工单 {} 没有找到相关人员", workOrder.getWorkOrderProjectNo());
                return;
            }

            List<GxtWorkOrderPerson> updatedPersons = new ArrayList<>();
            for (GxtWorkOrderPerson person : persons) {
                Double currentRunScore = person.getRunScore();
                Double newRunScore = (currentRunScore != null ? currentRunScore : 0.0) + rewardScore.doubleValue();
                
                GxtWorkOrderPerson updatedPerson = new GxtWorkOrderPerson();
                updatedPerson.setId(person.getId());
                updatedPerson.setRunScore(newRunScore);
                updatedPerson.setScore(person.getScore() != null ? person.getScore().add(rewardScore) : rewardScore);
                updatedPerson.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                updatedPerson.setUpdateTime(new Date());
                
                updatedPersons.add(updatedPerson);
                
                log.debug("维保工单 {} 人员 {} 运行得分更新: {} -> {}",
                    workOrder.getWorkOrderProjectNo(), person.getNickName(), currentRunScore, newRunScore);
            }

            // 批量更新人员得分
            int result = workOrderService.updateWorkOrderPersonList(updatedPersons);
            log.info("维保工单 {} 共更新 {} 名人员的运行得分和总得分", workOrder.getWorkOrderProjectNo(), updatedPersons.size());
            
            // 添加工单个人分数明细数据
            addOrderScoreDetailsForRunScoreWork(workOrder, persons, rewardScore, 2); // 2代表运行得分

            /*double totalScore = persons.stream()
                    .mapToDouble(person -> person.getTotalScore() != null ? person.getTotalScore() : 0.0)
                    .sum();
            workOrder.setScore(new BigDecimal(String.valueOf(totalScore)));

            workOrderService.updateGxtWorkOrderForScore(workOrder);*/
        } catch (Exception e) {
            log.error("更新维保工单 {} 人员运行得分时发生异常", workOrder.getWorkOrderProjectNo(), e);
        }
    }

    /**
     * 为维修工单人员更新停机扣分
     *
     * @param repairOrder    维修工单
     * @param deductionScore 扣分分数
     * @param archiveTime
     */
    private void updatePersonStopScoreForRepairOrder(GxtRepairOrder repairOrder, BigDecimal deductionScore, Date archiveTime) {
        try {
            List<GxtRepairOrderPerson> persons = repairOrder.getRepairOrderPersonList();
            if (persons == null || persons.isEmpty()) {
                // 如果工单中的人员列表为空，尝试从数据库查询
                persons = repairOrderService.selectRepairOrderPersonListByOrderId(repairOrder.getId());
            }

            if (persons == null || persons.isEmpty()) {
                log.warn("维修工单 {} 没有找到相关人员", repairOrder.getWorkOrderProjectNo());
                return;
            }

            List<GxtRepairOrderPerson> updatedPersons = new ArrayList<>();
            for (GxtRepairOrderPerson person : persons) {
                Double currentStopScore = person.getStopScore();
                Double newStopScore = (currentStopScore != null ? currentStopScore : 0.0) + deductionScore.doubleValue();
                
                GxtRepairOrderPerson updatedPerson = new GxtRepairOrderPerson();
                updatedPerson.setId(person.getId());
                updatedPerson.setStopScore(newStopScore);
                updatedPerson.setScore(person.getScore() != null ? person.getScore().add(deductionScore) : deductionScore);
                updatedPerson.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                updatedPerson.setUpdateTime(new Date());
                
                updatedPersons.add(updatedPerson);
                
                log.debug("维修工单 {} 人员 {} 停机扣分更新: {} -> {}",
                    repairOrder.getWorkOrderProjectNo(), person.getNickName(), currentStopScore, newStopScore );
            }

            // 批量更新人员得分
            int result = repairOrderService.updateRepairOrderPersonList(updatedPersons);
            log.info("维修工单 {} 共更新 {} 名人员的停机扣分和总得分", repairOrder.getWorkOrderProjectNo(), updatedPersons.size());
            
            // 添加工单个人分数明细数据
            addOrderScoreDetailsForStopScoreRepair(repairOrder, persons, deductionScore, 3, archiveTime); // 3代表停机扣分
        } catch (Exception e) {
            log.error("更新维修工单 {} 人员停机扣分时发生异常", repairOrder.getWorkOrderProjectNo(), e);
        }
    }

    /**
     * 为维保工单人员更新停机扣分
     * 
     * @param workOrder 维保工单
     * @param deductionScore 扣分分数
     */
    private void updatePersonStopScoreForWorkOrder(GxtWorkOrder workOrder, BigDecimal deductionScore, Date archiveTime) {
        try {
            List<GxtWorkOrderPerson> persons = workOrder.getWorkOrderPersonList();
            if (persons == null || persons.isEmpty()) {
                // 如果工单中的人员列表为空，尝试从数据库查询
                persons = workOrderService.selectWorkOrderPersonListByOrderId(workOrder.getId());
            }

            if (persons == null || persons.isEmpty()) {
                log.warn("维保工单 {} 没有找到相关人员", workOrder.getWorkOrderProjectNo());
                return;
            }

            List<GxtWorkOrderPerson> updatedPersons = new ArrayList<>();
            for (GxtWorkOrderPerson person : persons) {
                Double currentStopScore = person.getStopScore();
                Double newStopScore = (currentStopScore != null ? currentStopScore : 0.0) + deductionScore.doubleValue();
                
                GxtWorkOrderPerson updatedPerson = new GxtWorkOrderPerson();
                updatedPerson.setId(person.getId());
                updatedPerson.setStopScore(newStopScore);
                updatedPerson.setScore(person.getScore() != null ? person.getScore().add(deductionScore) : deductionScore);
                updatedPerson.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                updatedPerson.setUpdateTime(new Date());
                
                updatedPersons.add(updatedPerson);
                
                log.debug("维保工单 {} 人员 {} 停机扣分更新: {} -> {}",
                    workOrder.getWorkOrderProjectNo(), person.getNickName(), currentStopScore, newStopScore);
            }

            // 批量更新人员得分
            int result = workOrderService.updateWorkOrderPersonList(updatedPersons);
            log.info("维保工单 {} 共更新 {} 名人员的停机扣分和总得分", workOrder.getWorkOrderProjectNo(), updatedPersons.size());
            
            // 添加工单个人分数明细数据
            addOrderScoreDetailsForStopScoreWork(workOrder, persons, deductionScore, 3, archiveTime); // 3代表停机扣分
        } catch (Exception e) {
            log.error("更新维保工单 {} 人员停机扣分时发生异常", workOrder.getWorkOrderProjectNo(), e);
        }
    }

    /**
     * 更新月度统计数据以反映停机扣分，使用工单归档时间确定月份
     *
     * @param repairOrder 维修工单
     * @param deductionScore 扣分分数
     */
    private void updateMonthlyScoreDataForStopScore(GxtRepairOrder repairOrder, BigDecimal deductionScore, Date archiveTime) {
        try {
            // 使用归档时间所在的月份
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM");
            String monthPeriod = sdf.format(archiveTime);

            // 获取场站ID
            Long deptId = repairOrder.getPcsStationPid();

            // 获取月度统计信息
            GxtMonthScore queryScore = new GxtMonthScore();
            queryScore.setDeptId(deptId);
            queryScore.setMonthPeriod(monthPeriod);
            List<GxtMonthScore> scoreList = monthScoreService.selectGxtMonthScoreList(queryScore);
            GxtMonthScore monthScore = null;
            if (!scoreList.isEmpty()) {
                monthScore = scoreList.get(0);
            }

            if (monthScore == null) {
                // 如果没有月度统计记录，创建新的记录
                monthScore = new GxtMonthScore();
                monthScore.setDeptId(deptId);
                monthScore.setMonthPeriod(monthPeriod);
                monthScore.setStatus(0); // 初始状态
                monthScore.setPersionId(SecurityUtils.getUserId());
                monthScore.setCreateBy(SecurityUtils.getUsername());
                monthScore.setCreateTime(new Date());
                monthScoreService.insertGxtMonthScore(monthScore);

                // 重新查询刚插入的记录
                scoreList = monthScoreService.selectGxtMonthScoreList(queryScore);
                if (!scoreList.isEmpty()) {
                    monthScore = scoreList.get(0);
                }
            }

            if (monthScore != null) {
                // 更新用户评分统计
                updateUserScoresForStopScore(monthScore, repairOrder, deductionScore);
            }
        } catch (Exception e) {
            log.error("更新维修工单 {} 的月度扣分统计数据时发生异常", repairOrder.getWorkOrderProjectNo(), e);
        }
    }

    /**
     * 更新月度统计数据以反映停机扣分，使用工单归档时间确定月份
     *
     * @param workOrder 维保工单
     * @param deductionScore 扣分分数
     */
    private void updateMonthlyScoreDataForStopScore(GxtWorkOrder workOrder, BigDecimal deductionScore, Date archiveTime) {
        try {
            // 获取工单归档时间来确定月份
            //Date archiveTime = getArchiveTimeForWorkOrder(workOrder.getId());

            // 使用归档时间所在的月份
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM");
            String monthPeriod = sdf.format(archiveTime);

            // 获取场站ID
            Long deptId = workOrder.getPcsStationPid();

            // 获取月度统计信息
            GxtMonthScore queryScore = new GxtMonthScore();
            queryScore.setDeptId(deptId);
            queryScore.setMonthPeriod(monthPeriod);
            List<GxtMonthScore> scoreList = monthScoreService.selectGxtMonthScoreList(queryScore);
            GxtMonthScore monthScore = null;
            if (!scoreList.isEmpty()) {
                monthScore = scoreList.get(0);
            }

            if (monthScore == null) {
                // 如果没有月度统计记录，创建新的记录
                monthScore = new GxtMonthScore();
                monthScore.setDeptId(deptId);
                monthScore.setMonthPeriod(monthPeriod);
                monthScore.setStatus(0); // 初始状态
                monthScore.setPersionId(SecurityUtils.getUserId());
                monthScore.setCreateBy(SecurityUtils.getUsername());
                monthScore.setCreateTime(new Date());
                monthScoreService.insertGxtMonthScore(monthScore);

                // 重新查询刚插入的记录
                scoreList = monthScoreService.selectGxtMonthScoreList(queryScore);
                if (!scoreList.isEmpty()) {
                    monthScore = scoreList.get(0);
                }
            }

            if (monthScore != null) {
                // 更新用户评分统计
                updateUserScoresForStopScore(monthScore, workOrder, deductionScore);
            }
        } catch (Exception e) {
            log.error("更新维保工单 {} 的月度扣分统计数据时发生异常", workOrder.getWorkOrderProjectNo(), e);
        }
    }

    /**
     * 更新用户评分统计以反映停机扣分
     * 
     * @param monthScore 月度统计信息
     * @param order 维修工单
     * @param deductionScore 扣分分数
     */
    private void updateUserScoresForStopScore(GxtMonthScore monthScore, GxtRepairOrder order, BigDecimal deductionScore) {
        try {
            List<GxtRepairOrderPerson> persons = order.getRepairOrderPersonList();
            if (persons == null || persons.isEmpty()) {
                // 如果工单中的人员列表为空，尝试从数据库查询
                persons = repairOrderService.selectRepairOrderPersonListByOrderId(order.getId());
            }

            if (persons != null) {
                for (GxtRepairOrderPerson person : persons) {
                    Long userId = person.getUserId();
                    SysUser sysUser = userMapper.selectUserById(userId);
                    
                    // 使用userName、monthPeriod、monthScoreId精确查询用户评分记录
                    GxtUserScore userScoreQuery = new GxtUserScore();
                    userScoreQuery.setUserName(sysUser.getUserName());
                    userScoreQuery.setMonthPeriod(monthScore.getMonthPeriod());
                    userScoreQuery.setMonthScoreId(monthScore.getId());
                    List<GxtUserScore> userScores = userScoreService.selectGxtUserScoreList(userScoreQuery);
                    
                    if (!userScores.isEmpty()) {
                        // 找到现有记录，直接更新
                        GxtUserScore userScore = userScores.get(0);
                        BigDecimal currentRepairTotal = (userScore.getRepairTotalScore() != null) ?
                                userScore.getRepairTotalScore() : BigDecimal.ZERO;

                        BigDecimal newRepairScore = currentRepairTotal.add(deductionScore);
                        userScore.setRepairTotalScore(newRepairScore);

                        // 更新最终评分
                        BigDecimal maintenanceScore = (userScore.getMaintenanceTotalScore() != null) ?
                                userScore.getMaintenanceTotalScore() : BigDecimal.ZERO;

                        BigDecimal finalScore = maintenanceScore.add(newRepairScore);
                        userScore.setFinalScore(finalScore);
                        userScore.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                        userScore.setUpdateTime(new Date());

                        userScoreService.updateGxtUserScore(userScore);

                        log.debug("更新用户 {} 月度统计得分: {} -> {}", person.getNickName(), currentRepairTotal, newRepairScore);
                    } else {
                        // 没有找到记录，创建新记录
                        GxtUserScore newUserScore = new GxtUserScore();
                        newUserScore.setMonthScoreId(monthScore.getId());
                        newUserScore.setUserName(sysUser.getUserName());
                        newUserScore.setNickName(person.getNickName());
                        newUserScore.setMonthPeriod(monthScore.getMonthPeriod());
                        
                        // 设置维修工单得分
                        BigDecimal repairScore = deductionScore;
                        newUserScore.setRepairTotalScore(repairScore);
                        
                        // 维保得分默认为0
                        newUserScore.setMaintenanceTotalScore(BigDecimal.ZERO);
                        newUserScore.setFinalScore(deductionScore);
                        newUserScore.setStatus(0);
                        newUserScore.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                        newUserScore.setCreateTime(new Date());
                        // 插入新记录
                        userScoreService.insertGxtUserScore(newUserScore);
                        
                        log.debug("创建用户 {} 月度统计得分: {}", person.getNickName(), repairScore);
                    }
                }
            }
        } catch (Exception e) {
            log.error("更新维修工单人员月度扣分统计数据时发生异常", e);
        }
    }

    /**
     * 更新用户评分统计以反映停机扣分
     * 
     * @param monthScore 月度统计信息
     * @param order 维保工单
     * @param deductionScore 扣分分数
     */
    private void updateUserScoresForStopScore(GxtMonthScore monthScore, GxtWorkOrder order, BigDecimal deductionScore) {
        try {
            List<GxtWorkOrderPerson> persons = order.getWorkOrderPersonList();
            if (persons == null || persons.isEmpty()) {
                // 如果工单中的人员列表为空，尝试从数据库查询
                persons = workOrderService.selectWorkOrderPersonListByOrderId(order.getId());
            }

            if (persons != null) {
                for (GxtWorkOrderPerson person : persons) {
                    Long userId = person.getUserId();
                    SysUser sysUser = userMapper.selectUserById(userId);
                    
                    // 使用userName、monthPeriod、monthScoreId精确查询用户评分记录
                    GxtUserScore userScoreQuery = new GxtUserScore();
                    userScoreQuery.setUserName(sysUser.getUserName());
                    userScoreQuery.setMonthPeriod(monthScore.getMonthPeriod());
                    userScoreQuery.setMonthScoreId(monthScore.getId());
                    List<GxtUserScore> userScores = userScoreService.selectGxtUserScoreList(userScoreQuery);
                    
                    if (!userScores.isEmpty()) {
                        // 找到现有记录，直接更新
                        GxtUserScore userScore = userScores.get(0);
                        BigDecimal currentMaintenanceTotal = (userScore.getMaintenanceTotalScore() != null) ?
                                userScore.getMaintenanceTotalScore() : BigDecimal.ZERO;

                        BigDecimal newMaintenanceScore = currentMaintenanceTotal.add(deductionScore);
                        userScore.setMaintenanceTotalScore(newMaintenanceScore);

                        // 更新最终评分
                        BigDecimal repairScore = (userScore.getRepairTotalScore() != null) ?
                                userScore.getRepairTotalScore() : BigDecimal.ZERO;

                        BigDecimal finalScore = repairScore.add(newMaintenanceScore);
                        userScore.setFinalScore(finalScore);
                        userScore.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                        userScore.setUpdateTime(new Date());
                        
                        userScoreService.updateGxtUserScore(userScore);
                        
                        log.debug("更新用户 {} 月度统计得分: {} -> {}", person.getNickName(), currentMaintenanceTotal, newMaintenanceScore);
                    } else {
                        // 没有找到记录，创建新记录
                        GxtUserScore newUserScore = new GxtUserScore();
                        newUserScore.setMonthScoreId(monthScore.getId());
                        newUserScore.setUserName(sysUser.getUserName());
                        newUserScore.setNickName(person.getNickName());
                        newUserScore.setMonthPeriod(monthScore.getMonthPeriod());
                        
                        // 设置维保工单得分
                        BigDecimal maintenanceScore = deductionScore;
                        newUserScore.setMaintenanceTotalScore(maintenanceScore);
                        
                        // 维修得分默认为0
                        newUserScore.setRepairTotalScore(BigDecimal.ZERO);
                        newUserScore.setFinalScore(deductionScore);
                        newUserScore.setStatus(0);
                        newUserScore.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                        newUserScore.setCreateTime(new Date());
                        // 插入新记录
                        userScoreService.insertGxtUserScore(newUserScore);
                        
                        log.debug("创建用户 {} 月度统计得分: {}", person.getNickName(), maintenanceScore);
                    }
                }
            }
        } catch (Exception e) {
            log.error("更新维保工单人员月度扣分统计数据时发生异常", e);
        }
    }

    /**
     * 设置系统用户上下文，用于自动操作
     */
    private void setSystemUserContext() {
        try {
            // 获取admin用户信息
            SysUser userAdmin = userMapper.selectUserByUserName("admin");
            if (userAdmin != null) {
                Set<String> permissions = permissionService.getMenuPermission(userAdmin);
                LoginUser loginUser = new LoginUser(userAdmin, permissions);

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        loginUser,
                        null,
                        loginUser.getAuthorities()
                );

                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            log.error("设置系统用户上下文失败", e);
        }
    }


    

    /**
     * 添加运行得分的工单个人分数明细数据
     * 
     * @param repairOrder 维修工单
     * @param persons 更新的人员列表
     * @param rewardScore 奖励分数
     * @param scoreType 分数类型
     */
    private void addOrderScoreDetailsForRunScoreRepair(GxtRepairOrder repairOrder, List<GxtRepairOrderPerson> persons, BigDecimal rewardScore, int scoreType) {
        try {
            for (GxtRepairOrderPerson person : persons) {
                GxtOrderScoreDetail detail = new GxtOrderScoreDetail();
                
                // 设置基础信息
                detail.setUserId(person.getUserId());
                detail.setNickName(person.getNickName());
                detail.setOrderType(1); // 维修工单
                
                // 设置工单相关信息
                detail.setOrderId(repairOrder.getId());
                detail.setOrderCode(repairOrder.getWorkOrderProjectNo());
                
                // 设置分数类型和分数
                detail.setScoreType(scoreType); // 运行得分
                detail.setScore(rewardScore);
                detail.setRunScore(rewardScore);

                detail.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                detail.setCreateTime(new Date());
                // 保存到数据库
                orderScoreDetailService.insertGxtOrderScoreDetail(detail);
            }
        } catch (Exception e) {
            log.error("添加维修工单运行得分明细时发生异常", e);
        }
    }
    
    /**
     * 添加运行得分的工单个人分数明细数据
     * 
     * @param workOrder 维保工单
     * @param persons 更新的人员列表
     * @param rewardScore 奖励分数
     * @param scoreType 分数类型
     */
    private void addOrderScoreDetailsForRunScoreWork(GxtWorkOrder workOrder, List<GxtWorkOrderPerson> persons, BigDecimal rewardScore, int scoreType) {
        try {
            for (GxtWorkOrderPerson person : persons) {
                GxtOrderScoreDetail detail = new GxtOrderScoreDetail();
                
                // 设置基础信息
                detail.setUserId(person.getUserId());
                detail.setNickName(person.getNickName());
                detail.setOrderType(2); // 维保工单
                
                // 设置工单相关信息
                detail.setOrderId(workOrder.getId());
                detail.setOrderCode(workOrder.getWorkOrderProjectNo());
                
                // 设置分数类型和分数
                detail.setScoreType(scoreType); // 运行得分
                detail.setScore(rewardScore);
                detail.setRunScore(rewardScore);

                detail.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                detail.setCreateTime(new Date());
                
                // 保存到数据库
                orderScoreDetailService.insertGxtOrderScoreDetail(detail);
            }
        } catch (Exception e) {
            log.error("添加维保工单运行得分明细时发生异常", e);
        }
    }

    /**
     * 添加停机扣分的工单个人分数明细数据
     *
     * @param repairOrder    维修工单
     * @param persons        更新的人员列表
     * @param deductionScore 扣分分数
     * @param scoreType      分数类型
     * @param archiveTime
     */
    private void addOrderScoreDetailsForStopScoreRepair(GxtRepairOrder repairOrder, List<GxtRepairOrderPerson> persons, BigDecimal deductionScore, int scoreType, Date archiveTime) {
        try {

            for (GxtRepairOrderPerson person : persons) {
                GxtOrderScoreDetail detail = new GxtOrderScoreDetail();

                // 设置基础信息
                detail.setUserId(person.getUserId());
                detail.setNickName(person.getNickName());
                detail.setOrderType(1); // 维修工单

                // 设置工单相关信息
                detail.setOrderId(repairOrder.getId());
                detail.setOrderCode(repairOrder.getWorkOrderProjectNo());

                // 设置分数类型和分数
                detail.setScoreType(scoreType); // 停机扣分
                detail.setScore(deductionScore);
                detail.setStopScore(deductionScore);

                detail.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                detail.setCreateTime(archiveTime);

                // 保存到数据库
                orderScoreDetailService.insertGxtOrderScoreDetail(detail);
            }
        } catch (Exception e) {
            log.error("添加维修工单停机扣分明细时发生异常", e);
        }
    }

    /**
     * 添加停机扣分的工单个人分数明细数据
     * 
     * @param workOrder 维保工单
     * @param persons 更新的人员列表
     * @param deductionScore 扣分分数
     * @param scoreType 分数类型
     */
    private void addOrderScoreDetailsForStopScoreWork(GxtWorkOrder workOrder, List<GxtWorkOrderPerson> persons, BigDecimal deductionScore, int scoreType, Date archiveTime) {
        try {
            // 获取工单归档时间
            //Date archiveTime = getArchiveTimeForWorkOrder(workOrder.getId());
            
            for (GxtWorkOrderPerson person : persons) {
                GxtOrderScoreDetail detail = new GxtOrderScoreDetail();
                
                // 设置基础信息
                detail.setUserId(person.getUserId());
                detail.setNickName(person.getNickName());
                detail.setOrderType(2); // 维保工单
                
                // 设置工单相关信息
                detail.setOrderId(workOrder.getId());
                detail.setOrderCode(workOrder.getWorkOrderProjectNo());
                
                // 设置分数类型和分数
                detail.setScoreType(scoreType); // 停机扣分
                detail.setScore(deductionScore);
                detail.setStopScore(deductionScore);

                detail.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                detail.setCreateTime(archiveTime);
                
                // 保存到数据库
                orderScoreDetailService.insertGxtOrderScoreDetail(detail);
            }
        } catch (Exception e) {
            log.error("添加维保工单停机扣分明细时发生异常", e);
        }
    }

    /**
     * 处理待结单维修工单扣分
     * 判定条件：当前存在状态为"待结单"的维修工单
     * 执行逻辑：扫描符合条件的滞留维修工单
     * 若停机时长达到某扣罚档位（当前时间 - 故障发生时间 ≥ 配置表中的停运天数阈值）
     * 分值分配：每人扣分 = (配置扣分值 ÷ 该工单作业人数)
     *
     * @param repairOrder 维修工单
     */
    private void processPendingRepairOrderDeduction(GxtRepairOrder repairOrder) {
        log.debug("开始处理待结单维修工单 {} 的扣分", repairOrder.getWorkOrderProjectNo());

        // 计算停机时长：当前时间 - 故障发生时间
        Date occurTime = repairOrder.getOccurTime();
        if (occurTime == null) {
            log.warn("待结单维修工单 {} 的故障发生时间为空，跳过扣分", repairOrder.getWorkOrderProjectNo());
            return;
        }

        Date currentTime = new Date();
        int stopDays = DateUtils.calculateDateDifference(currentTime, occurTime);
        
        if (stopDays < 0) {
            log.debug("待结单维修工单 {} 的停机时长为 {} 天，无需扣分", repairOrder.getWorkOrderProjectNo(), stopDays);
            return;
        }

        // 获取奖励配置（包含扣分阈值和扣分值）
        GxtSafeOperationReward rewardQuery = new GxtSafeOperationReward();
        rewardQuery.setStatus(0);
        List<GxtSafeOperationReward> rewardConfigs = safeOperationRewardService.selectGxtSafeOperationRewardList(rewardQuery);
        if (rewardConfigs.isEmpty()) {
            log.warn("未找到任何启用的安全运行奖励配置，无法进行扣分");
            return;
        }

        // 按照safeDuration升序排序
        rewardConfigs.sort(Comparator.comparingInt(GxtSafeOperationReward::getSafeDuration));

        // 获取对应的扣分配置
        GxtSafeOperationReward applicableDeduction = getApplicableRewardConfig(rewardConfigs, stopDays);
        if (applicableDeduction == null) {
            log.debug("待结单维修工单 {} 停机 {} 天，未找到对应的扣分配置", repairOrder.getWorkOrderProjectNo(), stopDays);
            return;
        }

        // 获取停机扣分
        BigDecimal deductionScore = applicableDeduction.getDowntimeScore();
        if (deductionScore != null && deductionScore.compareTo(BigDecimal.ZERO) < 0) { // 确保是负数
            log.info("待结单维修工单 {} 停机 {} 天，达到扣罚档位 {} 天，共扣分 {}",
                repairOrder.getWorkOrderProjectNo(), stopDays, applicableDeduction.getSafeDuration(), deductionScore);

            // 获取工单作业人数
            List<GxtRepairOrderPerson> persons = repairOrder.getRepairOrderPersonList();
            if (persons == null || persons.isEmpty()) {
                // 如果工单中的人员列表为空，尝试从数据库查询
                persons = repairOrderService.selectRepairOrderPersonListByOrderId(repairOrder.getId());
            }

            // 过滤出isLeader等于1的人员
            if (persons != null && !persons.isEmpty()) {
                List<GxtRepairOrderPerson> leaderPersons = new ArrayList<>();
                for (GxtRepairOrderPerson person : persons) {
                    if (person.getIsLeader() != null && person.getIsLeader() == 1) {
                        leaderPersons.add(person);
                        break;
                    }
                }
                persons = leaderPersons;
            }

            // 如果没有找到工作负责人，创建虚拟负责人继续处理
            if (persons == null || persons.isEmpty()) {
                log.warn("待结单维修工单 {} 没有找到工作负责人，创建虚拟负责人继续处理", repairOrder.getWorkOrderProjectNo());
                persons = createVirtualLeaderPerson(repairOrder);
            }

            // 计算每人扣分 = (配置扣分值 ÷ 该工单作业人数)
            int personCount = persons.size();
            //BigDecimal perPersonDeduction = deductionScore.divide(new BigDecimal(personCount), 2, BigDecimal.ROUND_HALF_UP);

            BigDecimal divisionResult = deductionScore.divide(new BigDecimal(personCount), 10, BigDecimal.ROUND_HALF_UP);

            // 根据小数位数决定最终结果
            BigDecimal perPersonDeduction;
            if (divisionResult.scale() <= 6) {
                // 小数位数不超过6位，保持原值
                perPersonDeduction = divisionResult;
            } else {
                // 小数位数超过6位，截取到6位小数
                perPersonDeduction = divisionResult.setScale(6, BigDecimal.ROUND_HALF_UP);
            }

            log.info("待结单维修工单 {} 共 {} 人参与，每人扣分 {}", 
                repairOrder.getWorkOrderProjectNo(), personCount, perPersonDeduction);

            // 对相关工单人员进行扣分操作
            //updatePersonStopScoreForRepairOrder(repairOrder, perPersonDeduction, currentTime);
            // 更新月度统计数据
            //updateMonthlyScoreDataForStopScore(repairOrder, perPersonDeduction, currentTime);
            addOrderScoreDetailsForStopScoreRepairNotCompllete(repairOrder, persons, deductionScore, 3); // 3代表停机扣分
        } else {
            log.debug("待结单维修工单 {} 找到扣分配置但分数无效: {}", repairOrder.getWorkOrderProjectNo(), deductionScore);
        }
    }

    /**
     * 处理维保工单扣分
     *
     * @param workOrder 维保工单
     */
    private void processWorkOrderDeduction(GxtWorkOrder workOrder) {
        log.debug("开始处理维保工单 {} 的扣分", workOrder.getWorkOrderProjectNo());

        // 计算停运天数：复运时间 - 停机时间（pauseTime）
        Date restartTime = workOrder.getRestartTime();
        Date pauseTime = workOrder.getPauseTime(); // 维保工单使用pauseTime作为停机时间
        if (pauseTime == null) {
            pauseTime = workOrder.getCreateTime();
        }
        if (restartTime == null || pauseTime == null) {
            log.warn("维保工单 {} 的复运时间或停机时间为空，跳过扣分", workOrder.getWorkOrderProjectNo());
            return;
        }

        int daysBetween = DateUtils.calculateDateDifference(restartTime, pauseTime);
        if (daysBetween <= 0) {
            log.debug("维保工单 {} 的停运天数为 {} 天，无需扣分", workOrder.getWorkOrderProjectNo(), daysBetween);
            return;
        }

        /*Date archiveTime = getArchiveTimeForWorkOrder(workOrder.getId());
        if (archiveTime == null) {
            log.warn("维保工单 {} 未找到归档时间", workOrder.getWorkOrderProjectNo());
            return;
        }*/
        Date realEndTime = workOrder.getRealEndTime();
        if (realEndTime == null) {
            log.warn("维保工单 {} 未找到结束时间", workOrder.getWorkOrderProjectNo());
            return;
        }
        // 获取扣分配置
        GxtSafeOperationReward rewardQuery = new GxtSafeOperationReward();
        rewardQuery.setStatus(0);
        List<GxtSafeOperationReward> rewardConfigs = safeOperationRewardService.selectGxtSafeOperationRewardList(rewardQuery);
        if (rewardConfigs.isEmpty()) {
            log.warn("未找到任何启用的安全运行奖励配置，无法进行扣分");
            return;
        }

        // 按照safeDuration升序排序
        rewardConfigs.sort(Comparator.comparingInt(GxtSafeOperationReward::getSafeDuration));

        // 获取对应的扣分配置
        GxtSafeOperationReward applicableDeduction = getApplicableRewardConfig(rewardConfigs, daysBetween);
        if (applicableDeduction == null) {
            log.debug("维保工单 {} 停运天数 {} 未找到对应的扣分配置", workOrder.getWorkOrderProjectNo(), daysBetween);
            return;
        }

        // 获取停机扣分
        BigDecimal deductionScore = applicableDeduction.getDowntimeScore();
        if (deductionScore != null && deductionScore.compareTo(BigDecimal.ZERO) < 0) { // 确保是负数
            log.info("维保工单 {} 停运 {} 天，扣分 {}", workOrder.getWorkOrderProjectNo(), daysBetween, deductionScore);

            // 对相关工单人员进行扣分操作
            updatePersonStopScoreForWorkOrder(workOrder, deductionScore, realEndTime);
            // 更新月度统计数据
            updateMonthlyScoreDataForStopScore(workOrder, deductionScore, realEndTime);
        } else {
            log.debug("维保工单 {} 找到扣分配置但分数无效: {}", workOrder.getWorkOrderProjectNo(), deductionScore);
        }
    }

    /**
     * 获取设备最近一次中断事件的工单
     * 中断判定：查询满足完整中断条件的最新维修工单
     * 
     * @param equipmentId 设备ID
     * @return 最近中断工单，如果没有中断记录则返回null
     */
    private GxtRepairOrder getLastBreakOrder(Long equipmentId) {
        try {
            // 查询满足完整中断条件的维修工单（已包含处理方式和停机时长过滤）
            List<GxtRepairOrder> interruptOrders = repairOrderService.selectRepairOrdersByOccurTime(equipmentId);
            
            if (interruptOrders.isEmpty()) {
                log.debug("设备 {} 未找到满足中断条件的维修工单记录", equipmentId);
                return null;
            }
            
            // 获取满足中断条件的最新工单
            GxtRepairOrder interruptOrder = interruptOrders.get(0);
            
            log.debug("设备 {} 发生中断，工单: {}，故障时间: {}，恢复时间: {}", 
                equipmentId, interruptOrder.getWorkOrderProjectNo(), 
                interruptOrder.getOccurTime(), interruptOrder.getRestartTime());
            
            // SQL已过滤满足所有中断条件的工单，直接返回中断工单对象
            return interruptOrder;
            
        } catch (Exception e) {
            log.error("获取设备 {} 最近中断时间时发生异常", equipmentId, e);
            return null;
        }
    }


    /**
     * 处理工单奖励（通用方法）
     *
     * @param order          工单对象
     * @param rewardConfigs  奖励配置列表
     * @param orderType      工单类型：1-维修工单，2-维保工单
     * @param lastBreakOrder
     */
    private void processOrderReward(Object order, List<GxtSafeOperationReward> rewardConfigs, int orderType, GxtRepairOrder lastBreakOrder) {
        try {
            Date restartTime = null;
            String workOrderProjectNo = null;
            Long orderId = null;
            List<?> personList = null;
            Long pcsStationPid = null;
            
            // 根据工单类型提取公共属性
            if (orderType == 1) { // 维修工单
                GxtRepairOrder repairOrder = (GxtRepairOrder) order;
                restartTime = repairOrder.getRestartTime();
                workOrderProjectNo = repairOrder.getWorkOrderProjectNo();
                orderId = repairOrder.getId();
                personList = repairOrder.getRepairOrderPersonList();
                pcsStationPid = repairOrder.getPcsStationPid();
                
                // 如果人员列表为空，从数据库查询
                if (personList == null || personList.isEmpty()) {
                    personList = repairOrderService.selectRepairOrderPersonListByOrderId(orderId);
                }
            } else if (orderType == 2) { // 维保工单
                GxtWorkOrder workOrder = (GxtWorkOrder) order;
                restartTime = workOrder.getRestartTime();
                workOrderProjectNo = workOrder.getWorkOrderProjectNo();
                orderId = workOrder.getId();
                personList = workOrder.getWorkOrderPersonList();
                pcsStationPid = workOrder.getPcsStationPid();
                
                // 如果人员列表为空，从数据库查询
                if (personList == null || personList.isEmpty()) {
                    personList = workOrderService.selectWorkOrderPersonListByOrderId(orderId);
                }
            }
            
            if (restartTime == null) {
                log.warn("工单 {} 的恢复运行时间为空，跳过奖励处理", workOrderProjectNo);
                return;
            }
            
            if (personList == null || personList.isEmpty()) {
                log.warn("工单 {} 没有找到相关人员，跳过奖励处理", workOrderProjectNo);
                return;
            }
            
            // 计算该工单的安全运行天数（当前日期 - 恢复运行日期 - 1）
            int safeDays = DateUtils.calculateDateDifference(DateUtils.getNowDate(), restartTime) - 1;
            
            if (safeDays <= 0) {
                log.debug("工单 {} 安全运行天数为 {} 天，无需奖励", workOrderProjectNo, safeDays);
                return;
            }
            
            // 获取适用的奖励配置
            GxtSafeOperationReward applicableReward = getApplicableRewardConfig(rewardConfigs, safeDays);
            if (applicableReward == null) {
                log.debug("工单 {} 运行天数 {} 未找到对应的奖励配置", workOrderProjectNo, safeDays);
                return;
            }
            
            // 根据工单类型获取相应的奖励分数
            BigDecimal rewardScore = null;
            if (orderType == 1) {
                // 维修工单使用非计划检修奖励分值
                rewardScore = applicableReward.getUnplannedMaintenanceScore();
            } else if (orderType == 2) {
                // 维保工单使用计划检修奖励分值
                rewardScore = applicableReward.getPlannedMaintenanceScore();
            }
            
            if (rewardScore == null || rewardScore.compareTo(BigDecimal.ZERO) <= 0) {
                log.debug("工单 {} 找到奖励配置但分数无效: {}", workOrderProjectNo, rewardScore);
                return;
            }
            
            // 计算人均奖励分数
            // 不满6位小数保持原值，超过6位小数则截取到6位小数
            int personCount = personList.size();
            BigDecimal divisionResult = rewardScore.divide(new BigDecimal(personCount), 10, BigDecimal.ROUND_HALF_UP);
            
            // 根据小数位数决定最终结果
            BigDecimal perPersonReward;
            if (divisionResult.scale() <= 6) {
                // 小数位数不超过6位，保持原值
                perPersonReward = divisionResult;
            } else {
                // 小数位数超过6位，截取到6位小数
                perPersonReward = divisionResult.setScale(6, BigDecimal.ROUND_HALF_UP);
            }
            
            log.info("工单 {} 安全运行 {} 天，总奖励 {} 分，{} 人参与，人均奖励 {} 分",
                workOrderProjectNo, safeDays, rewardScore, personCount, perPersonReward);
            String repairMethod = lastBreakOrder != null ? lastBreakOrder.getRepairMethod() : null;
            boolean handelPre = false;
            long timeDiffMinutes = 0;
            if (lastBreakOrder != null) {
                if(lastBreakOrder.getRestartTime() == null){
                    handelPre = true;
                }else{
                    Date restartTimeBreak = lastBreakOrder.getRestartTime();
                    Date occurTimeBreak = lastBreakOrder.getOccurTime();
                    timeDiffMinutes = (restartTimeBreak.getTime() - occurTimeBreak.getTime()) / (1000 * 60);
                }
            }

            // 更新人员得分
            if (orderType == 1) {
                // 如果repairMethod为空
                if (repairMethod == null || repairMethod.trim().isEmpty()) {
                    handleOrderWithoutRepairMethod(order, perPersonReward, lastBreakOrder);
                }else{
                    if(handelPre){
                        handleOrderWithoutRepairMethod(order, perPersonReward, lastBreakOrder);
                    }else if(timeDiffMinutes <= 30){
                        updatePersonRunScoreForRepairOrder((GxtRepairOrder) order, perPersonReward);
                        updateMonthlyScoreDataForRunScore((GxtRepairOrder) order, perPersonReward);
                    }
                }
            } else if (orderType == 2) {
                // 如果repairMethod为空
                if (lastBreakOrder != null && (repairMethod == null || repairMethod.trim().isEmpty())) {
                    handleOrderWithoutRepairMethod(order, perPersonReward, lastBreakOrder);
                }else{
                    if(handelPre){
                        handleOrderWithoutRepairMethod(order, perPersonReward, lastBreakOrder);
                    }else if(timeDiffMinutes <= 30){
                        updatePersonRunScoreForWorkOrder((GxtWorkOrder) order, perPersonReward);
                        updateMonthlyScoreDataForRunScore((GxtWorkOrder) order, perPersonReward);
                    }
                }
            }
        } catch (Exception e) {
            String orderNo = (orderType == 1) ? 
                ((GxtRepairOrder) order).getWorkOrderProjectNo() : 
                ((GxtWorkOrder) order).getWorkOrderProjectNo();
            log.error("处理工单 {} 奖励时发生异常", orderNo, e);
        }
    }

    /**
     * 获取维修工单的归档时间
     *
     * @param orderId 工单ID
     * @return 归档时间，如果未找到则返回null
     */
    private Date getArchiveTimeForRepairOrder(Long orderId) {
        try {
            // 查询工单流转记录，找到actionType为archive的记录
            GxtRepairOrderFlow queryFlow = new GxtRepairOrderFlow();
            queryFlow.setOrderId(orderId);
            queryFlow.setActionType("archive");

            List<GxtRepairOrderFlow> flows = repairOrderFlowService.selectGxtRepairOrderFlowList(queryFlow);
            if (flows != null && !flows.isEmpty()) {
                // 返回归档时间
                return flows.get(0).getActionTime();
            }
            return null;
        } catch (Exception e) {
            log.error("获取维修工单 {} 归档时间时发生异常", orderId, e);
            return null;
        }
    }

    /**
     * 获取维保工单的归档时间
     *
     * @param orderId 工单ID
     * @return 归档时间，如果未找到则返回null
     */
    private Date getArchiveTimeForWorkOrder(Long orderId) {
        try {
            // 查询工单流转记录，找到actionType为archive的记录
            GxtWorkOrderFlow queryFlow = new GxtWorkOrderFlow();
            queryFlow.setOrderId(orderId);
            queryFlow.setActionType("archive");

            List<GxtWorkOrderFlow> flows = workOrderFlowService.selectGxtWorkOrderFlowList(queryFlow);
            if (flows != null && !flows.isEmpty()) {
                // 返回归档时间
                return flows.get(0).getActionTime();
            }
            return null;
        } catch (Exception e) {
            log.error("获取维保工单 {} 归档时间时发生异常", orderId, e);
            return null;
        }
    }

    /**
     * 判断是否可以处理指定类型的工单
     * 
     * @param lastBreakOrder 最近一次中断工单
     * @param orderType 工单类型：1-维修工单，2-维保工单
     * @return true-可以处理，false-不可以处理
     */
    private boolean canProcessOrders(GxtRepairOrder lastBreakOrder, int orderType) {
        // 如果lastBreakOrder为空
        if (lastBreakOrder == null) {
            // 维修工单：不能处理
            if (orderType == 1) {
                return false;
            }
            // 维保工单：可以处理
            else if (orderType == 2) {
                return true;
            }
        }
        /*
        // 如果lastBreakOrder不为空，检查repairMethod字段
        String repairMethod = lastBreakOrder.getRepairMethod();
        
        // 如果repairMethod为空
        if (repairMethod == null || repairMethod.trim().isEmpty()) {
            // 无论是维修工单还是维保工单，都不能处理
            return false;
        }
        
        // 如果repairMethod不为空，则可以处理*/
        return true;
    }

    /**
     * 处理repairMethod为空的工单情况
     * 添加工单工分明细表数据
     *
     * @param order 工单对象
     * @param rewardScore 奖励分数
     * @param lastBreakOrder 最近中断工单
     */
    private void handleOrderWithoutRepairMethod(Object order, BigDecimal rewardScore, GxtRepairOrder lastBreakOrder) {
        try {
            if (order instanceof GxtRepairOrder) {
                // 处理维修工单
                GxtRepairOrder repairOrder = (GxtRepairOrder) order;
                List<GxtRepairOrderPerson> persons = repairOrder.getRepairOrderPersonList();

                // 如果人员列表为空，从数据库查询
                if (persons == null || persons.isEmpty()) {
                    persons = repairOrderService.selectRepairOrderPersonListByOrderId(repairOrder.getId());
                }

                if (persons != null && !persons.isEmpty()) {
                    // 添加工单个人分数明细数据
                    addOrderScoreDetailsForSuspend(repairOrder, persons, rewardScore, 2, lastBreakOrder); // 2代表运行得分

                    log.info("处理维修工单 {} 的无维修方式奖励，共 {} 人参与，每人奖励 {} 分",
                            repairOrder.getWorkOrderProjectNo(), persons.size(), rewardScore);
                }
            } else if (order instanceof GxtWorkOrder) {
                // 处理维保工单
                GxtWorkOrder workOrder = (GxtWorkOrder) order;
                List<GxtWorkOrderPerson> persons = workOrder.getWorkOrderPersonList();

                // 如果人员列表为空，从数据库查询
                if (persons == null || persons.isEmpty()) {
                    persons = workOrderService.selectWorkOrderPersonListByOrderId(workOrder.getId());
                }

                if (persons != null && !persons.isEmpty()) {
                    // 添加工单个人分数明细数据
                    addOrderScoreDetailsForSuspend(workOrder, persons, rewardScore, 2,lastBreakOrder); // 2代表运行得分

                    log.info("处理维保工单 {} 的无维修方式奖励，共 {} 人参与，每人奖励 {} 分",
                            workOrder.getWorkOrderProjectNo(), persons.size(), rewardScore);
                }
            }
        } catch (Exception e) {
            String orderNo = (order instanceof GxtRepairOrder) ?
                    ((GxtRepairOrder) order).getWorkOrderProjectNo() :
                    ((GxtWorkOrder) order).getWorkOrderProjectNo();
            log.error("处理工单 {} 无维修方式情况时发生异常", orderNo, e);
        }
    }
    
    /**
     * 添加挂起时的工单个人分数明细数据（维修工单）
     * 
     * @param repairOrder 维修工单
     * @param persons 人员列表
     * @param rewardScore 奖励分数
     * @param scoreType 分数类型
     * @param lastBreakOrder 最近中断工单
     */
    private void addOrderScoreDetailsForSuspend(GxtRepairOrder repairOrder, List<GxtRepairOrderPerson> persons, BigDecimal rewardScore, int scoreType, GxtRepairOrder lastBreakOrder) {
        try {
            for (GxtRepairOrderPerson person : persons) {
                GxtOrderScoreDetail detail = new GxtOrderScoreDetail();
                
                // 设置基础信息
                detail.setUserId(person.getUserId());
                detail.setNickName(person.getNickName());
                detail.setOrderType(1); // 维修工单
                
                // 设置工单相关信息
                detail.setOrderId(repairOrder.getId());
                detail.setOrderCode(repairOrder.getWorkOrderProjectNo());
                
                // 设置分数类型和分数
                detail.setScoreType(scoreType); // 运行得分
                detail.setScore(rewardScore);
                detail.setRunScore(rewardScore);
                detail.setStatus(1);
                // 如果有最近中断工单，记录相关信息
                if (lastBreakOrder != null) {
                    detail.setOrderCodeRelate(lastBreakOrder.getWorkOrderProjectNo());
                }

                detail.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                detail.setCreateTime(new Date());
                
                // 保存到数据库
                orderScoreDetailService.insertGxtOrderScoreDetail(detail);
            }
            
            log.info("维修工单 {} 挂起处理完成，共添加 {} 条明细记录", repairOrder.getWorkOrderProjectNo(), persons.size());
        } catch (Exception e) {
            log.error("添加维修工单挂起明细时发生异常", e);
        }
    }
    
    /**
     * 添加挂起时的工单个人分数明细数据（维保工单）
     * 
     * @param workOrder 维保工单
     * @param persons 人员列表
     * @param rewardScore 奖励分数
     * @param scoreType 分数类型
     * @param lastBreakOrder 最近中断工单
     */
    private void addOrderScoreDetailsForSuspend(GxtWorkOrder workOrder, List<GxtWorkOrderPerson> persons, BigDecimal rewardScore, int scoreType, GxtRepairOrder lastBreakOrder) {
        try {
            for (GxtWorkOrderPerson person : persons) {
                GxtOrderScoreDetail detail = new GxtOrderScoreDetail();
                
                // 设置基础信息
                detail.setUserId(person.getUserId());
                detail.setNickName(person.getNickName());
                detail.setOrderType(2); // 维保工单
                
                // 设置工单相关信息
                detail.setOrderId(workOrder.getId());
                detail.setOrderCode(workOrder.getWorkOrderProjectNo());
                
                // 设置分数类型和分数
                detail.setScoreType(scoreType); // 运行得分
                detail.setScore(rewardScore);
                detail.setRunScore(rewardScore);
                detail.setStatus(1);
                // 如果有最近中断工单，记录相关信息
                if (lastBreakOrder != null) {
                    detail.setOrderCodeRelate(lastBreakOrder.getWorkOrderProjectNo());
                }

                detail.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                detail.setCreateTime(new Date());
                
                // 保存到数据库
                orderScoreDetailService.insertGxtOrderScoreDetail(detail);
            }
            
            log.info("维保工单 {} 挂起处理完成，共添加 {} 条明细记录", workOrder.getWorkOrderProjectNo(), persons.size());
        } catch (Exception e) {
            log.error("添加维保工单挂起明细时发生异常", e);
        }
    }

    /**
     * 添加停机扣分的工单个人分数明细数据(未结单)
     *
     * @param repairOrder    维修工单
     * @param persons        更新的人员列表
     * @param deductionScore 扣分分数
     * @param scoreType      分数类型
     */
    private void addOrderScoreDetailsForStopScoreRepairNotCompllete(GxtRepairOrder repairOrder, List<GxtRepairOrderPerson> persons, BigDecimal deductionScore, int scoreType) {
        try {

            for (GxtRepairOrderPerson person : persons) {
                GxtOrderScoreDetail detail = new GxtOrderScoreDetail();

                // 设置基础信息
                detail.setUserId(person.getUserId());
                detail.setNickName(person.getNickName());
                detail.setOrderType(1); // 维修工单

                // 设置工单相关信息
                detail.setOrderId(repairOrder.getId());
                detail.setOrderCode(repairOrder.getWorkOrderProjectNo());

                // 设置分数类型和分数
                detail.setScoreType(scoreType); // 停机扣分
                detail.setScore(deductionScore);
                detail.setStopScore(deductionScore);
                detail.setStatus(1);
                detail.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                detail.setCreateTime(new Date());

                // 保存到数据库
                orderScoreDetailService.insertGxtOrderScoreDetail(detail);
            }
        } catch (Exception e) {
            log.error("添加维修工单停机扣分明细时发生异常", e);
        }
    }
    
    /**
     * 创建虚拟负责人用于处理找不到真实负责人的工单
     * 
     * @param repairOrder 维修工单
     * @return 包含虚拟负责人的列表
     */
    private List<GxtRepairOrderPerson> createVirtualLeaderPerson(GxtRepairOrder repairOrder) {
        List<GxtRepairOrderPerson> virtualPersons = new ArrayList<>();
        
        // 创建虚拟负责人
        GxtRepairOrderPerson virtualPerson = new GxtRepairOrderPerson();
        
        // 设置基本信息
        virtualPerson.setUserId(-1L); // 使用-1表示虚拟用户
        virtualPerson.setNickName("虚拟负责人");
        virtualPerson.setUserName("virtual_leader");
        
        // 设置工单相关信息
        virtualPerson.setOrderId(repairOrder.getId());
        virtualPerson.setOrderCode(repairOrder.getWorkOrderProjectNo());
        
        // 设置状态和负责人标识
        virtualPerson.setStatus(1); // 正常状态
        virtualPerson.setIsLeader(1); // 标记为负责人
        
        // 设置时间和操作人信息
        virtualPerson.setCreateBy("system");
        virtualPerson.setCreateTime(new Date());
        
        // 初始化分数字段
        virtualPerson.setSelfScore(0.0);
        virtualPerson.setReviewScore(0.0);
        virtualPerson.setFinalScore(0.0);
        virtualPerson.setScore(BigDecimal.ZERO);
        virtualPerson.setExtraScore(0.0);
        virtualPerson.setTotalScore(0.0);
        virtualPerson.setRunScore(0.0);
        virtualPerson.setStopScore(0.0);
        
        virtualPersons.add(virtualPerson);
        
        log.info("为工单 {} 创建虚拟负责人: {} (用户ID: {})", 
                repairOrder.getWorkOrderProjectNo(), 
                virtualPerson.getNickName(), 
                virtualPerson.getUserId());
        
        return virtualPersons;
    }
}