package com.ygtx.gxt.service.impl;

import com.ygtx.common.constant.Constants;
import com.ygtx.common.core.domain.entity.SysRole;
import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.framework.aspectj.DataScopeAspect;
import com.ygtx.framework.web.service.SysPermissionService;
import com.ygtx.gxt.domain.*;
import com.ygtx.gxt.mapper.GxtOrderMineMapper;
import com.ygtx.gxt.mapper.GxtOrderScoreMapper;
import com.ygtx.gxt.service.IGxtOrderMineService;
import com.ygtx.gxt.service.IGxtOrderScoreService;
import com.ygtx.gxt.service.IGxtRepairOrderService;
import com.ygtx.gxt.service.IGxtWorkOrderService;
import com.ygtx.system.mapper.SysUserMapper;
import com.ygtx.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 我的工单Service业务层处理
 *
 * @author ouyj
 * @date 2025-11-27
 */
@Service
public class GxtOrderMineServiceImpl implements IGxtOrderMineService {

    @Autowired
    private GxtOrderMineMapper gxtOrderMineMapper;
    
    @Autowired
    private IGxtRepairOrderService gxtRepairOrderService;
    
    @Autowired
    private IGxtWorkOrderService gxtWorkOrderService;
    
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 查询我创建的工单列表（维修工单和维保工单）
     *
     * @param repairOrder 维修工单查询条件
     * @param workOrder 维保工单查询条件
     * @return 合并的工单列表
     */
    @Override
    public List<OrderScoreInfo> selectUnionOrderListMyCreate(GxtRepairOrder repairOrder, GxtWorkOrder workOrder) {
        if (repairOrder.getCreateBy() == null || repairOrder.getCreateBy().isEmpty()) {
            repairOrder.setCreateBy(SecurityUtils.getUsername());
        }

        if (workOrder.getCreateBy() == null || workOrder.getCreateBy().isEmpty()) {
            workOrder.setCreateBy(SecurityUtils.getUsername());
        }
        
        // 对于已作废(work_order_status = 'invalid')的工单，只有admin用户才能查看
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null && loginUser.getUser() != null && !loginUser.getUser().isAdmin()) {
            String invalidFilterSql = " AND (t.work_order_status != 'invalid')";
            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);
            }
            
            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);
            }
        }
        
        // 查询工单列表
        List<OrderScoreInfo> orderList = gxtOrderMineMapper.selectUnionOrderList(repairOrder, workOrder);

        return orderList;
    }

    @Override
    public List<OrderScoreInfo> selectUnionOrderListMyDone(GxtRepairOrder repairOrder, GxtWorkOrder workOrder) {
        //添加处理人员过滤，GxtRepairOrder从对应的GxtRepairOrderFlow取operatorId即是对应的处理人员，
        // GxtWorkOrder从对应的GxtWorkOrderFlow取operatorId即是对应的处理人员，
        // 只要能对应当前登录用户，就查询出来，
        Long currentUserId = SecurityUtils.getUserId();

        // 构建维修工单的处理人员过滤条件
        StringBuilder repairFilterSql = new StringBuilder();
        repairFilterSql.append(" AND (EXISTS(SELECT 1 FROM gxt_repair_order_flow f WHERE f.order_id = t.id AND f.operator_id = ")
                .append(currentUserId)
                .append("))");
        repairOrder.getParams().put("businessDataScope", repairFilterSql.toString());

        // 构建维保工单的处理人员过滤条件
        StringBuilder workFilterSql = new StringBuilder();
        workFilterSql.append(" AND (EXISTS(SELECT 1 FROM gxt_work_order_flow f WHERE f.order_id = t.id AND f.operator_id = ")
                .append(currentUserId)
                .append("))");
        workOrder.getParams().put("businessDataScope", workFilterSql.toString());

        // 对于已作废(work_order_status = 'invalid')的工单，只有admin用户才能查看
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null && loginUser.getUser() != null && !loginUser.getUser().isAdmin()) {
            String invalidFilterSql = " AND (t.work_order_status != 'invalid')";
            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);
            }

            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);
            }
        }

        // 查询工单列表
        List<OrderScoreInfo> orderList = gxtOrderMineMapper.selectUnionOrderList(repairOrder, workOrder);

        return orderList;
    }

    @Override
    public List<OrderScoreInfo> selectUnionOrderListMyRelate(GxtRepairOrder repairOrder, GxtWorkOrder workOrder) {
        //添加处理人员过滤，GxtRepairOrder从对应的GxtRepairOrderPerson取userId即是对应的相关人员，
        // GxtWorkOrder从对应的GxtWorkOrderPerson取userId即是对应的相关人员，
        // 只要能对应当前登录用户，就查询出来，
        Long currentUserId = SecurityUtils.getUserId();

        // 构建维修工单的处理人员过滤条件
        StringBuilder repairFilterSql = new StringBuilder();
        repairFilterSql.append(" AND (EXISTS(SELECT 1 FROM gxt_repair_order_person p WHERE p.order_id = t.id AND p.user_id = ")
                .append(currentUserId)
                .append("))");
        repairOrder.getParams().put("businessDataScope", repairFilterSql.toString());

        // 构建维保工单的处理人员过滤条件
        StringBuilder workFilterSql = new StringBuilder();
        workFilterSql.append(" AND (EXISTS(SELECT 1 FROM gxt_work_order_person p WHERE p.order_id = t.id AND p.user_id = ")
                .append(currentUserId)
                .append("))");
        workOrder.getParams().put("businessDataScope", workFilterSql.toString());

        // 对于已作废(work_order_status = 'invalid')的工单，只有admin用户才能查看
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null && loginUser.getUser() != null && !loginUser.getUser().isAdmin()) {
            String invalidFilterSql = " AND (t.work_order_status != 'invalid')";
            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);
            }

            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);
            }
        }

        // 查询工单列表
        List<OrderScoreInfo> orderList = gxtOrderMineMapper.selectUnionOrderList(repairOrder, workOrder);

        return orderList;
    }

    @Override
    public List<OrderScoreInfo> selectUnionOrderListMyTodo(GxtRepairOrder repairOrder, GxtWorkOrder workOrder, Long userId) {
        // 添加业务特定的数据权限过滤
        addBusinessDataScopeFilter(repairOrder, workOrder, userId);
        
        // 根据用户权限和工单状态进行过滤数据
        // repairOrder只能查询workOrderStatus为assigned、to_finish、to_approve、completed、to_issue、accept_return状态的数据
        // workOrder只能查询workOrderStatus为assigned、processing、to_finish、to_approve、completed、to_issue状态的数据

        //Long currentUserId = userId != null ? userId : SecurityUtils.getUserId();
        Long currentUserId = userId;
        
        // 构建维修工单的权限和状态过滤条件
        StringBuilder repairFilterSql = new StringBuilder();
        repairFilterSql.append(" AND (");
        boolean hasConditions = false;
        
        // assigned状态且有接单权限
        if (hasPermi(userId, "gxt:repairOrder:accept")) {
            repairFilterSql.append("t.work_order_status = 'assigned'");
            hasConditions = true;
        }
        
        // to_finish状态且有结单权限且是工作负责人
        if (hasPermi(userId, "gxt:repairOrder:finalize")) {
            if (hasConditions) repairFilterSql.append(" OR ");
            //repairFilterSql.append("(t.work_order_status = 'to_finish' AND t.team_leader_id = ").append(currentUserId != null ? currentUserId : SecurityUtils.getUserId()).append(")");
            repairFilterSql.append("t.work_order_status = 'to_finish'");
            hasConditions = true;
        }
        
        // to_approve状态且有审批权限
        if (hasPermi(userId, "gxt:repairOrder:approve")) {
            if (hasConditions) repairFilterSql.append(" OR ");
            repairFilterSql.append("t.work_order_status = 'to_approve'");
            hasConditions = true;
        }

        /*// completed状态且有复运权限
        if (hasPermi(userId, "gxt:repairOrder:restart")) {
            if (hasConditions) repairFilterSql.append(" OR ");
            repairFilterSql.append("t.work_order_status = 'completed' and t.restart_time is null ");
            hasConditions = true;
        }*/
        
        // 有复运权限，且未复运过，且不是to_issue、auto_suspend或accept_return状态
        if (hasPermi(userId, "gxt:repairOrder:restart")) {
            if (hasConditions) repairFilterSql.append(" OR ");
            repairFilterSql.append("(t.restart_time is null and t.work_order_status != 'to_issue' and t.work_order_status != 'auto_suspend' and t.work_order_status != 'accept_return')");
            hasConditions = true;
        }
        
        // to_issue、accept_return状态且有编辑权限，且当前用户是创建人本部门的人
        if (hasPermi(userId, "gxt:repairOrder:edit")) {
            if (hasConditions) repairFilterSql.append(" OR ");
            //repairFilterSql.append("t.work_order_status IN ('to_issue', 'accept_return') ");
            repairFilterSql.append("(t.work_order_status IN ('to_issue', 'accept_return') AND EXISTS (SELECT 1 FROM sys_user u, sys_dept d WHERE u.del_flag='0' and u.user_name = t.create_by AND u.dept_id = d.dept_id AND (d.dept_id = ")
                    .append(getDeptId(currentUserId))
                    .append(" OR FIND_IN_SET(")
                    .append(getDeptId(currentUserId))
                    .append(", d.ancestors))))");
            hasConditions = true;
        }

        // 有复启权限
        if (hasPermi(userId, "gxt:repairOrder:resetStart")) {
            if (hasConditions) repairFilterSql.append(" OR ");
            //repairFilterSql.append("t.work_order_status != 'to_issue' and t.work_order_status != 'completed' and t.work_order_status != 'archived' and t.work_order_status != 'invalid' and t.work_order_status != 'accept_return'");
            repairFilterSql.append("(t.work_order_status = 'to_finish' or t.work_order_status = 'assigned')");
            hasConditions = true;
        }

        // 如果没有任何权限，则不返回任何数据
        if (!hasConditions) {
            repairFilterSql = new StringBuilder();
            repairFilterSql.append(" AND 1=0"); // 永远为false的条件，确保不返回任何数据
        } else {
            repairFilterSql.append(")");
        }
        
        repairOrder.getParams().put("todoStatusFilter", repairFilterSql.toString());

        // 构建维保工单的权限和状态过滤条件
        StringBuilder workFilterSql = new StringBuilder();
        workFilterSql.append(" AND (");
        hasConditions = false;
        
        // assigned状态且有接单权限
        if (hasPermi(userId, "gxt:maintenance:order:accept")) {
            workFilterSql.append("t.work_order_status = 'assigned'");
            hasConditions = true;
        }
        
        // processing或to_finish状态且有结单权限且是工作负责人
        if (hasPermi(userId, "gxt:maintenance:order:complete")) {
            if (hasConditions) workFilterSql.append(" OR ");
            //workFilterSql.append("(t.work_order_status IN ('processing', 'to_finish') AND t.team_leader_id = ").append(currentUserId != null ? currentUserId : SecurityUtils.getUserId()).append(")");
            workFilterSql.append("t.work_order_status IN ('processing', 'to_finish')");
            hasConditions = true;
        }
        
        // to_approve状态且有审批权限
        if (hasPermi(userId, "gxt:maintenance:order:approve")) {
            if (hasConditions) workFilterSql.append(" OR ");
            workFilterSql.append("t.work_order_status = 'to_approve'");
            hasConditions = true;
        }

        /*// completed状态且有复运权限
        if (hasPermi(userId, "gxt:maintenance:order:restart")) {
            if (hasConditions) workFilterSql.append(" OR ");
            workFilterSql.append("t.work_order_status = 'completed' and t.restart_time is null");
            hasConditions = true;
        }*/
        
        // 有复运权限，且未复运过，且不是to_issue或auto_suspend状态
        if (hasPermi(userId, "gxt:maintenance:order:restart")) {
            if (hasConditions) workFilterSql.append(" OR ");
            workFilterSql.append("(t.restart_time is null and t.work_order_status != 'to_issue' and t.work_order_status != 'auto_suspend')");
            hasConditions = true;
        }

        // to_issue状态且有编辑权限
        if (hasPermi(userId, "gxt:maintenance:order:edit")) {
            if (hasConditions) workFilterSql.append(" OR ");
            workFilterSql.append("t.work_order_status = 'to_issue' ");
            hasConditions = true;
        }
        
        // 停机权限，且未停机过，且不在某些特定状态
        if (hasPermi(userId, "gxt:maintenance:order:shutdown")) {
            if (hasConditions) workFilterSql.append(" OR ");
            workFilterSql.append("(t.pause_time is null and t.work_order_status != 'to_issue' and t.work_order_status != 'auto_suspend' and t.work_order_status != 'completed' and t.work_order_status != 'archived' and t.work_order_status != 'invalid')");
            hasConditions = true;
        }
        
        // 如果没有任何权限，则不返回任何数据
        if (!hasConditions) {
            workFilterSql = new StringBuilder();
            workFilterSql.append(" AND 1=0"); // 永远为false的条件，确保不返回任何数据
        } else {
            workFilterSql.append(")");
        }
        
        workOrder.getParams().put("todoStatusFilter", workFilterSql.toString());

        // 查询工单列表
        List<OrderScoreInfo> orderList = gxtOrderMineMapper.selectUnionOrderList(repairOrder, workOrder);

        return orderList;
    }

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

        // 根据用户权限和工单状态进行过滤数据
        // repairOrder只能查询scoringStatus为to_self、to_re、to_approve、to_final 状态的数据
        // workOrder只能查询scoringStatus为to_self、to_re、to_approve、to_final状态的数据

        Long currentUserId = SecurityUtils.getUserId();

        // 构建维修工单的权限和状态过滤条件
        StringBuilder repairFilterSql = new StringBuilder();
        repairFilterSql.append(" AND (");
        boolean hasConditions = false;

        // to_self状态且有自评权限且是（工作负责人或者超级管理员角色）
        if (SecurityUtils.hasPermi("gxt:orderScore:selfEvaluation")) {
            repairFilterSql.append("(t.scoring_status = 'to_self' AND (t.team_leader_id = ")
                    .append(currentUserId)
                    .append(" OR ")
                    .append(SecurityUtils.getUserId())
                    .append(" IN (SELECT user_id FROM sys_user WHERE user_name = 'admin')))");
            hasConditions = true;
        }

        // to_re状态且有复评权限且是工作负责人
        if (SecurityUtils.hasPermi("gxt:orderScore:review")) {
            if (hasConditions) repairFilterSql.append(" OR ");
            repairFilterSql.append("t.scoring_status = 'to_re'");
            hasConditions = true;
        }

        // to_final状态且有终评权限
        if (SecurityUtils.hasPermi("gxt:orderScore:finalEvaluation")) {
            if (hasConditions) repairFilterSql.append(" OR ");
            repairFilterSql.append("t.scoring_status = 'to_final'");
            hasConditions = true;
        }

        // 如果没有任何权限，则不返回任何数据
        if (!hasConditions) {
            repairFilterSql = new StringBuilder();
            repairFilterSql.append(" AND 1=0"); // 永远为false的条件，确保不返回任何数据
        } else {
            repairFilterSql.append(")");
        }

        repairOrder.getParams().put("scoreStatusFilter", repairFilterSql.toString());

        // 构建维保工单的权限和状态过滤条件
        StringBuilder workFilterSql = new StringBuilder();
        workFilterSql.append(" AND (");
        hasConditions = false;

        // to_self状态且有自评权限且是（工作负责人或者超级管理员角色）
        if (SecurityUtils.hasPermi("gxt:orderScore:selfEvaluation")) {
            workFilterSql.append("(t.scoring_status = 'to_self' AND (t.team_leader_id = ")
                    .append(currentUserId)
                    .append(" OR ")
                    .append(SecurityUtils.getUserId())
                    .append(" IN (SELECT user_id FROM sys_user WHERE user_name = 'admin')))");
            hasConditions = true;
        }

        // to_re状态且有复评权限
        if (SecurityUtils.hasPermi("gxt:orderScore:review")) {
            if (hasConditions) workFilterSql.append(" OR ");
            workFilterSql.append("t.scoring_status = 'to_re'");
            hasConditions = true;
        }

        // to_final状态且有终评权限
        if (SecurityUtils.hasPermi("gxt:orderScore:finalEvaluation")) {
            if (hasConditions) workFilterSql.append(" OR ");
            workFilterSql.append("t.scoring_status = 'to_final'");
            hasConditions = true;
        }

        // 如果没有任何权限，则不返回任何数据
        if (!hasConditions) {
            workFilterSql = new StringBuilder();
            workFilterSql.append(" AND 1=0"); // 永远为false的条件，确保不返回任何数据
        } else {
            workFilterSql.append(")");
        }

        workOrder.getParams().put("scoreStatusFilter", workFilterSql.toString());

        // 查询工单列表
        List<OrderScoreInfo> orderList = gxtOrderMineMapper.selectUnionOrderList(repairOrder, workOrder);

        return orderList;
    }

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

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

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

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

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

        // 构建业务特定的数据权限SQL
        StringBuilder orderBusinessSql = new StringBuilder();
        StringBuilder repairBusinessSql = new StringBuilder();

        // 如果有任何一个角色有全部数据权限，则不过滤数据范围
        if (!hasAllDataPermission) {
            // 遍历用户角色，根据角色的数据范围添加业务特定的权限控制
            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 (!currentUser.isAdmin()) {
            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);
            }
        }
    }

    private LoginUser getLoginUser(Long userId) {
        if (userId != null) {
            // 根据用户ID获取用户信息
            SysUser user = userMapper.selectUserById(userId);
            /*if (user != null) {
                LoginUser loginUser = new LoginUser();
                loginUser.setUser(user);
                return loginUser;
            }*/
            Set<String> permissions = permissionService.getMenuPermission(user);
            LoginUser loginUser = new LoginUser(user,permissions);
            return loginUser;
        }
        // 获取当前登录用户
        return SecurityUtils.getLoginUser();
    }

    /**
     * 判断用户是否为管理员
     *
     * @param userId 用户ID
     * @return 是否为管理员
     */
    private boolean isAdmin(Long userId) {
        if (userId != null) {
            SysUser user = userMapper.selectUserById(userId);
            return user != null && user.isAdmin();
        }
        return SecurityUtils.isAdmin(userId);
    }

    /**
     * 获取用户部门ID
     *
     * @param userId 用户ID（可选）
     * @return 部门ID
     */
    private Long getDeptId(Long userId) {
        if (userId != null) {
            SysUser user = userMapper.selectUserById(userId);
            if (user != null) {
                return user.getDeptId();
            }
        }
        return SecurityUtils.getDeptId();
    }

    /**
     * 检查用户是否有指定权限
     * 
     * @param userId 用户ID（可选）
     * @param permission 权限字符串
     * @return 是否有权限
     */
    private boolean hasPermi(Long userId, String permission) {
        if (userId != null) {
            // 根据用户ID获取用户信息和权限
            SysUser user = userMapper.selectUserById(userId);
            if (user != null) {
                Set<String> permissions = permissionService.getMenuPermission(user);
                return SecurityUtils.hasPermi(permissions, permission);
            }
            return false;
        }
        // 使用当前登录用户的权限检查
        return SecurityUtils.hasPermi(permission);
    }
}