package com.ygtx.gxt.service.impl;

import com.ygtx.common.constant.CacheConstants;
import com.ygtx.common.constant.Constants;
import com.ygtx.common.core.domain.entity.SysDept;
import com.ygtx.common.core.redis.RedisCache;
import com.ygtx.common.exception.ServiceException;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.common.utils.spring.SpringUtils;
import com.ygtx.framework.web.service.SysPermissionService;
import com.ygtx.gxt.domain.*;
import com.ygtx.gxt.mapper.GxtOrderScoreMapper;
import com.ygtx.gxt.mapper.GxtRepairOrderMapper;
import com.ygtx.gxt.mapper.GxtUserScoreMapper;
import com.ygtx.gxt.mapper.GxtWorkOrderMapper;
import com.ygtx.gxt.service.*;
import com.ygtx.system.mapper.SysDeptMapper;
import com.ygtx.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.core.domain.entity.SysRole;
import com.ygtx.framework.aspectj.DataScopeAspect;
import com.ygtx.system.mapper.SysUserMapper;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 工单评分Service业务层处理
 *
 * @author lingming
 * @date 2025-11-12
 */
@Service
public class GxtOrderScoreServiceImpl implements IGxtOrderScoreService {

    @Autowired
    private GxtOrderScoreMapper gxtOrderScoreMapper;

    @Autowired
    private IGxtRepairOrderService gxtRepairOrderService;

    @Autowired
    private IGxtWorkOrderService gxtWorkOrderService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IGxtRepairOrderFlowService repairOrderFlowService;

    @Autowired
    private IGxtMonthRepairProjectService gxtMonthRepairProjectService;
    
    @Autowired
    private IGxtMonthFanInspectionService gxtMonthFanInspectionService;
    
    @Autowired
    private IGxtUserScoreService gxtUserScoreService;

    @Autowired
    private IGxtWorkOrderFlowService gxtWorkOrderFlowService;
    
    @Autowired
    private IGxtMonthScoreService gxtMonthScoreService;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private GxtRepairOrderMapper gxtRepairOrderMapper;

    @Autowired
    private GxtWorkOrderMapper gxtWorkOrderMapper;

    @Autowired
    private IGxtOrderScoreDetailService gxtOrderScoreDetailService;

    @Autowired
    private GxtUserScoreMapper gxtUserScoreMapper;

    /**
     * 查询合并的工单列表（维修工单和维保工单）
     *
     * @param repairOrder 维修工单查询条件
     * @param workOrder 维保工单查询条件
     * @return 合并的工单列表
     */
    @Override
    public List<OrderScoreInfo> selectUnionOrderList(GxtRepairOrder repairOrder, GxtWorkOrder workOrder, String keyword) {
        // 添加业务特定的数据权限过滤
        addBusinessDataScopeFilter(repairOrder, workOrder);

        // 设置创建人，用于数据权限过滤
        if(!Constants.SUPER_ADMIN.equals(SecurityUtils.getUsername())){
            if (repairOrder.getCreateBy() == null || repairOrder.getCreateBy().isEmpty()) {
                repairOrder.setCreateBy(SecurityUtils.getUsername());
            }

            if (workOrder.getCreateBy() == null || workOrder.getCreateBy().isEmpty()) {
                workOrder.setCreateBy(SecurityUtils.getUsername());
            }
        }
        // 查询工单列表
        List<OrderScoreInfo> orderList = gxtOrderScoreMapper.selectUnionOrderList(repairOrder, workOrder, keyword);

        // 为每个工单填充人员评分列表数据
        for (OrderScoreInfo order : orderList) {
            if (order.getOrderType() == 1) {
                // 维修工单
                List<GxtRepairOrderPerson> repairPersons = gxtRepairOrderService.selectRepairOrderPersonListByOrderId(order.getId());
                // 转换为OrderScorePerson列表
                List<OrderScorePerson> scorePersons = new ArrayList<>();
                for (GxtRepairOrderPerson person : repairPersons) {
                    OrderScorePerson scorePerson = new OrderScorePerson();
                    scorePerson.setId(person.getId());
                    scorePerson.setUserId(person.getUserId());
                    scorePerson.setNickName(person.getNickName());
                    scorePerson.setSelfScore(person.getSelfScore());
                    scorePerson.setReviewScore(person.getReviewScore());
                    scorePerson.setFinalScore(person.getFinalScore());
                    scorePerson.setIsLeader(person.getIsLeader());
                    scorePerson.setFeedbackReason(person.getFeedbackReason());
                    scorePerson.setConfirmStatus(person.getConfirmStatus());
                    scorePerson.setExtraScore(person.getExtraScore());
                    scorePerson.setTotalScore(person.getTotalScore());
                    scorePersons.add(scorePerson);
                    if (Objects.equals(person.getUserId(), SecurityUtils.getUserId()) && ("to_archive".equals(order.getScoringStatus()) || "archived".equals(order.getScoringStatus()))) {
                        order.setMyScore(person.getScore());
                    }
                }
                order.setScorePersonList(scorePersons);
            } else if (order.getOrderType() == 2) {
                // 维保工单
                List<GxtWorkOrderPerson> workPersons = gxtWorkOrderService.selectWorkOrderPersonListByOrderId(order.getId());
                // 转换为OrderScorePerson列表
                List<OrderScorePerson> scorePersons = new ArrayList<>();
                for (GxtWorkOrderPerson person : workPersons) {
                    OrderScorePerson scorePerson = new OrderScorePerson();
                    scorePerson.setId(person.getId());
                    scorePerson.setUserId(person.getUserId());
                    scorePerson.setNickName(person.getNickName());
                    scorePerson.setSelfScore(person.getSelfScore());
                    scorePerson.setReviewScore(person.getReviewScore());
                    scorePerson.setFinalScore(person.getFinalScore());
                    scorePerson.setIsLeader(person.getIsLeader());
                    scorePerson.setFeedbackReason(person.getFeedbackReason());
                    scorePerson.setConfirmStatus(person.getConfirmStatus());
                    scorePersons.add(scorePerson);
                    if (Objects.equals(person.getUserId(), SecurityUtils.getUserId())  && ("to_archive".equals(order.getScoringStatus()) || "archived".equals(order.getScoringStatus()))) {
                        order.setMyScore(person.getScore());
                    }
                }
                order.setScorePersonList(scorePersons);
            }
        }

        return orderList;
    }

    /**
     * 获取工单评分统计信息
     *
     * @param repairOrder 维修工单查询条件
     * @param workOrder 维保工单查询条件
     * @param month 月份筛选条件
     * @return 统计信息
     */
    @Override
    public Map<String, Object> getOrderScoreStatistics(GxtRepairOrder repairOrder, GxtWorkOrder workOrder, String month) {
        Map<String, Object> result = new HashMap<>();
        String userName = SecurityUtils.getUsername();
        if(StringUtils.isNotEmpty(userName)){
            // 添加用户ID参数用于Mapper查询 gxtUserScoreMapper
            GxtUserScore gxtUserScore = new GxtUserScore();
            gxtUserScore.setUserName(userName);
            gxtUserScore.setMonthPeriod( month);
            List<GxtUserScore> gxtUserScores = gxtUserScoreMapper.selectGxtUserScoreList(gxtUserScore);
            
            // 计算工分并赋值给result中的totalScore、maintenanceScore、repairScore
            BigDecimal totalScore = BigDecimal.ZERO;
            BigDecimal maintenanceScore = BigDecimal.ZERO;
            BigDecimal repairScore = BigDecimal.ZERO;
            
            for (GxtUserScore userScore : gxtUserScores) {
                // 累加维护总分
                if (userScore.getMaintenanceTotalScore() != null) {
                    maintenanceScore = maintenanceScore.add(userScore.getMaintenanceTotalScore());
                }
                // 累加维修总分
                if (userScore.getRepairTotalScore() != null) {
                    repairScore = repairScore.add(userScore.getRepairTotalScore());
                }
                // 累加最终得分
                if (userScore.getFinalScore() != null) {
                    totalScore = totalScore.add(userScore.getFinalScore());
                }
            }
            
            /*result.put("totalScore", totalScore.doubleValue());
            result.put("maintenanceScore", maintenanceScore.doubleValue());
            result.put("repairScore", repairScore.doubleValue());*/

            result.put("totalScore", totalScore);
            result.put("maintenanceScore", maintenanceScore);
            result.put("repairScore", repairScore);
        }
        return result;
    }

    /**
     * 判断当前用户的数据权限是否为"仅本人数据"
     *
     * @return true表示数据权限为"仅本人数据"，false表示其他权限
     */
    private boolean isCurrentUserDataScopeSelf() {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return false;
        }

        SysUser currentUser = loginUser.getUser();
        if (currentUser == null) {
            return false;
        }

        // 如果是超级管理员，不过滤数据
        if (currentUser.isAdmin()) {
            return false;
        }

        // 获取用户角色
        List<SysRole> roles = currentUser.getRoles();
        if (roles == null || roles.isEmpty()) {
            return false;
        }

        // 检查所有角色的数据权限是否都是"仅本人数据"
        for (SysRole role : roles) {
            String dataScope = role.getDataScope();
            // 如果有任何一个角色不是"仅本人数据"权限，则不显示排名
            if (!DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
                return false;
            }
        }

        // 所有角色都是"仅本人数据"权限
        return true;
    }

    /**
     * 计算用户在所在场站的排名
     *
     * @return 用户在所在场站的排名
     */
    private int calculateUserRankInStation(GxtRepairOrder repairOrder, GxtWorkOrder workOrder, String month) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return 1; // 默认排名第一
        }

        SysUser currentUser = loginUser.getUser();
        if (currentUser == null || currentUser.getUserId() == null) {
            return 1; // 默认排名第一
        }

        Long userId = currentUser.getUserId();
        Long deptId = currentUser.getDeptId();

        // 检查是否有部门ID
        if (deptId == null) {
            return 1; // 默认排名第一
        }

        // 创建不带业务数据范围过滤的新查询条件用于排名计算
        GxtRepairOrder rankRepairOrder = new GxtRepairOrder();
        GxtWorkOrder rankWorkOrder = new GxtWorkOrder();
        
        // 复制原始查询条件的参数，但移除业务数据范围过滤
        if (repairOrder != null && repairOrder.getParams() != null) {
            Map<String, Object> params = new HashMap<>(repairOrder.getParams());
            params.remove("businessDataScope");
            rankRepairOrder.setParams(params);
        }
        
        if (workOrder != null && workOrder.getParams() != null) {
            Map<String, Object> params = new HashMap<>(workOrder.getParams());
            params.remove("businessDataScope");
            rankWorkOrder.setParams(params);
        }

        // 获取当前用户处理的工单工分
        double currentUserScore = getUserScore(userId, rankRepairOrder, rankWorkOrder, month);

        // 获取同一场站其他用户的工单工分
        List<Map<String, Object>> stationUserScores = getStationUserScores(deptId, rankRepairOrder, rankWorkOrder, month);

        // 检查是否获取到用户数据
        if (stationUserScores == null || stationUserScores.isEmpty()) {
            return 1; // 只有当前用户，排名第一
        }

        // 计算排名
        int rank = 1;
        for (Map<String, Object> userScore : stationUserScores) {
            if (userScore == null || userScore.get("userId") == null || userScore.get("score") == null) {
                continue;
            }

            Long userIdInStation = (Long) userScore.get("userId");
            double score = (Double) userScore.get("score");

            // 跳过当前用户自己
            if (userIdInStation.equals(userId)) {
                continue;
            }

            // 如果其他用户的工分大于当前用户，则排名下降
            if (score > currentUserScore) {
                rank++;
            }
        }

        return rank;
    }

    /**
     * 获取用户处理的工单工分
     *
     * @param userId 用户ID
     * @return 用户处理的工单工分
     */
    private double getUserScore(Long userId, GxtRepairOrder repairOrder, GxtWorkOrder workOrder, String month) {
        // 复制查询条件
        GxtRepairOrder userRepairOrder = new GxtRepairOrder();
        if (repairOrder != null) {
            try {
                org.springframework.beans.BeanUtils.copyProperties(repairOrder, userRepairOrder);
                // 复制参数
                Map<String, Object> params = new HashMap<>();
                if (repairOrder.getParams() != null) {
                    params.putAll(repairOrder.getParams());
                }
                userRepairOrder.setParams(params);
            } catch (Exception e) {
                // 忽略拷贝异常
            }
        }

        GxtWorkOrder userWorkOrder = new GxtWorkOrder();
        if (workOrder != null) {
            try {
                org.springframework.beans.BeanUtils.copyProperties(workOrder, userWorkOrder);
                // 复制参数
                Map<String, Object> params = new HashMap<>();
                if (workOrder.getParams() != null) {
                    params.putAll(workOrder.getParams());
                }
                userWorkOrder.setParams(params);
            } catch (Exception e) {
                // 忽略拷贝异常
            }
        }

        // 为维修工单添加用户筛选条件
        if (userRepairOrder != null) {
            // 添加用户ID参数用于Mapper查询
            userRepairOrder.getParams().put("currentUserId", userId);
        }

        // 为维保工单添加用户筛选条件
        if (userWorkOrder != null) {
            // 添加用户ID参数用于Mapper查询
            userWorkOrder.getParams().put("currentUserId", userId);
        }

        // 查询用户处理的工单统计信息
        Map<String, Object> statistics = gxtOrderScoreMapper.selectOrderScoreStatistics(userRepairOrder, userWorkOrder, month);

        // 计算总工分
        Object maintenanceScoreObj = statistics.get("maintenanceScore");
        Object repairScoreObj = statistics.get("repairScore");

        double maintenanceScore = maintenanceScoreObj != null ? ((Number) maintenanceScoreObj).doubleValue() : 0.0;
        double repairScore = repairScoreObj != null ? ((Number) repairScoreObj).doubleValue() : 0.0;

        return maintenanceScore + repairScore;
    }

    /**
     * 获取场站内所有用户的工单工分
     *
     * @param deptId 场站ID
     * @return 场站内所有用户的工单工分列表
     */
    private List<Map<String, Object>> getStationUserScores(Long deptId, GxtRepairOrder repairOrder, GxtWorkOrder workOrder, String month) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Long> stationUserIds = getStationUserIds(deptId);

        // 逐个计算场站内每个用户的工分
        for (Long userId : stationUserIds) {
            double userScore = getUserScore(userId, repairOrder, workOrder, month);
            Map<String, Object> userScoreMap = new HashMap<>();
            userScoreMap.put("userId", userId);
            userScoreMap.put("score", userScore);
            result.add(userScoreMap);
        }
        return result;
    }

    /**
     * 获取场站内所有用户ID
     *
     * @param deptId 场站ID
     * @return 场站内所有用户ID列表
     */
    private List<Long> getStationUserIds(Long deptId) {
        if (deptId == null) {
            return new ArrayList<>(); // 返回空列表而不是null
        }

        SysUser user = new SysUser();
        user.setDeptId(deptId);
        List<SysUser> sysUsers = userMapper.selectUserListByDeptId(user);
        List<Long> userIds = new ArrayList<>();
        if (sysUsers != null) {
            sysUsers.forEach(sysUser -> {
                if (sysUser != null && sysUser.getUserId() != null) {
                    userIds.add(sysUser.getUserId());
                }
            });
        }
        return userIds;
    }

    /**
     * 保存自评信息
     *
     * @param orderScoreInfo 工单评分信息
     * @return 结果
     */
    @Override
    @Transactional
    public int selfEvaluation(OrderScoreInfo orderScoreInfo) {
        try {
            if (orderScoreInfo.getOrderType() == 1) {
                GxtRepairOrder oldOrder = gxtRepairOrderService.selectGxtRepairOrderById(orderScoreInfo.getId());
                if(!oldOrder.getScoringStatus().equals("to_self") && !oldOrder.getScoringStatus().equals("returned") ){
                    throw new ServiceException("该工单状态已变更，不能自评！");
                }
                // 维修工单自评
                GxtRepairOrder order = new GxtRepairOrder();
                order.setId(orderScoreInfo.getId());
                order.setMaintenanceType(orderScoreInfo.getMaintenanceType());
                order.setContent(orderScoreInfo.getWorkSummary());
                order.setExtraWork(orderScoreInfo.getExtraWork());
                order.setScoringStatus("to_re"); // 提交自评后状态改为待复评

                // 计算自评总分并设置到工单对象
                if (orderScoreInfo.getScorePersonList() != null) {
                    double totalScore = orderScoreInfo.getScorePersonList().stream()
                            .mapToDouble(person -> person.getTotalScore() != null ? person.getTotalScore() : 0.0)
                            .sum();
                    order.setScore(new BigDecimal(String.valueOf(totalScore)));
                }
                order.setUpdateTime(new Date());
                order.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                // 更新工单信息
                int result = gxtRepairOrderService.updateGxtRepairOrderForScore(order);

                // 更新人员评分信息
                if (orderScoreInfo.getScorePersonList() != null) {
                    List<GxtRepairOrderPerson> personList = new ArrayList<>();
                    for (OrderScorePerson person : orderScoreInfo.getScorePersonList()) {
                        GxtRepairOrderPerson repairPerson = new GxtRepairOrderPerson();
                        repairPerson.setId(person.getId());
                        repairPerson.setSelfScore(person.getSelfScore());
                        repairPerson.setExtraScore(person.getExtraScore());
                        repairPerson.setTotalScore(person.getTotalScore());
                        //repairPerson.setIsLeader(person.getIsLeader());
                        personList.add(repairPerson);
                    }
                    gxtRepairOrderService.updateRepairOrderPersonList(personList);
                }

                // 添加工单流转记录
                GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
                flow.setOrderId(orderScoreInfo.getId());
                flow.setOrderCode(orderScoreInfo.getWorkOrderProjectNo());
                flow.setActionType("selfRating");
                flow.setFromStatus(oldOrder.getWorkOrderStatus());
                flow.setToStatus(oldOrder.getWorkOrderStatus());
                flow.setFromScoreStatus(oldOrder.getScoringStatus());
                flow.setToScoreStatus(order.getScoringStatus());
                flow.setOperatorId(SecurityUtils.getUserId());
                flow.setOperatorName(SecurityUtils.getLoginUser().getUser().getNickName());
                flow.setActionTime(DateUtils.getNowDate());
                flow.setActionRemark("提交自评");
                repairOrderFlowService.insertGxtRepairOrderFlow(flow);

                return result;
            } else if (orderScoreInfo.getOrderType() == 2) {
                GxtWorkOrder oldOrder = gxtWorkOrderService.selectGxtWorkOrderById(orderScoreInfo.getId());
                if(!oldOrder.getScoringStatus().equals("to_self") && !oldOrder.getScoringStatus().equals("returned") ){
                    throw new ServiceException("该工单状态已变更，不能自评！");
                }
                // 维保工单自评
                GxtWorkOrder order = new GxtWorkOrder();
                order.setId(orderScoreInfo.getId());
                order.setInspectionType(orderScoreInfo.getInspectionType());
                order.setRealContent(orderScoreInfo.getWorkSummary());
                /*order.setRealStartTime(orderScoreInfo.getRealStartTime());
                order.setRealEndTime(orderScoreInfo.getWorkEndTime());*/
                order.setItemCompletionFactor(orderScoreInfo.getItemCompletionFactor());
                order.setItemCompletionFactorSum(orderScoreInfo.getItemCompletionFactorSum());
                order.setScoringStatus("to_re"); // 提交自评后状态改为待复评

                // 计算自评总分并设置到工单对象
                if (orderScoreInfo.getScorePersonList() != null) {
                    /*double totalScore = orderScoreInfo.getScorePersonList().stream()
                            .mapToDouble(person -> person.getSelfScore() != null ? person.getSelfScore() : 0.0)
                            .sum();*/
                    double totalScore = orderScoreInfo.getScorePersonList().stream()
                            .mapToDouble(person -> person.getTotalScore() != null ? person.getTotalScore() : 0.0)
                            .sum();
                    order.setScore(new BigDecimal(String.valueOf(totalScore)));
                }
                order.setUpdateTime(new Date());
                order.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                // 更新工单信息
                int result = gxtWorkOrderService.updateGxtWorkOrderForScore(order);

                // 更新人员评分信息
                if (orderScoreInfo.getScorePersonList() != null) {
                    List<GxtWorkOrderPerson> personList = new ArrayList<>();
                    for (OrderScorePerson person : orderScoreInfo.getScorePersonList()) {
                        GxtWorkOrderPerson workPerson = new GxtWorkOrderPerson();
                        workPerson.setId(person.getId());
                        workPerson.setSelfScore(person.getSelfScore());
                        //workPerson.setIsLeader(person.getIsLeader());
                        workPerson.setExtraScore(person.getExtraScore());
                        workPerson.setTotalScore(person.getTotalScore());
                        personList.add(workPerson);
                    }
                    gxtWorkOrderService.updateWorkOrderPersonList(personList);
                }

                // 添加工单流转记录
                GxtWorkOrderFlow flow = new GxtWorkOrderFlow();
                flow.setOrderId(orderScoreInfo.getId());
                flow.setOrderCode(orderScoreInfo.getWorkOrderProjectNo());
                flow.setActionType("selfRating");
                flow.setFromStatus(oldOrder.getWorkOrderStatus());
                flow.setToStatus(oldOrder.getWorkOrderStatus());
                flow.setFromScoreStatus(oldOrder.getScoringStatus());
                flow.setToScoreStatus(order.getScoringStatus());
                flow.setOperatorId(SecurityUtils.getUserId());
                flow.setOperatorName(SecurityUtils.getLoginUser().getUser().getNickName());
                flow.setActionTime(DateUtils.getNowDate());
                flow.setActionRemark("提交自评");
                gxtWorkOrderFlowService.insertGxtWorkOrderFlow(flow);

                return result;
            }
            return 0;
        } catch (Exception e) {
            throw new RuntimeException("保存自评信息失败：" + e.getMessage(), e);
        }
    }

    /**
     * 保存复评信息
     *
     * @param orderScoreInfo 工单评分信息
     * @return 结果
     */
    @Override
    @Transactional
    public int review(OrderScoreInfo orderScoreInfo) {
        try {
            if (orderScoreInfo.getOrderType() == 1) {
                GxtRepairOrder oldOrder = gxtRepairOrderService.selectGxtRepairOrderById(orderScoreInfo.getId());
                if(!oldOrder.getScoringStatus().equals("to_re")){
                    throw new ServiceException("该工单状态已变更，不能复评！");
                }
                // 维修工单复评
                GxtRepairOrder order = new GxtRepairOrder();
                order.setId(orderScoreInfo.getId());
                // 检查是否为评分退回操作
                if (StringUtils.isNotEmpty(orderScoreInfo.getScoreReturnReason())) {
                    // 评分退回操作：设置为已退回状态
                    order.setScoringStatus("returned");
                    order.setScoreReturnReason(orderScoreInfo.getScoreReturnReason());
                } else {
                    // 正常复评操作
                    order.setMaintenanceType(orderScoreInfo.getMaintenanceType());
                    order.setModifyReason(orderScoreInfo.getModifyReason());
                    order.setReviewScoreNum(orderScoreInfo.getReviewScoreNum());
                    order.setFinalCoefficient(orderScoreInfo.getFinalCoefficient());
                    /*if(orderScoreInfo.getReviewScoreNum() == 1){
                        order.setScoringStatus("to_confirm");
                    }else if(orderScoreInfo.getReviewScoreNum() == 2){
                        order.setScoringStatus("to_final");
                    }*/

                    if(oldOrder.getRestartTime() != null){
                        order.setScoringStatus("archived");
                        order.setWorkOrderStatus("archived");
                    }else{
                        order.setScoringStatus("to_archive");
                    }
                    //order.setScoringStatus("to_final");
                }
                // 计算复评总分并设置到工单对象
                if (orderScoreInfo.getScorePersonList() != null) {
                    /*double totalScore = orderScoreInfo.getScorePersonList().stream()
                            .mapToDouble(person -> person.getReviewScore() != null ? person.getReviewScore() : 0.0)
                            .sum();
                     ;*/
                    double totalScore = orderScoreInfo.getScorePersonList().stream()
                            .mapToDouble(person -> person.getTotalScore() != null ? person.getTotalScore() : 0.0)
                            .sum();
                    order.setScore(new BigDecimal(String.valueOf(totalScore)));
                }
                order.setUpdateTime(new Date());
                order.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                // 更新工单信息
                int result = gxtRepairOrderService.updateGxtRepairOrderForScore(order);

                // 更新人员评分信息
                if (StringUtils.isEmpty(orderScoreInfo.getScoreReturnReason()) && orderScoreInfo.getScorePersonList() != null) {
                    List<GxtRepairOrderPerson> personList = new ArrayList<>();
                    for (OrderScorePerson person : orderScoreInfo.getScorePersonList()) {
                        GxtRepairOrderPerson repairPerson = new GxtRepairOrderPerson();
                        repairPerson.setId(person.getId());
                        repairPerson.setReviewScore(person.getReviewScore());
                        //repairPerson.setScore(person.getReviewScore() != null ? BigDecimal.valueOf(person.getReviewScore()) : null);
                        repairPerson.setTotalScore(person.getTotalScore());
                        // 计算总分时考虑runScore
                        Double calculatedScore = (person.getTotalScore() != null ? person.getTotalScore() : 0.0) + 
                                          (person.getRunScore() != null ? person.getRunScore() : 0.0) +  (person.getStopScore() != null ? person.getStopScore() : 0.0);
                        repairPerson.setScore(calculatedScore != 0.0 ? BigDecimal.valueOf(calculatedScore) : null);
                        personList.add(repairPerson);
                    }
                    gxtRepairOrderService.updateRepairOrderPersonList(personList);
                }

                // 添加工单流转记录
                GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
                flow.setOrderId(orderScoreInfo.getId());
                flow.setOrderCode(orderScoreInfo.getWorkOrderProjectNo());
                if (StringUtils.isNotEmpty(orderScoreInfo.getScoreReturnReason())) {
                    // 评分退回操作
                    flow.setActionType("returnRating");
                    flow.setActionRemark("退回原因：" + orderScoreInfo.getScoreReturnReason());
                } else {
                    // 正常复评操作
                    flow.setActionType("reviewRating");
                    flow.setActionRemark("提交复评");
                }
                flow.setFromStatus(oldOrder.getWorkOrderStatus());
                flow.setToStatus(oldOrder.getWorkOrderStatus());
                flow.setFromScoreStatus(oldOrder.getScoringStatus());
                flow.setToScoreStatus(order.getScoringStatus());
                flow.setOperatorId(SecurityUtils.getUserId());
                flow.setOperatorName(SecurityUtils.getLoginUser().getUser().getNickName());
                flow.setActionTime(DateUtils.getNowDate());
                repairOrderFlowService.insertGxtRepairOrderFlow(flow);

                if("archived".equals(order.getWorkOrderStatus())){
                    // 添加归档流程记录
                    flow = new GxtRepairOrderFlow();
                    flow.setOrderId(order.getId());
                    flow.setOrderCode(orderScoreInfo.getWorkOrderProjectNo());
                    flow.setActionType("archive");
                    flow.setFromStatus("to_archive");
                    flow.setToStatus("archived");
                    flow.setOperatorId(1L); // 系统自动操作，使用系统用户ID
                    flow.setOperatorName("系统自动");
                    flow.setActionTime(DateUtils.getNowDate());
                    flow.setActionRemark("系统自动归档工单");
                    repairOrderFlowService.insertGxtRepairOrderFlow(flow);
                }
                if ("to_archive".equals(order.getScoringStatus()) || "archived".equals(order.getScoringStatus())) {
                    // 更新月度统计数据
                    updateMonthlyScoreData(orderScoreInfo);
                    
                    // 添加工单个人分数明细数据
                    addOrderScoreDetails(orderScoreInfo);
                }
                return result;
            } else if (orderScoreInfo.getOrderType() == 2) {
                // 维保工单复评
                GxtWorkOrder oldOrder = gxtWorkOrderService.selectGxtWorkOrderById(orderScoreInfo.getId());
                if(!oldOrder.getScoringStatus().equals("to_re")){
                    throw new ServiceException("该工单状态已变更，不能复评！");
                }
                GxtWorkOrder order = new GxtWorkOrder();
                order.setId(orderScoreInfo.getId());
                order.setItemCompletionFactor(orderScoreInfo.getItemCompletionFactor());
                order.setModifyReason(orderScoreInfo.getModifyReason());
                order.setReviewScoreNum(orderScoreInfo.getReviewScoreNum());
                /*if(orderScoreInfo.getReviewScoreNum() == 1){
                    order.setScoringStatus("to_confirm");
                }else if(orderScoreInfo.getReviewScoreNum() == 2){
                    order.setScoringStatus("to_final");
                }*/
                if (StringUtils.isNotEmpty(orderScoreInfo.getScoreReturnReason())) {
                    // 评分退回操作：设置为已退回状态
                    order.setScoringStatus("returned");
                    order.setScoreReturnReason(orderScoreInfo.getScoreReturnReason());
                }else{
                    if(oldOrder.getRestartTime() != null){
                        order.setScoringStatus("archived");
                        order.setWorkOrderStatus("archived");
                    }else{
                        order.setScoringStatus("to_archive");
                    }
                }

                // 计算复评总分并设置到工单对象
                if (orderScoreInfo.getScorePersonList() != null) {
                    /*double totalScore = orderScoreInfo.getScorePersonList().stream()
                            .mapToDouble(person -> person.getReviewScore() != null ? person.getReviewScore() : 0.0)
                            .sum();*/
                    double totalScore = orderScoreInfo.getScorePersonList().stream()
                            .mapToDouble(person -> person.getTotalScore() != null ? person.getTotalScore() : 0.0)
                            .sum();
                    order.setScore(new BigDecimal(String.valueOf(totalScore)));
                }
                order.setUpdateTime(new Date());
                order.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                // 更新工单信息
                int result = gxtWorkOrderService.updateGxtWorkOrderForScore(order);

                // 更新人员评分信息
                if (StringUtils.isEmpty(orderScoreInfo.getScoreReturnReason()) && orderScoreInfo.getScorePersonList() != null) {
                    List<GxtWorkOrderPerson> personList = new ArrayList<>();
                    for (OrderScorePerson person : orderScoreInfo.getScorePersonList()) {
                        GxtWorkOrderPerson workPerson = new GxtWorkOrderPerson();
                        workPerson.setId(person.getId());
                        workPerson.setReviewScore(person.getReviewScore());
                        //workPerson.setScore(person.getReviewScore() != null ? BigDecimal.valueOf(person.getReviewScore()) : null);
                        workPerson.setTotalScore(person.getTotalScore());
                        // 计算总分时考虑runScore
                        Double calculatedScore = (person.getTotalScore() != null ? person.getTotalScore() : 0.0) + 
                                          (person.getRunScore() != null ? person.getRunScore() : 0.0) +  (person.getStopScore() != null ? person.getStopScore() : 0.0);
                        workPerson.setScore(calculatedScore != 0.0 ? BigDecimal.valueOf(calculatedScore) : null);
                        personList.add(workPerson);
                    }
                    gxtWorkOrderService.updateWorkOrderPersonList(personList);
                }

                // 添加工单流转记录
                GxtWorkOrderFlow flow = new GxtWorkOrderFlow();
                flow.setOrderId(orderScoreInfo.getId());
                flow.setOrderCode(orderScoreInfo.getWorkOrderProjectNo());
                if (StringUtils.isNotEmpty(orderScoreInfo.getScoreReturnReason())) {
                    // 评分退回操作
                    flow.setActionType("returnRating");
                    flow.setActionRemark("退回原因：" + orderScoreInfo.getScoreReturnReason());
                } else {
                    // 正常复评操作
                    flow.setActionType("reviewRating");
                    flow.setActionRemark("提交复评");
                }
                flow.setFromStatus(oldOrder.getWorkOrderStatus());
                flow.setToStatus(oldOrder.getWorkOrderStatus());
                flow.setFromScoreStatus(oldOrder.getScoringStatus());
                flow.setToScoreStatus(order.getScoringStatus());
                flow.setOperatorId(SecurityUtils.getUserId());
                flow.setOperatorName(SecurityUtils.getLoginUser().getUser().getNickName());
                flow.setActionTime(DateUtils.getNowDate());
                gxtWorkOrderFlowService.insertGxtWorkOrderFlow(flow);
                if("archived".equals(order.getWorkOrderStatus())){
                    // 添加归档流程记录
                    flow = new GxtWorkOrderFlow();
                    flow.setOrderId(order.getId());
                    flow.setOrderCode(orderScoreInfo.getWorkOrderProjectNo());
                    flow.setActionType("archive");
                    flow.setFromStatus("to_archive");
                    flow.setToStatus("archived");
                    flow.setOperatorId(1L); // 系统自动操作，使用系统用户ID
                    flow.setOperatorName("系统自动");
                    flow.setActionTime(DateUtils.getNowDate());
                    flow.setActionRemark("系统自动归档工单");
                    gxtWorkOrderFlowService.insertGxtWorkOrderFlow(flow);
                }
                if ("to_archive".equals(order.getScoringStatus()) || "archived".equals(order.getScoringStatus())) {
                    // 更新月度统计数据
                    updateMonthlyScoreData(orderScoreInfo);
                    
                    // 添加工单个人分数明细数据
                    addOrderScoreDetails(orderScoreInfo);
                }
                return result;
            }
            return 0;
        } catch (Exception e) {
            throw new RuntimeException("保存复评信息失败：" + e.getMessage(), e);
        }
    }

    /**
     * 保存终评信息
     *
     * @param orderScoreInfo 工单评分信息
     * @return 结果
     */
    @Override
    @Transactional
    public int finalEvaluation(OrderScoreInfo orderScoreInfo) {
        try {
            if (orderScoreInfo.getOrderType() == 1) {
                // 维修工单终评
                GxtRepairOrder oldOrder = gxtRepairOrderService.selectGxtRepairOrderById(orderScoreInfo.getId());
                // 更新人员评分信息
                if (orderScoreInfo.getScorePersonList() != null) {
                    List<GxtRepairOrderPerson> personList = new ArrayList<>();
                    for (OrderScorePerson person : orderScoreInfo.getScorePersonList()) {
                        GxtRepairOrderPerson repairPerson = new GxtRepairOrderPerson();
                        repairPerson.setId(person.getId());
                        repairPerson.setFinalScore(person.getFinalScore());
                        repairPerson.setTotalScore(person.getTotalScore());
                        // 计算总分时考虑runScore
                        Double calculatedScore = (person.getTotalScore() != null ? person.getTotalScore() : 0.0) + 
                                          (person.getRunScore() != null ? person.getRunScore() : 0.0) +  (person.getStopScore() != null ? person.getStopScore() : 0.0);
                        repairPerson.setScore(calculatedScore != 0.0 ? BigDecimal.valueOf(calculatedScore) : null);
                        personList.add(repairPerson);
                    }
                    gxtRepairOrderService.updateRepairOrderPersonList(personList);
                }
                //GxtRepairOrder orderSearch = gxtRepairOrderService.selectGxtRepairOrderById(orderScoreInfo.getId());
                // 更新工单状态
                GxtRepairOrder order = new GxtRepairOrder();
                order.setId(orderScoreInfo.getId());
                if(oldOrder.getRestartTime() != null){
                    order.setScoringStatus("archived");
                    order.setWorkOrderStatus("archived");
                }else{
                    order.setScoringStatus("to_archive");
                }
                order.setFinalCoefficient(orderScoreInfo.getFinalCoefficient());

                // 计算终评总分并设置到工单对象
                if (orderScoreInfo.getScorePersonList() != null) {
                    double totalScore = orderScoreInfo.getScorePersonList().stream()
                            .mapToDouble(person -> person.getTotalScore() != null ? person.getTotalScore() : 0.0)
                            .sum();
                    order.setScore(new BigDecimal(String.valueOf(totalScore)));
                }
                order.setUpdateTime(new Date());
                order.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                gxtRepairOrderService.updateGxtRepairOrderForScore(order);

                // 添加工单流转记录
                GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
                flow.setOrderId(orderScoreInfo.getId());
                flow.setOrderCode(orderScoreInfo.getWorkOrderProjectNo());
                flow.setActionType("finalRating");
                flow.setFromStatus(oldOrder.getWorkOrderStatus());
                flow.setToStatus(oldOrder.getWorkOrderStatus());
                flow.setFromScoreStatus(oldOrder.getScoringStatus());
                flow.setToScoreStatus(order.getScoringStatus());
                flow.setOperatorId(SecurityUtils.getUserId());
                flow.setOperatorName(SecurityUtils.getLoginUser().getUser().getNickName());
                flow.setActionTime(DateUtils.getNowDate());
                flow.setActionRemark("提交终评");
                repairOrderFlowService.insertGxtRepairOrderFlow(flow);

                if("archived".equals(order.getWorkOrderStatus())){
                    // 添加归档流程记录
                    flow = new GxtRepairOrderFlow();
                    flow.setOrderId(order.getId());
                    flow.setOrderCode(orderScoreInfo.getWorkOrderProjectNo());
                    flow.setActionType("archive");
                    flow.setFromStatus("to_archive");
                    flow.setToStatus("archived");
                    flow.setOperatorId(1L); // 系统自动操作，使用系统用户ID
                    flow.setOperatorName("系统自动");
                    flow.setActionTime(DateUtils.getNowDate());
                    flow.setActionRemark("系统自动归档工单");
                    repairOrderFlowService.insertGxtRepairOrderFlow(flow);
                }
                if("to_final".equals(oldOrder.getScoringStatus())){
                    // 更新月度统计数据
                    updateMonthlyScoreData(orderScoreInfo);

                    // 添加工单个人分数明细数据
                    addOrderScoreDetails(orderScoreInfo);
                }else if("appealing".equals(oldOrder.getScoringStatus())){
                    // 更新月度统计数据（仅更新用户得分）
                    updateMonthlyScoreDataForFinalEval(orderScoreInfo);
                }
                return 1;
            } else if (orderScoreInfo.getOrderType() == 2) {
                // 维保工单终评
                GxtWorkOrder oldOrder = gxtWorkOrderService.selectGxtWorkOrderById(orderScoreInfo.getId());
                // 更新人员评分信息
                if (orderScoreInfo.getScorePersonList() != null) {
                    List<GxtWorkOrderPerson> personList = new ArrayList<>();
                    for (OrderScorePerson person : orderScoreInfo.getScorePersonList()) {
                        GxtWorkOrderPerson workPerson = new GxtWorkOrderPerson();
                        workPerson.setId(person.getId());
                        workPerson.setFinalScore(person.getFinalScore());
                        //workPerson.setScore(person.getFinalScore() != null ? BigDecimal.valueOf(person.getFinalScore()) : null);
                        workPerson.setTotalScore(person.getTotalScore());
                        // 计算总分时考虑runScore
                        Double calculatedScore = (person.getTotalScore() != null ? person.getTotalScore() : 0.0) + 
                                          (person.getRunScore() != null ? person.getRunScore() : 0.0) +  (person.getStopScore() != null ? person.getStopScore() : 0.0);
                        workPerson.setScore(calculatedScore != 0.0 ? BigDecimal.valueOf(calculatedScore) : null);
                        personList.add(workPerson);
                    }
                    gxtWorkOrderService.updateWorkOrderPersonList(personList);
                }
                //GxtWorkOrder orderSearch = gxtWorkOrderService.selectGxtWorkOrderById(orderScoreInfo.getId());
                // 更新工单状态
                GxtWorkOrder order = new GxtWorkOrder();
                order.setId(orderScoreInfo.getId());
                if(oldOrder.getRestartTime() != null){
                    order.setScoringStatus("archived");
                    order.setWorkOrderStatus("archived");
                }else{
                    order.setScoringStatus("to_archive");
                }
                order.setFinalCoefficient(orderScoreInfo.getFinalCoefficient());

                // 计算终评总分并设置到工单对象
                if (orderScoreInfo.getScorePersonList() != null) {
                    /*double totalScore = orderScoreInfo.getScorePersonList().stream()
                            .mapToDouble(person -> person.getFinalScore() != null ? person.getFinalScore() : 0.0)
                            .sum();*/
                    double totalScore = orderScoreInfo.getScorePersonList().stream()
                            .mapToDouble(person -> person.getTotalScore() != null ? person.getTotalScore() : 0.0)
                            .sum();
                    order.setScore(new BigDecimal(String.valueOf(totalScore)));
                }
                order.setUpdateTime(new Date());
                order.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                gxtWorkOrderService.updateGxtWorkOrderForScore(order);

                // 添加工单流转记录
                GxtWorkOrderFlow flow = new GxtWorkOrderFlow();
                flow.setOrderId(orderScoreInfo.getId());
                flow.setOrderCode(orderScoreInfo.getWorkOrderProjectNo());
                flow.setActionType("finalRating");
                flow.setFromStatus(oldOrder.getWorkOrderStatus());
                flow.setToStatus(oldOrder.getWorkOrderStatus());
                flow.setFromScoreStatus(oldOrder.getScoringStatus());
                flow.setToScoreStatus(order.getScoringStatus());
                flow.setOperatorId(SecurityUtils.getUserId());
                flow.setOperatorName(SecurityUtils.getLoginUser().getUser().getNickName());
                flow.setActionTime(DateUtils.getNowDate());
                flow.setActionRemark("提交终评");
                gxtWorkOrderFlowService.insertGxtWorkOrderFlow(flow);

                if("archived".equals(order.getWorkOrderStatus())){
                    // 添加归档流程记录
                    flow = new GxtWorkOrderFlow();
                    flow.setOrderId(order.getId());
                    flow.setOrderCode(orderScoreInfo.getWorkOrderProjectNo());
                    flow.setActionType("archive");
                    flow.setFromStatus("to_archive");
                    flow.setToStatus("archived");
                    flow.setOperatorId(1L); // 系统自动操作，使用系统用户ID
                    flow.setOperatorName("系统自动");
                    flow.setActionTime(DateUtils.getNowDate());
                    flow.setActionRemark("系统自动归档工单");
                    gxtWorkOrderFlowService.insertGxtWorkOrderFlow(flow);
                }

                if("to_final".equals(oldOrder.getScoringStatus())){
                    // 更新月度统计数据
                    updateMonthlyScoreData(orderScoreInfo);

                    // 添加工单个人分数明细数据
                    addOrderScoreDetails(orderScoreInfo);
                }else if("appealing".equals(oldOrder.getScoringStatus())){
                    // 更新月度统计数据（仅更新用户得分）
                    updateMonthlyScoreDataForFinalEval(orderScoreInfo);
                }
                return 1;
            }
            return 0;
        } catch (Exception e) {
            throw new RuntimeException("保存终评信息失败：" + e.getMessage(), e);
        }
    }

    /**
     * 更新月度统计数据
     * @param orderScoreInfo 工单对象
     */
    private void updateMonthlyScoreData(OrderScoreInfo orderScoreInfo) {
        try {
            Date realEndTime = new Date();
            if (orderScoreInfo.getOrderType() == 1) {
                // 维修工单
                GxtRepairOrder order = gxtRepairOrderService.selectGxtRepairOrderById(orderScoreInfo.getId());
                // 获取工单完成时间所在的月份
                if (order.getRealEndTime() != null) {
                    realEndTime = order.getRealEndTime();
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                //String monthPeriod = sdf.format(order.getOccurTime());
                //String monthPeriod = sdf.format(new Date());
                String monthPeriod = sdf.format(realEndTime);

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

                // 获取月度统计信息 - 使用简单查询替代复杂的 getGxtMonthScoreByParams 方法
                GxtMonthScore queryScore = new GxtMonthScore();
                queryScore.setDeptId(deptId);
                queryScore.setMonthPeriod(monthPeriod);
                List<GxtMonthScore> scoreList = gxtMonthScoreService.selectGxtMonthScoreList(queryScore);
                GxtMonthScore monthScore = null;
                if (!scoreList.isEmpty()) {
                    monthScore = scoreList.get(0);
                }

                if (monthScore == null) {
                    // 新增monthScore
                    monthScore = new GxtMonthScore();
                    monthScore.setDeptId(deptId);
                    monthScore.setMonthPeriod(monthPeriod);
                    monthScore.setStatus(0); // 初始状态
                    monthScore.setPersionId(SecurityUtils.getUserId());
                    monthScore.setCreateBy(SecurityUtils.getUsername());
                    monthScore.setCreateTime(new Date());
                    gxtMonthScoreService.insertGxtMonthScore(monthScore);
                    // 直接查询刚插入的记录
                    queryScore = new GxtMonthScore();
                    queryScore.setDeptId(deptId);
                    queryScore.setMonthPeriod(monthPeriod);
                    scoreList = gxtMonthScoreService.selectGxtMonthScoreList(queryScore);
                    if (!scoreList.isEmpty()) {
                        monthScore = scoreList.get(0);
                    }
                }
                // 更新月度场站维修项目工单统计
                //updateMonthRepairProject(monthScore, order);

                // 更新用户评分统计
                updateUserScores(monthScore, order);
            } else if (orderScoreInfo.getOrderType() == 2) {
                // 维保工单
                GxtWorkOrder order = gxtWorkOrderService.selectGxtWorkOrderById(orderScoreInfo.getId());
                // 获取工单完成时间所在的月份
                if (order.getRealEndTime() != null) {
                    realEndTime = order.getRealEndTime();
                }

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                //String monthPeriod = sdf.format(order.getCreateTime());
                //String monthPeriod = sdf.format(new Date());
                String monthPeriod = sdf.format(realEndTime);

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

                // 获取月度统计信息 - 使用简单查询替代复杂的 getGxtMonthScoreByParams 方法
                GxtMonthScore queryScore = new GxtMonthScore();
                queryScore.setDeptId(deptId);
                queryScore.setMonthPeriod(monthPeriod);
                List<GxtMonthScore> scoreList = gxtMonthScoreService.selectGxtMonthScoreList(queryScore);
                GxtMonthScore monthScore = null;
                if (!scoreList.isEmpty()) {
                    monthScore = scoreList.get(0);
                }

                if (monthScore == null) {
                    // 新增monthScore
                    monthScore = new GxtMonthScore();
                    monthScore.setDeptId(deptId);
                    monthScore.setMonthPeriod(monthPeriod);
                    monthScore.setStatus(0); // 初始状态
                    monthScore.setPersionId(SecurityUtils.getUserId());
                    monthScore.setCreateBy(SecurityUtils.getUsername());
                    monthScore.setCreateTime(new Date());
                    gxtMonthScoreService.insertGxtMonthScore(monthScore);
                    // 直接查询刚插入的记录
                    queryScore = new GxtMonthScore();
                    queryScore.setDeptId(deptId);
                    queryScore.setMonthPeriod(monthPeriod);
                    scoreList = gxtMonthScoreService.selectGxtMonthScoreList(queryScore);
                    if (!scoreList.isEmpty()) {
                        monthScore = scoreList.get(0);
                    }
                }
                // 更新月度场站风机类型工单统计
                //updateMonthFanInspection(monthScore, order);

                // 更新用户评分统计
                updateUserScores(monthScore, order);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 更新月度场站风机类型工单统计
     * @param monthScore 月度统计信息
     * @param order 工单对象
     */
    private void updateMonthFanInspection(GxtMonthScore monthScore, GxtWorkOrder order) {
        try {
            // 拆分逗号分隔的检查类型
            String[] inspectionTypes = {};
            if (order.getInspectionType() != null && !order.getInspectionType().isEmpty()) {
                inspectionTypes = order.getInspectionType().split(",");
            }
            
            // 先查询该工单所属月度统计下的风机检查类型统计记录
            GxtMonthFanInspection queryFanInspection = new GxtMonthFanInspection();
            queryFanInspection.setMonthScoreId(monthScore.getId());
            queryFanInspection.setDeptId(order.getPcsStationPid());
            queryFanInspection.setMonthPeriod(monthScore.getMonthPeriod());
            // 查询所有该月度统计下的风机检查类型统计记录
            List<GxtMonthFanInspection> fanInspections = gxtMonthFanInspectionService.selectGxtMonthFanInspectionList(queryFanInspection);
            
            // 对每个检查类型进行处理
            for (String inspectionType : inspectionTypes) {
                if (inspectionType == null || inspectionType.trim().isEmpty()) {
                    continue;
                }
                inspectionType = inspectionType.trim(); // 去除空格
                
                // 在结果中查找匹配当前工单model和当前inspectionType的记录
                GxtMonthFanInspection matchedRecord = null;
                for (GxtMonthFanInspection fanInspection : fanInspections) {
                    if (order.getModel() != null && order.getModel().equals(fanInspection.getModel()) 
                        && inspectionType.equals(fanInspection.getInspectionTypeId())) {
                        matchedRecord = fanInspection;
                        break;
                    }
                }
                
                if (matchedRecord != null) {
                    // 如果存在记录，则更新设备数量和计算得分
                    // 每种检查类型都要统计一次设备数量
                    matchedRecord.setDeviceCount(matchedRecord.getDeviceCount() != null ? matchedRecord.getDeviceCount() + 1 : 1);
                    
                    // 如果有项目分值，则重新计算得分
                    if (matchedRecord.getFanInspectionScore() != null) {
                        BigDecimal calculatedScore = matchedRecord.getFanInspectionScore()
                            .multiply(new BigDecimal(matchedRecord.getDeviceCount()));
                        matchedRecord.setCalculatedScore(calculatedScore);
                    }
                    matchedRecord.setUpdateBy(SecurityUtils.getUsername());
                    matchedRecord.setUpdateTime(new Date());
                    gxtMonthFanInspectionService.updateGxtMonthFanInspection(matchedRecord);
                } else {
                    // 如果不存在记录，则通过selectGxtMonthFanInspectionListByAdd获取初始化数据后插入
                    
                    // 构造查询条件以从数据库获取待插入的数据
                    GxtMonthFanInspection templateQuery = new GxtMonthFanInspection();
                    templateQuery.setDeptId(order.getPcsStationPid());
                    templateQuery.setMonthPeriod(monthScore.getMonthPeriod());
                    
                    // 使用selectGxtMonthFanInspectionListByAdd方法获取模板数据
                    List<GxtMonthFanInspection> templateList = gxtMonthFanInspectionService.selectGxtMonthFanInspectionListByAdd(templateQuery);

                    // 在templateList中查找与当前工单匹配的记录
                    for (GxtMonthFanInspection templateItem : templateList) {
                        if (order.getModel() != null && order.getModel().equals(templateItem.getModel()) 
                            && inspectionType.equals(templateItem.getInspectionTypeId())) {
                            SysDept dept = sysDeptMapper.selectDeptById(order.getPcsStationPid());
                            // 设置关联的月度统计ID和其他必要字段
                            templateItem.setMonthScoreId(monthScore.getId());
                            templateItem.setDeptId(order.getPcsStationPid());
                            templateItem.setDeptName(dept.getDeptName());
                            templateItem.setMonthPeriod(monthScore.getMonthPeriod());
                            templateItem.setStatus(0);
                            templateItem.setCreateBy(SecurityUtils.getUsername());
                            templateItem.setCreateTime(new Date());
                            /*// 设置初始设备数量为1（因为这是一个工单）
                            templateItem.setDeviceCount(1);
                            // 如果有项目分值，则设置初始计算得分
                            if (templateItem.getFanInspectionScore() != null) {
                                templateItem.setCalculatedScore(templateItem.getFanInspectionScore());
                            }else{
                                templateItem.setCalculatedScore(BigDecimal.ZERO);
                            }*/
                            // 插入新记录
                            gxtMonthFanInspectionService.insertGxtMonthFanInspection(templateItem);
                            // 将新插入的记录添加到fanInspections列表，防止重复插入
                            fanInspections.add(templateItem);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 更新月度场站维修项目工单统计
     * @param monthScore 月度统计信息
     * @param order 工单对象
     */
    private void updateMonthRepairProject(GxtMonthScore monthScore, GxtRepairOrder order) {
        try {
            // 创建查询条件，查找与当前工单相关的维修项目统计
            GxtMonthRepairProject queryRepairProject = new GxtMonthRepairProject();
            queryRepairProject.setMonthScoreId(monthScore.getId());
            queryRepairProject.setDeptId(order.getPcsStationPid());
            queryRepairProject.setMaintenanceType(order.getMaintenanceType());
            queryRepairProject.setMonthPeriod(monthScore.getMonthPeriod());
            // 查询所有该月度统计下的维修项目统计记录
            List<GxtMonthRepairProject> repairProjects = gxtMonthRepairProjectService.selectGxtMonthRepairProjectList(queryRepairProject);

            GxtMonthRepairProject matchedRecord = null;
            
            if (repairProjects != null && !repairProjects.isEmpty()) {
                matchedRecord = repairProjects.get(0);
                // 如果存在记录，则更新工单数量和计算得分
                matchedRecord.setOrderCount(matchedRecord.getOrderCount() != null ? matchedRecord.getOrderCount() + 1 : 1);
                
                // 如果有项目分值，则重新计算得分
                if (matchedRecord.getProjectScore() != null) {
                    BigDecimal calculatedScore = matchedRecord.getProjectScore()
                        .multiply(new BigDecimal(matchedRecord.getOrderCount()));
                    matchedRecord.setCalculatedScore(calculatedScore);
                }
                matchedRecord.setUpdateBy(SecurityUtils.getUsername());
                matchedRecord.setUpdateTime(new Date());
                gxtMonthRepairProjectService.updateGxtMonthRepairProject(matchedRecord);
            } else {
                // 如果不存在记录，则通过selectGxtMonthRepairProjectListByAdd获取初始化数据后插入
                
                // 构造查询条件以从数据库获取待插入的数据
                GxtMonthRepairProject templateQuery = new GxtMonthRepairProject();
                templateQuery.setDeptId(order.getPcsStationPid());
                templateQuery.setMonthPeriod(monthScore.getMonthPeriod());
                
                // 使用selectGxtMonthRepairProjectListByAdd方法获取模板数据
                List<GxtMonthRepairProject> templateList = gxtMonthRepairProjectService.selectGxtMonthRepairProjectListByAdd(templateQuery);

                // 在templateList中查找与当前工单匹配的记录
                for (GxtMonthRepairProject templateItem : templateList) {
                    if (order.getMaintenanceType() != null && order.getMaintenanceType().equals(templateItem.getMaintenanceType())) {
                        SysDept dept = sysDeptMapper.selectDeptById(order.getPcsStationPid());
                        // 设置关联的月度统计ID和其他必要字段
                        templateItem.setMonthScoreId(monthScore.getId());
                        templateItem.setDeptId(order.getPcsStationPid());
                        templateItem.setDeptName(dept.getDeptName());
                        templateItem.setMonthPeriod(monthScore.getMonthPeriod());
                        templateItem.setCreateBy(SecurityUtils.getUsername());
                        templateItem.setCreateTime(new Date());
                        // 插入新记录
                        gxtMonthRepairProjectService.insertGxtMonthRepairProject(templateItem);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    /**
     * 更新用户评分统计(维修工单)
     * @param monthScore 月度统计信息
     * @param order 工单对象
     */
    private void updateUserScores(GxtMonthScore monthScore, GxtRepairOrder order) {
        try {
            // 获取参与该工单的所有人员
            List<GxtRepairOrderPerson> orderPersons = gxtRepairOrderService.selectRepairOrderPersonListByOrderId(order.getId());
            
            // 获取现有的用户评分统计列表
            GxtUserScore queryUserScore = new GxtUserScore();
            queryUserScore.setMonthScoreId(monthScore.getId());
            //queryUserScore.setMonthPeriod(monthScore.getMonthPeriod());
            List<GxtUserScore> userScores = gxtUserScoreService.selectGxtUserScoreList(queryUserScore);
            
            if (!orderPersons.isEmpty()) {
                // 遍历工单中的每个人员
                for (GxtRepairOrderPerson orderPerson : orderPersons) {
                    Long userId = orderPerson.getUserId();
                    SysUser sysUser = userMapper.selectUserById(userId);
                    boolean found = false;
                    // 在月度统计中查找该用户
                    if(userScores != null){
                        for (GxtUserScore userScore : userScores) {
                            // 使用userName进行匹配
                            if (sysUser != null && sysUser.getUserName() != null && sysUser.getUserName().equals(userScore.getUserName())) {
                                // 更新维修工单总分
                                // 从score中扣减runScore，避免重复计算
                                BigDecimal baseScore = (orderPerson.getScore() != null) ? orderPerson.getScore() : BigDecimal.ZERO;
                                BigDecimal runScore = (orderPerson.getRunScore() != null) ? 
                                        BigDecimal.valueOf(orderPerson.getRunScore()) : BigDecimal.ZERO;
                                BigDecimal stopScore = (orderPerson.getStopScore() != null) ?
                                        BigDecimal.valueOf(orderPerson.getStopScore()) : BigDecimal.ZERO;
                                BigDecimal repairScore = baseScore.subtract(runScore).subtract(stopScore);

                                BigDecimal currentRepairTotal = (userScore.getRepairTotalScore() != null) ?
                                        userScore.getRepairTotalScore() : BigDecimal.ZERO;

                                userScore.setRepairTotalScore(currentRepairTotal.add(repairScore));

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

                                BigDecimal finalScore = maintenanceScore.add(currentRepairTotal.add(repairScore));
                                userScore.setFinalScore(finalScore);
                                userScore.setUpdateBy(SecurityUtils.getUsername());
                                userScore.setUpdateTime(new Date());
                                gxtUserScoreService.updateGxtUserScore(userScore);
                                found = true;
                                break;
                            }
                        }
                    }

                    // 如果没找到用户记录，则创建新记录
                    if (!found) {
                        GxtUserScore newUserScore = new GxtUserScore();
                        newUserScore.setMonthScoreId(monthScore.getId());
                        newUserScore.setUserName(sysUser.getUserName());
                        newUserScore.setNickName(orderPerson.getNickName());
                        newUserScore.setMonthPeriod(monthScore.getMonthPeriod());
                        
                        // 设置维修工单得分
                        /*BigDecimal repairScore = (orderPerson.getScore() != null) ?
                                orderPerson.getScore() : BigDecimal.ZERO;*/
                        // 从score中扣减runScore，避免重复计算
                        BigDecimal baseScore = (orderPerson.getScore() != null) ? orderPerson.getScore() : BigDecimal.ZERO;
                        BigDecimal runScore = (orderPerson.getRunScore() != null) ?
                                BigDecimal.valueOf(orderPerson.getRunScore()) : BigDecimal.ZERO;
                        BigDecimal stopScore = (orderPerson.getStopScore() != null) ?
                                BigDecimal.valueOf(orderPerson.getStopScore()) : BigDecimal.ZERO;
                        BigDecimal repairScore = baseScore.subtract(runScore).subtract(stopScore);
                        newUserScore.setRepairTotalScore(repairScore);
                        
                        // 维保得分默认为0
                        newUserScore.setMaintenanceTotalScore(BigDecimal.ZERO);
                        newUserScore.setFinalScore(repairScore);
                        newUserScore.setStatus(0);
                        newUserScore.setCreateBy(SecurityUtils.getUsername());
                        newUserScore.setCreateTime(new Date());
                        // 插入新记录
                        gxtUserScoreService.insertGxtUserScore(newUserScore);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 更新用户评分统计(维保工单)
     * @param monthScore 月度统计信息
     * @param order 工单对象
     */
    private void updateUserScores(GxtMonthScore monthScore, GxtWorkOrder order) {
        try {
            // 获取参与该工单的所有人员
            List<GxtWorkOrderPerson> orderPersons = gxtWorkOrderService.selectWorkOrderPersonListByOrderId(order.getId());
            
            // 获取现有的用户评分统计列表
            GxtUserScore queryUserScore = new GxtUserScore();
            queryUserScore.setMonthScoreId(monthScore.getId());
            //queryUserScore.setMonthPeriod(monthScore.getMonthPeriod());
            List<GxtUserScore> userScores = gxtUserScoreService.selectGxtUserScoreList(queryUserScore);
            
            if (!orderPersons.isEmpty()) {
                // 遍历工单中的每个人员
                for (GxtWorkOrderPerson orderPerson : orderPersons) {
                    Long userId = orderPerson.getUserId();
                    SysUser sysUser = userMapper.selectUserById(userId);
                    boolean found = false;
                    // 在月度统计中查找该用户
                    if(userScores != null){
                        for (GxtUserScore userScore : userScores) {
                            // 使用userName进行匹配
                            if (sysUser != null && sysUser.getUserName() != null && sysUser.getUserName().equals(userScore.getUserName())) {
                                // 更新维保工单总分
                                // 从score中扣减runScore，避免重复计算
                                BigDecimal baseScore = (orderPerson.getScore() != null) ? orderPerson.getScore() : BigDecimal.ZERO;
                                BigDecimal runScore = (orderPerson.getRunScore() != null) ? 
                                        BigDecimal.valueOf(orderPerson.getRunScore()) : BigDecimal.ZERO;
                                BigDecimal stopScore = (orderPerson.getStopScore() != null) ?
                                        BigDecimal.valueOf(orderPerson.getStopScore()) : BigDecimal.ZERO;
                                BigDecimal maintenanceScore = baseScore.subtract(runScore).subtract(stopScore);

                                BigDecimal currentMaintenanceTotal = (userScore.getMaintenanceTotalScore() != null) ?
                                        userScore.getMaintenanceTotalScore() : BigDecimal.ZERO;

                                userScore.setMaintenanceTotalScore(currentMaintenanceTotal.add(maintenanceScore));

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

                                BigDecimal finalScore = repairScore.add(currentMaintenanceTotal.add(maintenanceScore));
                                userScore.setFinalScore(finalScore);
                                userScore.setUpdateBy(SecurityUtils.getUsername());
                                userScore.setUpdateTime(new Date());
                                gxtUserScoreService.updateGxtUserScore(userScore);
                                found = true;
                                break;
                            }
                        }
                    }

                    // 如果没找到用户记录，则创建新记录
                    if (!found) {
                        GxtUserScore newUserScore = new GxtUserScore();
                        newUserScore.setMonthScoreId(monthScore.getId());
                        newUserScore.setUserName(sysUser.getUserName());
                        newUserScore.setNickName(orderPerson.getNickName());
                        newUserScore.setMonthPeriod(monthScore.getMonthPeriod());
                        
                        // 设置维保工单得分
                        /*BigDecimal maintenanceScore = (orderPerson.getScore() != null) ?
                                orderPerson.getScore() : BigDecimal.ZERO;*/
                        // 从score中扣减runScore，避免重复计算
                        BigDecimal baseScore = (orderPerson.getScore() != null) ? orderPerson.getScore() : BigDecimal.ZERO;
                        BigDecimal runScore = (orderPerson.getRunScore() != null) ?
                                BigDecimal.valueOf(orderPerson.getRunScore()) : BigDecimal.ZERO;
                        BigDecimal stopScore = (orderPerson.getStopScore() != null) ?
                                BigDecimal.valueOf(orderPerson.getStopScore()) : BigDecimal.ZERO;
                        BigDecimal maintenanceScore = baseScore.subtract(runScore).subtract(stopScore);
                        newUserScore.setMaintenanceTotalScore(maintenanceScore);
                        
                        // 维修得分默认为0
                        newUserScore.setRepairTotalScore(BigDecimal.ZERO);
                        newUserScore.setFinalScore(maintenanceScore);
                        newUserScore.setStatus(0);
                        newUserScore.setCreateBy(SecurityUtils.getUsername());
                        newUserScore.setCreateTime(new Date());
                        // 插入新记录
                        gxtUserScoreService.insertGxtUserScore(newUserScore);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 更新月度统计数据（终评专用版本，仅更新用户得分）
     * @param orderScoreInfo 工单对象
     */
    private void updateMonthlyScoreDataForFinalEval(OrderScoreInfo orderScoreInfo) {
        try {
            if (orderScoreInfo.getOrderType() == 1) {
                // 维修工单
                GxtRepairOrder order = gxtRepairOrderService.selectGxtRepairOrderById(orderScoreInfo.getId());
                // 获取工单完成时间所在的月份
                if (order.getOccurTime() != null) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    String monthPeriod = sdf.format(order.getOccurTime());

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

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

                    if (monthScore != null) {
                        // 仅更新用户评分统计（基于reviewScore和finalScore的差值）
                        updateUserScoresForFinalEval(monthScore, order);
                    }
                }
            } else if (orderScoreInfo.getOrderType() == 2) {
                // 维保工单
                GxtWorkOrder order = gxtWorkOrderService.selectGxtWorkOrderById(orderScoreInfo.getId());
                // 获取工单完成时间所在的月份
                if (order.getCreateTime() != null) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    String monthPeriod = sdf.format(order.getCreateTime());

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

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

                    if (monthScore != null) {
                        // 仅更新用户评分统计（基于reviewScore和finalScore的差值）
                        updateUserScoresForFinalEval(monthScore, order);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新用户评分统计（终评专用版本，基于reviewScore和finalScore的差值）
     * @param monthScore 月度统计信息
     * @param order 工单对象
     */
    private void updateUserScoresForFinalEval(GxtMonthScore monthScore, GxtRepairOrder order) {
        try {
            // 获取参与该工单的所有人员（当前数据库中的最新数据）
            List<GxtRepairOrderPerson> orderPersons = gxtRepairOrderService.selectRepairOrderPersonListByOrderId(order.getId());
            
            // 获取现有的用户评分统计列表
            GxtUserScore queryUserScore = new GxtUserScore();
            queryUserScore.setMonthScoreId(monthScore.getId());
            //queryUserScore.setMonthPeriod(monthScore.getMonthPeriod());
            List<GxtUserScore> userScores = gxtUserScoreService.selectGxtUserScoreList(queryUserScore);
            
            if (!orderPersons.isEmpty()) {
                // 遍历工单中的每个人员
                for (GxtRepairOrderPerson orderPerson : orderPersons) {
                    // 计算差值：finalScore - reviewScore
                    Double reviewScore = orderPerson.getReviewScore() != null ? orderPerson.getReviewScore() : 0.0;
                    Double finalScore = orderPerson.getFinalScore() != null ? orderPerson.getFinalScore() : 0.0;
                    BigDecimal scoreDiff = new BigDecimal(String.valueOf(finalScore - reviewScore));

                    Long userId = orderPerson.getUserId();
                    SysUser sysUser = userMapper.selectUserById(userId);
                    boolean found = false;
                    // 在月度统计中查找该用户
                    if(userScores != null){
                        for (GxtUserScore userScore : userScores) {
                            // 使用userName进行匹配
                            if (sysUser != null && sysUser.getUserName() != null && sysUser.getUserName().equals(userScore.getUserName())) {
                                // 更新维修工单总分（应用差值）
                                BigDecimal currentRepairTotal = (userScore.getRepairTotalScore() != null) ?
                                        userScore.getRepairTotalScore() : BigDecimal.ZERO;

                                userScore.setRepairTotalScore(currentRepairTotal.add(scoreDiff));

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

                                BigDecimal finalScoreTotal = maintenanceScore.add(currentRepairTotal).add(scoreDiff);
                                userScore.setFinalScore(finalScoreTotal);
                                userScore.setUpdateBy(SecurityUtils.getUsername());
                                userScore.setUpdateTime(new Date());
                                gxtUserScoreService.updateGxtUserScore(userScore);
                                found = true;
                                break;
                            }
                        }
                    }
                    // 如果没找到用户记录，则创建新记录
                    /*if (!found) {
                        GxtUserScore newUserScore = new GxtUserScore();
                        newUserScore.setMonthScoreId(monthScore.getId());
                        newUserScore.setUserName(sysUser.getUserName());
                        newUserScore.setNickName(orderPerson.getNickName());
                        newUserScore.setMonthPeriod(monthScore.getMonthPeriod());

                        // 设置维修工单得分
                        BigDecimal repairScore = (orderPerson.getScore() != null) ?
                                orderPerson.getScore() : BigDecimal.ZERO;
                        newUserScore.setRepairTotalScore(repairScore);

                        // 维保得分默认为0
                        newUserScore.setMaintenanceTotalScore(BigDecimal.ZERO);
                        newUserScore.setFinalScore(repairScore);
                        newUserScore.setStatus(0);
                        newUserScore.setCreateBy(SecurityUtils.getUsername());
                        newUserScore.setCreateTime(new Date());
                        // 插入新记录
                        gxtUserScoreService.insertGxtUserScore(newUserScore);
                    }*/
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新用户评分统计（终评专用版本，基于reviewScore和finalScore的差值）- 维保工单版本
     * @param monthScore 月度统计信息
     * @param order 工单对象
     */
    private void updateUserScoresForFinalEval(GxtMonthScore monthScore, GxtWorkOrder order) {
        try {
            // 获取参与该工单的所有人员（当前数据库中的最新数据）
            List<GxtWorkOrderPerson> orderPersons = gxtWorkOrderService.selectWorkOrderPersonListByOrderId(order.getId());

            // 获取现有的用户评分统计列表
            GxtUserScore queryUserScore = new GxtUserScore();
            queryUserScore.setMonthScoreId(monthScore.getId());
            //queryUserScore.setMonthPeriod(monthScore.getMonthPeriod());
            List<GxtUserScore> userScores = gxtUserScoreService.selectGxtUserScoreList(queryUserScore);

            if (!orderPersons.isEmpty()) {
                // 遍历工单中的每个人员
                for (GxtWorkOrderPerson orderPerson : orderPersons) {
                    // 计算差值：finalScore - reviewScore
                    Double reviewScore = orderPerson.getReviewScore() != null ? orderPerson.getReviewScore() : 0.0;
                    Double finalScore = orderPerson.getFinalScore() != null ? orderPerson.getFinalScore() : 0.0;
                    BigDecimal scoreDiff = new BigDecimal(String.valueOf(finalScore - reviewScore));
                    Long userId = orderPerson.getUserId();
                    SysUser sysUser = userMapper.selectUserById(userId);
                    boolean found = false;
                    // 在月度统计中查找该用户
                    if(userScores != null){
                        for (GxtUserScore userScore : userScores) {
                            // 使用userName进行匹配
                            if (sysUser != null && sysUser.getUserName() != null && sysUser.getUserName().equals(userScore.getUserName())) {
                                // 更新用户得分（加上差值）
                                BigDecimal currentMaintenanceTotalScore = (userScore.getMaintenanceTotalScore() != null) ?
                                        userScore.getMaintenanceTotalScore() : BigDecimal.ZERO;

                                userScore.setMaintenanceTotalScore(currentMaintenanceTotalScore.add(scoreDiff));

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

                                BigDecimal finalScoreTotal = repairTotalScore.add(currentMaintenanceTotalScore).add(scoreDiff);
                                userScore.setFinalScore(finalScoreTotal);
                                userScore.setUpdateBy(SecurityUtils.getUsername());
                                userScore.setUpdateTime(new Date());
                                // 更新用户评分统计
                                gxtUserScoreService.updateGxtUserScore(userScore);
                                found = true;
                                break;
                            }
                        }
                    }
                    // 如果没找到用户记录，则创建新记录
                    /*if (!found) {
                        GxtUserScore newUserScore = new GxtUserScore();
                        newUserScore.setMonthScoreId(monthScore.getId());
                        newUserScore.setUserName(sysUser.getUserName());
                        newUserScore.setNickName(orderPerson.getNickName());
                        newUserScore.setMonthPeriod(monthScore.getMonthPeriod());

                        // 设置维保工单得分
                        BigDecimal maintenanceScore = (orderPerson.getScore() != null) ?
                                orderPerson.getScore() : BigDecimal.ZERO;
                        newUserScore.setMaintenanceTotalScore(maintenanceScore);

                        // 维修得分默认为0
                        newUserScore.setRepairTotalScore(BigDecimal.ZERO);
                        newUserScore.setFinalScore(maintenanceScore);
                        newUserScore.setStatus(0);
                        newUserScore.setCreateBy(SecurityUtils.getUsername());
                        newUserScore.setCreateTime(new Date());
                        // 插入新记录
                        gxtUserScoreService.insertGxtUserScore(newUserScore);
                    }*/
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存确认信息
     *
     * @param orderScoreInfo 工单评分信息
     * @return 结果
     */
    @Override
    @Transactional
    public int confirm(OrderScoreInfo orderScoreInfo) {
        try {
            if (orderScoreInfo.getOrderType() == 1) {
                // 维修工单确认
                GxtRepairOrder orderSearch = gxtRepairOrderService.selectGxtRepairOrderById(orderScoreInfo.getId());
                GxtRepairOrder order = new GxtRepairOrder();
                order.setId(orderScoreInfo.getId());
                order.setConfirmStatus(orderScoreInfo.getConfirmStatus());
                order.setFeedbackReason(orderScoreInfo.getFeedbackReason());
                order.setUpdateTime(new Date());
                order.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                // 更新工单信息
                int result = gxtRepairOrderService.updateGxtRepairOrderForScore(order);

                // 根据工作负责人的确认状态更新工单的评分状态
                if (orderScoreInfo.getConfirmStatus() != null) {
                    GxtRepairOrder statusOrder = new GxtRepairOrder();
                    statusOrder.setId(orderScoreInfo.getId());
                    
                    // 如果是确认状态
                    if (orderScoreInfo.getConfirmStatus() == 1) {
                        if (orderScoreInfo.getScorePersonList() != null) {
                            List<GxtRepairOrderPerson> personList = new ArrayList<>();
                            for (OrderScorePerson person : orderScoreInfo.getScorePersonList()) {
                                GxtRepairOrderPerson repairPerson = new GxtRepairOrderPerson();
                                repairPerson.setId(person.getId());
                                repairPerson.setScore(person.getReviewScore() != null ? BigDecimal.valueOf(person.getReviewScore()) : null);
                                personList.add(repairPerson);
                            }
                            gxtRepairOrderService.updateRepairOrderPersonList(personList);
                        }
                        if(orderSearch.getRestartTime() != null){
                            statusOrder.setScoringStatus("archived");
                            statusOrder.setWorkOrderStatus("archived");
                        }else{
                            statusOrder.setScoringStatus("to_archive");
                        }
                    } 
                    // 如果是反馈状态
                    else if (orderScoreInfo.getConfirmStatus() == 2) {
                        // 进入终评状态
                        statusOrder.setScoringStatus("to_final");
                    }
                    
                    gxtRepairOrderService.updateGxtRepairOrderForScore(statusOrder);

                    // 添加工单流转记录
                    GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
                    flow.setOrderId(orderScoreInfo.getId());
                    flow.setOrderCode(orderSearch.getWorkOrderProjectNo());
                    if (orderScoreInfo.getConfirmStatus() == 1) {
                        flow.setActionType("confirmRating");
                    }else if (orderScoreInfo.getConfirmStatus() == 2) {
                        flow.setActionType("feedbackRating");
                    }
                    flow.setFromStatus(orderSearch.getWorkOrderStatus());
                    flow.setToStatus(orderSearch.getWorkOrderStatus());
                    flow.setFromScoreStatus(orderSearch.getScoringStatus());
                    flow.setToScoreStatus(statusOrder.getScoringStatus());
                    flow.setOperatorId(SecurityUtils.getUserId());
                    flow.setOperatorName(SecurityUtils.getLoginUser().getUser().getNickName());
                    flow.setActionTime(DateUtils.getNowDate());
                    if (orderScoreInfo.getConfirmStatus() == 1) {
                        flow.setActionRemark("提交确认");
                    }else if (orderScoreInfo.getConfirmStatus() == 2) {
                        flow.setActionRemark("提交反馈");
                    }
                    repairOrderFlowService.insertGxtRepairOrderFlow(flow);

                    if("archived".equals(statusOrder.getWorkOrderStatus())){
                        // 添加归档流程记录
                        flow = new GxtRepairOrderFlow();
                        flow.setOrderId(orderSearch.getId());
                        flow.setOrderCode(orderSearch.getWorkOrderProjectNo());
                        flow.setActionType("archive");
                        flow.setFromStatus("to_archive");
                        flow.setToStatus("archived");
                        flow.setOperatorId(1L); // 系统自动操作，使用系统用户ID
                        flow.setOperatorName("系统自动");
                        flow.setActionTime(DateUtils.getNowDate());
                        flow.setActionRemark("系统自动归档工单");
                        repairOrderFlowService.insertGxtRepairOrderFlow(flow);
                    }
                }
                if (orderScoreInfo.getConfirmStatus() == 1) {
                    // 更新月度统计数据
                    updateMonthlyScoreData(orderScoreInfo);
                }
                return result;
            } else if (orderScoreInfo.getOrderType() == 2) {
                // 维保工单确认
                GxtWorkOrder oldOrder = gxtWorkOrderService.selectGxtWorkOrderById(orderScoreInfo.getId());
                GxtWorkOrder order = new GxtWorkOrder();
                order.setId(orderScoreInfo.getId());
                order.setConfirmStatus(orderScoreInfo.getConfirmStatus());
                order.setFeedbackReason(orderScoreInfo.getFeedbackReason());
                order.setUpdateTime(new Date());
                order.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                // 更新工单信息
                int result = gxtWorkOrderService.updateGxtWorkOrderForScore(order);

                // 根据工作负责人的确认状态更新工单的评分状态
                if (orderScoreInfo.getConfirmStatus() != null) {
                    GxtWorkOrder statusOrder = new GxtWorkOrder();
                    statusOrder.setId(orderScoreInfo.getId());
                    
                    // 如果是确认状态
                    if (orderScoreInfo.getConfirmStatus() == 1) {
                        // 进入终评状态
                        statusOrder.setScoringStatus("to_final");
                    } 
                    // 如果是反馈状态
                    else if (orderScoreInfo.getConfirmStatus() == 2) {
                        // 再次进入复评状态
                        statusOrder.setScoringStatus("to_re");
                    }
                    
                    gxtWorkOrderService.updateGxtWorkOrderForScore(statusOrder);

                    // 添加工单流转记录
                    GxtWorkOrderFlow flow = new GxtWorkOrderFlow();
                    flow.setOrderId(orderScoreInfo.getId());
                    flow.setOrderCode(oldOrder.getWorkOrderProjectNo());
                    if (orderScoreInfo.getConfirmStatus() == 1) {
                        flow.setActionType("confirmRating");
                    }else if (orderScoreInfo.getConfirmStatus() == 2) {
                        flow.setActionType("feedbackRating");
                    }
                    flow.setFromStatus(oldOrder.getWorkOrderStatus());
                    flow.setToStatus(oldOrder.getWorkOrderStatus());
                    flow.setFromScoreStatus(oldOrder.getScoringStatus());
                    flow.setToScoreStatus(statusOrder.getScoringStatus());
                    flow.setOperatorId(SecurityUtils.getUserId());
                    flow.setOperatorName(SecurityUtils.getLoginUser().getUser().getNickName());
                    flow.setActionTime(DateUtils.getNowDate());
                    if (orderScoreInfo.getConfirmStatus() == 1) {
                        flow.setActionRemark("提交确认");
                    }else if (orderScoreInfo.getConfirmStatus() == 2) {
                        flow.setActionRemark("提交反馈");
                    }
                    gxtWorkOrderFlowService.insertGxtWorkOrderFlow(flow);
                }
                return result;
            }
            return 0;
        } catch (Exception e) {
            throw new RuntimeException("保存确认信息失败：" + e.getMessage(), e);
        }
    }

    /**
     * 发起申诉
     *
     * @param orderScoreInfo 工单评分信息
     * @return 结果
     */
    @Override
    @Transactional
    public int appeal(OrderScoreInfo orderScoreInfo) {
        try {
            if (orderScoreInfo.getOrderType() == 1) {
                // 维修工单申诉
                GxtRepairOrder order = gxtRepairOrderService.selectGxtRepairOrderById(orderScoreInfo.getId());

                // 更新工单状态为申诉中
                GxtRepairOrder updateOrder = new GxtRepairOrder();
                updateOrder.setId(orderScoreInfo.getId());
                updateOrder.setConfirmStatus(3); // 使用confirmStatus字段标记为已申诉（值为3）
                updateOrder.setAppealReason(orderScoreInfo.getAppealReason());
                updateOrder.setScoringStatus("appealing"); // 申诉中状态
                updateOrder.setAppealUserId(SecurityUtils.getUserId());
                updateOrder.setAppealUserName(SecurityUtils.getLoginUser().getUser().getNickName());
                updateOrder.setAppealTime(DateUtils.getNowDate());
                updateOrder.setUpdateTime(new Date());
                updateOrder.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                int result = gxtRepairOrderService.updateGxtRepairOrderForScore(updateOrder);

                // 添加工单流转记录
                GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
                flow.setOrderId(orderScoreInfo.getId());
                flow.setOrderCode(order.getWorkOrderProjectNo());
                flow.setActionType("appealRating");
                flow.setFromStatus(order.getWorkOrderStatus());
                flow.setToStatus(order.getWorkOrderStatus());
                flow.setFromScoreStatus(order.getScoringStatus());
                flow.setToScoreStatus("appealing");
                flow.setOperatorId(SecurityUtils.getUserId());
                flow.setOperatorName(SecurityUtils.getLoginUser().getUser().getNickName());
                flow.setActionTime(DateUtils.getNowDate());
                flow.setActionRemark("发起申诉：" + orderScoreInfo.getAppealReason());
                repairOrderFlowService.insertGxtRepairOrderFlow(flow);

                Long gxtCenterId = order.getGxtCenterId();
                setRedisAppealNum(gxtCenterId);

                return result;
            } else if (orderScoreInfo.getOrderType() == 2) {
                // 维保工单申诉
                GxtWorkOrder order = gxtWorkOrderService.selectGxtWorkOrderById(orderScoreInfo.getId());

                // 更新工单状态为申诉中
                GxtWorkOrder updateOrder = new GxtWorkOrder();
                updateOrder.setId(orderScoreInfo.getId());
                updateOrder.setConfirmStatus(3); // 使用confirmStatus字段标记为已申诉（值为3）
                updateOrder.setAppealReason(orderScoreInfo.getAppealReason());
                updateOrder.setScoringStatus("appealing"); // 申诉中状态
                updateOrder.setAppealUserId(SecurityUtils.getUserId());
                updateOrder.setAppealUserName(SecurityUtils.getLoginUser().getUser().getNickName());
                updateOrder.setAppealTime(DateUtils.getNowDate());
                updateOrder.setUpdateTime(new Date());
                updateOrder.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                int result = gxtWorkOrderService.updateGxtWorkOrderForScore(updateOrder);

                // 添加工单流转记录
                GxtWorkOrderFlow flow = new GxtWorkOrderFlow();
                flow.setOrderId(orderScoreInfo.getId());
                flow.setOrderCode(order.getWorkOrderProjectNo());
                flow.setActionType("appealRating");
                flow.setFromStatus(order.getWorkOrderStatus());
                flow.setToStatus(order.getWorkOrderStatus());
                flow.setFromScoreStatus(order.getScoringStatus());
                flow.setToScoreStatus("appealing");
                flow.setOperatorId(SecurityUtils.getUserId());
                flow.setOperatorName(SecurityUtils.getLoginUser().getUser().getNickName());
                flow.setActionTime(DateUtils.getNowDate());
                flow.setActionRemark("发起申诉：" + orderScoreInfo.getAppealReason());
                gxtWorkOrderFlowService.insertGxtWorkOrderFlow(flow);

                Long gxtCenterId = order.getGxtCenterId();
                setRedisAppealNum(gxtCenterId);

                return result;
            }
            return 0;
        } catch (Exception e) {
            throw new RuntimeException("发起申诉失败：" + e.getMessage(), e);
        }
    }

    @Override
    public List<OrderScoreInfo> selectMobileUnionOrderList(GxtRepairOrder repairOrder, GxtWorkOrder workOrder, String keyword) {
        return selectMobileUnionOrderList(null, repairOrder, workOrder, keyword);
    }

    @Override
    public List<OrderScoreInfo> selectMobileUnionOrderList(Long userId, GxtRepairOrder repairOrder, GxtWorkOrder workOrder, String keyword) {
       String userName = "";
       if(userId != null){
           SysUser sysUser = userMapper.selectUserById(userId);
           userName = sysUser.getUserName();
           addBusinessDataScopeFilter(sysUser, repairOrder, workOrder);
       }else{
           addBusinessDataScopeFilter(repairOrder, workOrder);
           userName = SecurityUtils.getUsername();
       }
        // 添加业务特定的数据权限过滤
        // 设置创建人，用于数据权限过滤
        if(!Constants.SUPER_ADMIN.equals(userName)){
            if (repairOrder.getCreateBy() == null || repairOrder.getCreateBy().isEmpty()) {
                repairOrder.setCreateBy(userName);
            }
            if (workOrder.getCreateBy() == null || workOrder.getCreateBy().isEmpty()) {
                workOrder.setCreateBy(userName);
            }
            if (repairOrder.getParams().get("currentUser") == null) {
                repairOrder.getParams().put("currentUser", SecurityUtils.getUsername());
            }
            if (workOrder.getParams().get("currentUser") == null) {
                workOrder.getParams().put("currentUser", SecurityUtils.getUsername());
            }
        }
        // 查询工单列表
        return gxtOrderScoreMapper.selectMobileUnionOrderList(repairOrder, workOrder,keyword);
    }

    @Override
    public List<OrderScoreInfo> selectUnionExportOrderList(GxtRepairOrder repairOrder, GxtWorkOrder workOrder) {
        // 添加业务特定的数据权限过滤
        addBusinessDataScopeFilter(repairOrder, workOrder);

        // 设置创建人，用于数据权限过滤
        if(!Constants.SUPER_ADMIN.equals(SecurityUtils.getUsername())){
            if (repairOrder.getCreateBy() == null || repairOrder.getCreateBy().isEmpty()) {
                repairOrder.setCreateBy(SecurityUtils.getUsername());
            }

            if (workOrder.getCreateBy() == null || workOrder.getCreateBy().isEmpty()) {
                workOrder.setCreateBy(SecurityUtils.getUsername());
            }
        }
        // 查询工单列表
        List<OrderScoreInfo> orderList = gxtOrderScoreMapper.selectUnionExportOrderList(repairOrder, workOrder);
        return orderList;
    }

    private void addBusinessDataScopeFilter(SysUser currentUser, GxtRepairOrder repairOrder, GxtWorkOrder workOrder) {
        if (currentUser == null) {
            return;
        }
        // 如果是超级管理员，不过滤数据
        if (currentUser.isAdmin()) {
            return;
        }

        // 获取用户角色
        List<SysRole> roles = currentUser.getRoles();
        if (roles == null || roles.isEmpty()) {
            // 如果用户没有任何角色，则不返回任何数据
            String noDataCondition = " AND 1=0";
            workOrder.getParams().put("businessDataScope", noDataCondition);
            repairOrder.getParams().put("businessDataScope", noDataCondition);
            return;
        }

        // 检查是否有"全部数据"权限的角色
        boolean hasAllDataPermission = roles.stream()
                .anyMatch(role -> DataScopeAspect.DATA_SCOPE_ALL.equals(role.getDataScope()));

        // 如果有任何一个角色有全部数据权限，则不过滤数据范围
        if (!hasAllDataPermission) {
            // 构建业务特定的数据权限SQL
            StringBuilder orderBusinessSql = new StringBuilder();
            StringBuilder repairBusinessSql = new StringBuilder();

            // 遍历用户角色，根据角色的数据范围添加业务特定的权限控制
            for (SysRole role : roles) {
                String dataScope = role.getDataScope();

                // 自定义数据权限 - 根据角色的数据范围值来控制查询条件
                if (DataScopeAspect.DATA_SCOPE_CUSTOM.equals(dataScope)) {
                    // 获取具有自定义数据权限的角色ID列表
                    List<String> customRoleIds = new ArrayList<>();
                    for (SysRole r : roles) {
                        if (DataScopeAspect.DATA_SCOPE_CUSTOM.equals(r.getDataScope())) {
                            customRoleIds.add(String.valueOf(r.getRoleId()));
                        }
                    }

                    // 构建自定义数据权限查询条件
                    if (orderBusinessSql.length() > 0) {
                        orderBusinessSql.append(" OR ");
                    }
                    // 构建自定义数据权限查询条件
                    if (repairBusinessSql.length() > 0) {
                        repairBusinessSql.append(" OR ");
                    }

                    if (customRoleIds.size() > 1) {
                        // 多个自定义数据权限角色使用IN查询
                        orderBusinessSql.append("(t.pcs_station_pid IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append("))")
                                .append(" OR t.pcs_station_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append("))")
                                .append(" OR t.gxt_center_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append(")))");
                        repairBusinessSql.append("(t.pcs_station_pid IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append("))")
                                .append(" OR t.pcs_station_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append("))")
                                .append(" OR t.gxt_center_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append(")))");
                    } else {
                        // 单个自定义数据权限角色查询
                        orderBusinessSql.append("(t.pcs_station_pid IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append(")")
                                .append(" OR t.pcs_station_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append(")")
                                .append(" OR t.gxt_center_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append("))");
                        repairBusinessSql.append("(t.pcs_station_pid IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append(")")
                                .append(" OR t.pcs_station_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append(")")
                                .append(" OR t.gxt_center_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append("))");
                    }
                    continue;
                }

                // 部门数据权限 - 适用于部门负责人角色
                if (DataScopeAspect.DATA_SCOPE_DEPT.equals(dataScope)) {
                    if (orderBusinessSql.length() > 0) {
                        orderBusinessSql.append(" OR ");
                    }
                    if (repairBusinessSql.length() > 0) {
                        repairBusinessSql.append(" OR ");
                    }
                    orderBusinessSql.append("(t.pcs_station_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR t.pcs_station_pid = ")
                            .append(currentUser.getDeptId())
                            .append(" OR t.gxt_center_id = ")
                            .append(currentUser.getDeptId())
                            .append(")");
                    repairBusinessSql.append("(t.pcs_station_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR t.pcs_station_pid = ")
                            .append(currentUser.getDeptId())
                            .append(" OR t.gxt_center_id = ")
                            .append(currentUser.getDeptId())
                            .append(")");
                    continue;
                }

                // 部门及以下数据权限
                if (DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                    if (orderBusinessSql.length() > 0) {
                        orderBusinessSql.append(" OR ");
                    }
                    if (repairBusinessSql.length() > 0) {
                        repairBusinessSql.append(" OR ");
                    }
                    orderBusinessSql.append("(t.pcs_station_id IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors))")
                            .append(" OR t.pcs_station_pid IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors))")
                            .append(" OR t.gxt_center_id IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors)))");
                    repairBusinessSql.append("(t.pcs_station_id IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors))")
                            .append(" OR t.pcs_station_pid IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors))")
                            .append(" OR t.gxt_center_id IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors)))");
                    continue;
                }

                // 仅本人数据权限 - 适用于主检修员角色
                if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
                    if (orderBusinessSql.length() > 0) {
                        orderBusinessSql.append(" OR ");
                    }
                    if (repairBusinessSql.length() > 0) {
                        repairBusinessSql.append(" OR ");
                    }
                    orderBusinessSql.append("(t.team_leader_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.assign_user_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.accept_user_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.id IN (SELECT order_id FROM gxt_work_order_person WHERE user_id = ")
                            .append(currentUser.getUserId())
                            .append(") ")
                            .append(" OR t.create_by = '")
                            .append(currentUser.getUserName())
                            .append("')");
                    repairBusinessSql.append("(t.team_leader_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.assign_user_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.accept_user_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.id IN (SELECT order_id FROM gxt_repair_order_person WHERE user_id = ")
                            .append(currentUser.getUserId())
                            .append(") ")
                            .append(" OR t.create_by = '")
                            .append(currentUser.getUserName())
                            .append("')");
                    continue;
                }
            }
            String selfData = configService.selectConfigByKey("gxt.oder.selfData");
            if (StringUtils.isNotEmpty(selfData) && "1".equals(selfData)) {
                if (orderBusinessSql.length() > 0) {
                    orderBusinessSql.append(" OR ");
                }
                if (repairBusinessSql.length() > 0) {
                    repairBusinessSql.append(" OR ");
                }
                orderBusinessSql.append("(t.team_leader_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.assign_user_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.accept_user_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.id IN (SELECT order_id FROM gxt_work_order_person WHERE user_id = ")
                        .append(currentUser.getUserId())
                        .append(") ")
                        .append(" OR t.create_by = '")
                        .append(currentUser.getUserName())
                        .append("')");
                repairBusinessSql.append("(t.team_leader_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.assign_user_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.accept_user_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.id IN (SELECT order_id FROM gxt_repair_order_person WHERE user_id = ")
                        .append(currentUser.getUserId())
                        .append(") ")
                        .append(" OR t.create_by = '")
                        .append(currentUser.getUserName())
                        .append("')");
            }
            // 如果构建了业务特定的过滤条件，则添加到查询参数中
            if (orderBusinessSql.length() > 0) {
                String businessDataScopeSql = " AND (" + orderBusinessSql.toString() + ")";
                workOrder.getParams().put("businessDataScope", businessDataScopeSql);
            }
            if (repairBusinessSql.length() > 0) {
                String businessDataScopeSql = " AND (" + repairBusinessSql.toString() + ")";
                repairOrder.getParams().put("businessDataScope", businessDataScopeSql);
            }
        }
        
        // 对于已作废(work_order_status = 'invalid')的工单，只有admin用户才能查看
        if (!SecurityUtils.isAdmin(currentUser.getUserId())) {
            String invalidFilterSql = " AND (t.work_order_status != 'invalid')";
            if (workOrder.getParams().get("businessDataScope") != null) {
                String existingSql = workOrder.getParams().get("businessDataScope").toString();
                workOrder.getParams().put("businessDataScope", existingSql + invalidFilterSql);
            } else {
                workOrder.getParams().put("businessDataScope", invalidFilterSql);
            }
            if (repairOrder.getParams().get("businessDataScope") != null) {
                String existingSql = repairOrder.getParams().get("businessDataScope").toString();
                repairOrder.getParams().put("businessDataScope", existingSql + invalidFilterSql);
            } else {
                repairOrder.getParams().put("businessDataScope", invalidFilterSql);
            }
        }
    }

    /**
     * 添加业务特定的数据权限过滤条件
     * 基于角色的数据范围进行自定义权限控制
     *
     * @param repairOrder 维修工单查询条件
     * @param workOrder 维保工单查询条件
     */
    private void addBusinessDataScopeFilter(GxtRepairOrder repairOrder, GxtWorkOrder workOrder) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(loginUser == null){
            return;
        }
        addBusinessDataScopeFilter(loginUser.getUser(), repairOrder, workOrder);
    }

    @Transactional
    public int confirmV0(OrderScoreInfo orderScoreInfo) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = SecurityUtils.getUserId();

            if (orderScoreInfo.getOrderType() == 1) {
                // 维修工单确认
                GxtRepairOrder order = new GxtRepairOrder();
                order.setId(orderScoreInfo.getId());

                // 更新工单信息
                int result = gxtRepairOrderService.updateGxtRepairOrderForScore(order);

                // 只更新当前登录用户的确认状态和反馈理由
                if (orderScoreInfo.getScorePersonList() != null) {
                    List<GxtRepairOrderPerson> personList = new ArrayList<>();
                    for (OrderScorePerson person : orderScoreInfo.getScorePersonList()) {
                        // 只更新当前登录用户的数据
                        if (person.getUserId() != null && person.getUserId().equals(currentUserId)) {
                            GxtRepairOrderPerson repairPerson = new GxtRepairOrderPerson();
                            repairPerson.setId(person.getId());
                            repairPerson.setConfirmStatus(person.getConfirmStatus());
                            repairPerson.setFeedbackReason(person.getFeedbackReason());
                            personList.add(repairPerson);
                            break; // 找到当前用户后直接退出循环
                        }
                    }
                    if (!personList.isEmpty()) {
                        gxtRepairOrderService.updateRepairOrderPersonList(personList);
                    }
                }

                // 根据所有用户的确认状态更新工单的评分状态
                List<GxtRepairOrderPerson> allPersons = gxtRepairOrderService.selectRepairOrderPersonListByOrderId(orderScoreInfo.getId());
                String scoringStatus = determineScoringStatus(allPersons);
                if (scoringStatus != null) {
                    GxtRepairOrder statusOrder = new GxtRepairOrder();
                    statusOrder.setId(orderScoreInfo.getId());
                    statusOrder.setScoringStatus(scoringStatus);
                    gxtRepairOrderService.updateGxtRepairOrderForScore(statusOrder);
                }

                return result;
            } else if (orderScoreInfo.getOrderType() == 2) {
                // 维保工单确认
                GxtWorkOrder order = new GxtWorkOrder();
                order.setId(orderScoreInfo.getId());

                // 更新工单信息
                int result = gxtWorkOrderService.updateGxtWorkOrderForScore(order);

                // 只更新当前登录用户的确认状态和反馈理由
                if (orderScoreInfo.getScorePersonList() != null) {
                    List<GxtWorkOrderPerson> personList = new ArrayList<>();
                    for (OrderScorePerson person : orderScoreInfo.getScorePersonList()) {
                        // 只更新当前登录用户的数据
                        if (person.getUserId() != null && person.getUserId().equals(currentUserId)) {
                            GxtWorkOrderPerson workPerson = new GxtWorkOrderPerson();
                            workPerson.setId(person.getId());
                            workPerson.setConfirmStatus(person.getConfirmStatus());
                            workPerson.setFeedbackReason(person.getFeedbackReason());
                            personList.add(workPerson);
                            break; // 找到当前用户后直接退出循环
                        }
                    }
                    if (!personList.isEmpty()) {
                        gxtWorkOrderService.updateWorkOrderPersonList(personList);
                    }
                }

                // 根据所有用户的确认状态更新工单的评分状态
                List<GxtWorkOrderPerson> allPersons = gxtWorkOrderService.selectWorkOrderPersonListByOrderId(orderScoreInfo.getId());
                String scoringStatus = determineScoringStatus(allPersons);
                if (scoringStatus != null) {
                    GxtWorkOrder statusOrder = new GxtWorkOrder();
                    statusOrder.setId(orderScoreInfo.getId());
                    statusOrder.setScoringStatus(scoringStatus);
                    gxtWorkOrderService.updateGxtWorkOrderForScore(statusOrder);
                }

                return result;
            }
            return 0;
        } catch (Exception e) {
            throw new RuntimeException("保存确认信息失败：" + e.getMessage(), e);
        }
    }

    /**
     * 根据所有用户的确认状态确定工单的评分状态
     *
     * @param persons 所有工单参与人员
     * @return 评分状态
     */
    private String determineScoringStatus(List<? extends Object> persons) {
        if (persons == null || persons.isEmpty()) {
            return null;
        }

        boolean allConfirmed = true;  // 所有用户都已确认
        boolean hasFeedback = false;  // 存在反馈的用户
        int validUserCount = 0;       // 有效用户数量（userId不为空的用户）

        for (Object obj : persons) {
            Long userId = null;
            Integer confirmStatus = null;

            if (obj instanceof GxtRepairOrderPerson) {
                userId = ((GxtRepairOrderPerson) obj).getUserId();
                confirmStatus = ((GxtRepairOrderPerson) obj).getConfirmStatus();
            } else if (obj instanceof GxtWorkOrderPerson) {
                userId = ((GxtWorkOrderPerson) obj).getUserId();
                confirmStatus = ((GxtWorkOrderPerson) obj).getConfirmStatus();
            }

            // 如果userId为空，则不计入统计
            if (userId == null) {
                continue;
            }

            // 增加有效用户计数
            validUserCount++;

            // 如果有任何用户的确认状态为空或为0（未确认），则不是全部确认
            if (confirmStatus == null || confirmStatus == 0) {
                allConfirmed = false;
            }
            // 如果有任何用户的确认状态为2（已反馈），则标记存在反馈
            else if (confirmStatus == 2) {
                hasFeedback = true;
            }
        }

        // 如果没有有效用户，保持当前状态不变
        if (validUserCount == 0) {
            return null;
        }

        // 如果所有用户都已确认
        if (allConfirmed) {
            // 如果存在反馈，则状态改为待复评
            if (hasFeedback) {
                return "to_re";
            }
            // 否则状态改为待终评
            else {
                return "to_final";
            }
        }
        // 如果不是所有用户都已确认，保持当前状态不变
        return null;
    }

    /**
     * 根据月份筛选工单列表
     *
     * @param orderList 工单列表
     * @param month 月份（格式：yyyy-MM）
     * @return 筛选后的工单列表
     */
    private List<OrderScoreInfo> filterOrdersByMonth(List<OrderScoreInfo> orderList, String month) {
        if (orderList == null || orderList.isEmpty() || month == null || month.isEmpty()) {
            return orderList;
        }

        List<OrderScoreInfo> filteredOrders = new ArrayList<>();
        for (OrderScoreInfo order : orderList) {
            // 检查工单的完成时间是否在指定月份
            boolean matchMonth = false;
            if (order.getOrderType() == 1) { // 维修工单
                if (order.getRealEndTime() != null) {
                    String orderMonth = new java.text.SimpleDateFormat("yyyy-MM").format(order.getRealEndTime());
                    matchMonth = month.equals(orderMonth);
                }
            } else if (order.getOrderType() == 2) { // 维保工单
                if (order.getRealEndTime() != null) {
                    String orderMonth = new java.text.SimpleDateFormat("yyyy-MM").format(order.getRealEndTime());
                    matchMonth = month.equals(orderMonth);
                }
            }

            if (matchMonth) {
                filteredOrders.add(order);
            }
        }

        return filteredOrders;
    }

    private void setRedisAppealNum(Long deptId) {
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(deptId);
        List<SysUser> users = userMapper.selectUserList(sysUser);

        // 过滤出属于目标部门且具有指定权限的用户
        List<SysUser> targetUsers = users.stream()
                .filter(user -> {
                    // 检查用户是否具有"gxt:orderScore:finalEvaluation"权限
                    Set<String> userPermissions = permissionService.getMenuPermission(user);
                    return SecurityUtils.hasPermi(userPermissions, "gxt:orderScore:finalEvaluation");
                })
                .collect(Collectors.toList());

        GxtRepairOrder gxtRepairOrder = new GxtRepairOrder();
        gxtRepairOrder.setGxtCenterId(deptId);
        gxtRepairOrder.setScoringStatus("appealing");
        List<GxtRepairOrder> repairOrders = gxtRepairOrderMapper.selectGxtRepairOrderList(gxtRepairOrder);
        // 过滤掉状态为"invalid"的工单
        repairOrders = repairOrders.stream()
                .filter(order -> !"invalid".equals(order.getWorkOrderStatus()))
                .collect(Collectors.toList());
        
        GxtWorkOrder gxtWorkOrder = new GxtWorkOrder();
        gxtWorkOrder.setGxtCenterId(deptId);
        gxtWorkOrder.setScoringStatus("appealing");
        List<GxtWorkOrder> workOrders = gxtWorkOrderMapper.selectGxtWorkOrderList(gxtWorkOrder);
        // 过滤掉状态为"invalid"的工单
        workOrders = workOrders.stream()
                .filter(order -> !"invalid".equals(order.getWorkOrderStatus()))
                .collect(Collectors.toList());

        // 循环这些用户，更新他们的待申诉数量
        for (SysUser user : targetUsers) {
            Long userId = user.getUserId();
            int taskNum = 0;
            if (repairOrders != null && !repairOrders.isEmpty()) {
                taskNum = taskNum + repairOrders.size() ;
            }
            if (workOrders != null && !workOrders.isEmpty()) {
                taskNum = taskNum + workOrders.size() ;
            }
            if(taskNum > 0){
                redisCache.lPush(CacheConstants.NOTIFY_STORAGE_APPEAL_KEY, userId, taskNum + "");
                redisCache.lPush(CacheConstants.NOTIFY_STORAGE_APPEAL_NOW, userId, taskNum + "");
            }
        }
    }
    
    /**
     * 添加工单个人分数明细数据
     * 将工单个人分数明细保存到GxtOrderScoreDetail表
     * 
     * @param orderScoreInfo 工单评分信息
     */
    private void addOrderScoreDetails(OrderScoreInfo orderScoreInfo) {
        try {
            Date realEndTime = new Date();
            if (orderScoreInfo.getOrderType() == 1) {
                // 维修工单
                GxtRepairOrder order = gxtRepairOrderService.selectGxtRepairOrderById(orderScoreInfo.getId());
                // 获取工单完成时间所在的月份
                if (order.getRealEndTime() != null) {
                    realEndTime = order.getRealEndTime();
                }
            }else if (orderScoreInfo.getOrderType() == 2) {
                // 维保工单
                GxtWorkOrder order = gxtWorkOrderService.selectGxtWorkOrderById(orderScoreInfo.getId());
                // 获取工单完成时间所在的月份
                if (order.getRealEndTime() != null) {
                    realEndTime = order.getRealEndTime();
                }
            }
            if (orderScoreInfo.getScorePersonList() != null && !orderScoreInfo.getScorePersonList().isEmpty()) {
                for (OrderScorePerson person : orderScoreInfo.getScorePersonList()) {
                    GxtOrderScoreDetail detail = new GxtOrderScoreDetail();
                    
                    // 设置基础信息
                    detail.setUserId(person.getUserId());
                    detail.setNickName(person.getNickName());
                    detail.setOrderType(orderScoreInfo.getOrderType());
                    
                    // 设置工单相关信息
                    detail.setOrderId(orderScoreInfo.getId());
                    detail.setOrderCode(orderScoreInfo.getWorkOrderProjectNo());
                    // 设置分数类型和分数（这里可以根据实际需要调整）
                    detail.setScoreType(1); // 工单得分
                    
                    // 设置具体分数（工单得分）
                    if (person.getTotalScore() != null) {
                        detail.setScore(BigDecimal.valueOf(person.getTotalScore()));
                        detail.setRateScore(BigDecimal.valueOf(person.getTotalScore()));
                    }
                    detail.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                    //detail.setCreateTime(new Date());
                    detail.setCreateTime(realEndTime);
                    // 保存到数据库
                    gxtOrderScoreDetailService.insertGxtOrderScoreDetail(detail);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取工单评分统计信息V0
     *
     * @param repairOrder 维修工单查询条件
     * @param workOrder 维保工单查询条件
     * @param month 月份筛选条件
     * @return 统计信息
     */
    public Map<String, Object> getOrderScoreStatisticsV0(GxtRepairOrder repairOrder, GxtWorkOrder workOrder, String month) {
        // 添加业务特定的数据权限过滤
        addBusinessDataScopeFilter(repairOrder, workOrder);

        // 设置创建人，用于数据权限过滤
        if(!Constants.SUPER_ADMIN.equals(SecurityUtils.getUsername())){
            if (repairOrder.getCreateBy() == null || repairOrder.getCreateBy().isEmpty()) {
                repairOrder.setCreateBy(SecurityUtils.getUsername());
            }

            if (workOrder.getCreateBy() == null || workOrder.getCreateBy().isEmpty()) {
                workOrder.setCreateBy(SecurityUtils.getUsername());
            }
        }

        Map<String, Object> result = new HashMap<>();
        Long currentUserId = SecurityUtils.getUserId();
        if(currentUserId != null){
            // 添加用户ID参数用于Mapper查询
            repairOrder.getParams().put("currentUserId", currentUserId);
            workOrder.getParams().put("currentUserId", currentUserId);

            Map<String, Object> statistics = gxtOrderScoreMapper.selectOrderScoreStatistics(repairOrder, workOrder, month);

            // 计算总工分
            Object maintenanceScoreObj = statistics.get("maintenanceScore");
            Object repairScoreObj = statistics.get("repairScore");

            double maintenanceScore = maintenanceScoreObj != null ? ((Number) maintenanceScoreObj).doubleValue() : 0.0;
            double repairScore = repairScoreObj != null ? ((Number) repairScoreObj).doubleValue() : 0.0;
            double totalScore = maintenanceScore + repairScore;

            result.put("totalScore", totalScore);
            result.put("maintenanceScore", maintenanceScore);
            result.put("repairScore", repairScore);
            result.put("maintenanceCount", statistics.get("maintenanceCount"));
            result.put("repairCount", statistics.get("repairCount"));
        }
        return result;
        /*// 如果用户的数据权限是"仅本人数据"，则只统计本人的工分
        if (isCurrentUserDataScopeSelf()) {
            Long currentUserId = SecurityUtils.getUserId();
            if (currentUserId != null) {
                // 添加用户ID参数用于Mapper查询
                repairOrder.getParams().put("currentUserId", currentUserId);
                workOrder.getParams().put("currentUserId", currentUserId);

                // 直接使用Mapper查询，避免加载大量数据到内存
                Map<String, Object> statistics = gxtOrderScoreMapper.selectOrderScoreStatistics(repairOrder, workOrder, month);

                // 计算总工分
                Object maintenanceScoreObj = statistics.get("maintenanceScore");
                Object repairScoreObj = statistics.get("repairScore");

                double maintenanceScore = maintenanceScoreObj != null ? ((Number) maintenanceScoreObj).doubleValue() : 0.0;
                double repairScore = repairScoreObj != null ? ((Number) repairScoreObj).doubleValue() : 0.0;
                double totalScore = maintenanceScore + repairScore;

                result.put("totalScore", totalScore);
                result.put("maintenanceScore", maintenanceScore);
                result.put("repairScore", repairScore);
                result.put("maintenanceCount", statistics.get("maintenanceCount"));
                result.put("repairCount", statistics.get("repairCount"));

                // 计算排名
                int rank = calculateUserRankInStation(repairOrder, workOrder, month);
                result.put("rank", rank);

                // 计算场站总人数
                LoginUser loginUser = SecurityUtils.getLoginUser();
                if (loginUser != null && loginUser.getUser() != null) {
                    Long deptId = loginUser.getUser().getDeptId();
                    if (deptId != null) {
                        List<Long> stationUserIds = getStationUserIds(deptId);
                        // 确保至少包含当前用户
                        if (stationUserIds.isEmpty() && currentUserId != null) {
                            stationUserIds = new ArrayList<>();
                            stationUserIds.add(currentUserId);
                        }
                        result.put("totalRankingUsers", stationUserIds.size());
                    } else {
                        // 如果没有部门信息，至少当前用户参与排名
                        result.put("totalRankingUsers", 1);
                    }
                } else {
                    // 如果无法获取用户信息，至少当前用户参与排名
                    result.put("totalRankingUsers", 1);
                }

                return result;
            }
        }

        // 获取统计信息（非"仅本人数据"权限用户或其他情况）
        Map<String, Object> statistics = gxtOrderScoreMapper.selectOrderScoreStatistics(repairOrder, workOrder, month);
        result.putAll(statistics);

        // 计算总工分
        Object maintenanceScoreObj = statistics.get("maintenanceScore");
        Object repairScoreObj = statistics.get("repairScore");

        double maintenanceScore = maintenanceScoreObj != null ? ((Number) maintenanceScoreObj).doubleValue() : 0.0;
        double repairScore = repairScoreObj != null ? ((Number) repairScoreObj).doubleValue() : 0.0;
        double totalScore = maintenanceScore + repairScore;

        result.put("totalScore", totalScore);
        result.put("maintenanceScore", maintenanceScore);
        result.put("repairScore", repairScore);

        return result;*/
    }
}