package com.ygtx.gxt.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import com.github.pagehelper.util.StringUtil;
import com.ygtx.common.constant.Constants;
import com.ygtx.common.constant.UserConstants;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.core.page.PageDomain;
import com.ygtx.common.exception.ServiceException;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.common.utils.DictUtils;
import com.ygtx.common.core.domain.entity.SysDept;
import com.ygtx.framework.aspectj.DataScopeAspect;
import com.ygtx.gxt.domain.*;
import com.ygtx.gxt.mapper.GxtEquipmentMapper;
import com.ygtx.gxt.mapper.GxtOrderPersonMapper;
import com.ygtx.gxt.service.IGxtUserOperatorHistoryService;
import com.ygtx.system.domain.SysPost;
import com.ygtx.system.domain.SysPostHomePage;
import com.ygtx.system.service.*;
import com.ygtx.gxt.mapper.GxtRepairOrderPersonMapper;
import com.ygtx.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.ygtx.gxt.mapper.GxtRepairOrderMapper;
import com.ygtx.gxt.service.IGxtRepairOrderService;
import com.ygtx.gxt.service.IGxtRepairOrderFlowService;
import com.ygtx.common.annotation.DataScope;
import com.ygtx.common.core.domain.entity.SysRole;
import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;

/**
 * 维修工单Service业务层处理
 *
 * @author ouyj
 * @date 2025-10-30
 */
@Service
public class GxtRepairOrderServiceImpl implements IGxtRepairOrderService
{
    @Autowired
    private GxtRepairOrderMapper gxtRepairOrderMapper;

    @Autowired
    private IGxtRepairOrderFlowService gxtRepairOrderFlowService;

    @Autowired
    private GxtRepairOrderPersonMapper gxtRepairOrderPersonMapper;

    @Autowired
    private IGxtUserOperatorHistoryService gxtUserOperatorHistoryService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysPostService sysPostService;

    @Autowired
    private ISysPostHomePageService sysPostHomePageService;

    @Autowired
    private GxtEquipmentMapper gxtEquipmentMapper;

    @Autowired
    @Qualifier("sourceDataSource")
    private DataSource sourceDataSource;

    @Autowired
    private GxtOrderPersonMapper orderPersonMapper;

    /**
     * 查询维修工单
     *
     * @param id 维修工单主键
     * @return 维修工单
     */
    @Override
    public GxtRepairOrder selectGxtRepairOrderById(Long id)
    {
        GxtRepairOrder order = gxtRepairOrderMapper.selectGxtRepairOrderById(id);
        if (order != null) {
            // 查询工单流转记录
            GxtRepairOrderFlow flowQuery = new GxtRepairOrderFlow();
            flowQuery.setOrderId(id);
            List<GxtRepairOrderFlow> flowList = gxtRepairOrderFlowService.selectGxtRepairOrderFlowList(flowQuery);
            order.setRepairOrderFlowList(flowList);
            GxtRepairOrderPerson repairOrderPerson = new GxtRepairOrderPerson();
            repairOrderPerson.setOrderId(id);
            List<GxtRepairOrderPerson> repairOrderPersonList = gxtRepairOrderPersonMapper.selectGxtRepairOrderPersonList(repairOrderPerson);
            order.setRepairOrderPersonList(repairOrderPersonList);
        }
        return order;
    }

    /**
     * 查询维修工单列表
     *
     * @param gxtRepairOrder 维修工单
     * @return 维修工单
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<GxtRepairOrder> selectGxtRepairOrderList(GxtRepairOrder gxtRepairOrder)
    {
        // 添加业务特定的数据权限过滤
        addBusinessDataScopeFilter(gxtRepairOrder);

        updateParam(gxtRepairOrder);

        if(!Constants.SUPER_ADMIN.equals(SecurityUtils.getUsername())){
            // 确保设置了当前用户的用户名，用于待下发工单的权限过滤
            if (gxtRepairOrder.getParams().get("currentUser") == null) {
                gxtRepairOrder.getParams().put("currentUser", SecurityUtils.getUsername());
            }
        }

        return gxtRepairOrderMapper.selectGxtRepairOrderList(gxtRepairOrder);
    }

    private void updateParam(GxtRepairOrder gxtRepairOrder) {
        if (StringUtil.isNotEmpty(gxtRepairOrder.getHomePageParam())) {
            StringBuilder params = new StringBuilder();
            if ("toBe".equals(gxtRepairOrder.getHomePageParam())) {
                String level = SecurityUtils.getLoginUser().getUser().getDept().getLevel();
                if ("3".equals(level)) {
                    gxtRepairOrder.setPcsStationPid(SecurityUtils.getDeptId());
                }
                if ("2".equals(level)) {
                    gxtRepairOrder.setGxtCenterId(SecurityUtils.getDeptId());
                }
                List<String> status = new ArrayList<>();
                if (SecurityUtils.hasPermi("gxt:repairOrder:assign")) {
                    status.add("to_issue");
                }
                if (SecurityUtils.hasPermi("gxt:repairOrder:accept")) {
                    status.add("assigned");
                }
                if (SecurityUtils.hasPermi("gxt:repairOrder:complete")) {
                    status.add("to_finish");
                }
                if (SecurityUtils.hasPermi("gxt:repairOrder:approve")) {
                    status.add("to_approve");
                }

                // 构建IN查询条件
                if (!status.isEmpty()) {
                    params = new StringBuilder(" AND t.work_order_status IN (");
                    for (String si : status) {
                        params.append("'").append(si).append("',");
                    }
                    params.deleteCharAt(params.length() - 1);
                    params.append(")");
                }
            } else if ("toStart".equals(gxtRepairOrder.getHomePageParam())) {
                gxtRepairOrder.setAssignUserId(SecurityUtils.getUserId());
            } else if ("toHandle".equals(gxtRepairOrder.getHomePageParam())) {
                params = new StringBuilder(" AND t.id IN (SELECT order_id FROM gxt_repair_order_flow WHERE operator_id=");
                params.append(SecurityUtils.getUserId());
                params.append(" GROUP BY order_id)");
            } else if ("toRelated".equals(gxtRepairOrder.getHomePageParam())) {
                params = new StringBuilder(" AND t.id IN (SELECT order_id FROM gxt_repair_order_person WHERE user_id=");
                params.append(SecurityUtils.getUserId());
                params.append(" GROUP BY order_id)");
            }
            // 如果构建了业务特定的过滤条件，则添加到查询参数中
            if (params.length()>0) {
                if (gxtRepairOrder.getParams().get("businessDataScope")!=null) {
                    String businessDataScopeSql = gxtRepairOrder.getParams().get("businessDataScope").toString();
                    gxtRepairOrder.getParams().put("businessDataScope", businessDataScopeSql + params.toString());
                } else {
                    gxtRepairOrder.getParams().put("businessDataScope", params.toString());
                }
            }
        }
    }

    /**
     * 新增维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        // 根据pcsStationId获取部门id,设值给pcsStationPid
        if (gxtRepairOrder.getPcsStationId() != null) {
            SysDept dept = getDeptInfoAndParent(gxtRepairOrder.getPcsStationId());
            if (dept != null && "3".equals(dept.getLevel())) {
                gxtRepairOrder.setPcsStationPid(dept.getDeptId());
            }else{
                gxtRepairOrder.setPcsStationPid(gxtRepairOrder.getPcsStationId());
            }
        }

        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        if("assigned".equals(gxtRepairOrder.getWorkOrderStatus())){
            gxtRepairOrder.setAssignTime(DateUtils.getNowDate());
            gxtRepairOrder.setAssignUserId(SecurityUtils.getUserId());
            gxtRepairOrder.setAssignUserName(nickName);
        }
        gxtRepairOrder.setOrderType(1L);
        gxtRepairOrder.setCreateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setCreateTime(DateUtils.getNowDate());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.insertGxtRepairOrder(gxtRepairOrder);

        // 记录工单创建流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            if("to_issue".equals(gxtRepairOrder.getWorkOrderStatus())){
                flow.setActionType("create");
            }else if("assigned".equals(gxtRepairOrder.getWorkOrderStatus())){
                flow.setActionType("create_to_assign");
            }
            flow.setFromStatus(null);
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            if("to_issue".equals(gxtRepairOrder.getWorkOrderStatus())){
                flow.setActionRemark("创建维修工单");
            }else if("assigned".equals(gxtRepairOrder.getWorkOrderStatus())){
                flow.setActionRemark("创建并下发维修工单");
            }
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);

            if("assigned".equals(gxtRepairOrder.getWorkOrderStatus())) {
                // 自动挂起时间
                String suspendTime = configService.selectConfigByKey("gxt.autoSuspend.time");
                String suspendEndTime = configService.selectConfigByKey("gxt.autoSuspend.endTime");
                if (StringUtils.isNotEmpty(suspendTime)) {
                    // 1. 将字符串解析为 LocalTime
                    LocalTime startTime = LocalTime.parse(suspendTime, DateTimeFormatter.ofPattern("H:mm:ss"));
                    LocalTime endTime = LocalTime.parse(suspendEndTime, DateTimeFormatter.ofPattern("H:mm:ss"));

                    // 2. 获取当前时间（仅时分秒，不含日期）
                    LocalTime now = LocalTime.now();
                    // 当前时间晚于挂起时间
                    if (now.isAfter(startTime) || now.isBefore(endTime)) {
                        gxtRepairOrder.setWorkOrderStatus("auto_suspend");
                        gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);
                        flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
                        flow.setActionType("auto_suspend");
                        flow.setFromStatus("assigned");
                        flow.setToStatus("auto_suspend");
                        flow.setOperatorId(1L);
                        flow.setOperatorName("系统");
                        flow.setActionTime(DateUtils.getNowDate());
                        flow.setCreateBy("admin");
                        flow.setCreateTime(DateUtils.getNowDate());
                        gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
                    }
                }
            }
        }

        return result;
    }

    /**
     * 修改维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int updateGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        // 根据pcsStationId获取部门id,设值给pcsStationPid
        if (gxtRepairOrder.getPcsStationId() != null) {
            SysDept dept = getDeptInfoAndParent(gxtRepairOrder.getPcsStationId());
            if (dept != null && "3".equals(dept.getLevel())) {
                gxtRepairOrder.setPcsStationPid(dept.getDeptId());
            }else{
                gxtRepairOrder.setPcsStationPid(gxtRepairOrder.getPcsStationId());
            }
        }

        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        if("assigned".equals(gxtRepairOrder.getWorkOrderStatus())){
            gxtRepairOrder.setAssignTime(DateUtils.getNowDate());
            gxtRepairOrder.setAssignUserId(SecurityUtils.getUserId());
            gxtRepairOrder.setAssignUserName(nickName);
        }
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 如果工单状态发生变化，记录流转信息
        if (result > 0 && oldOrder != null &&
            !oldOrder.getWorkOrderStatus().equals(gxtRepairOrder.getWorkOrderStatus())) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            if("assigned".equals(gxtRepairOrder.getWorkOrderStatus())){
                flow.setActionType("assign");
            }
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            if("assigned".equals(gxtRepairOrder.getWorkOrderStatus())){
                flow.setActionRemark("下发维修工单");
            }
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);

            if("assigned".equals(gxtRepairOrder.getWorkOrderStatus())) {
                // 自动挂起时间
                String suspendTime = configService.selectConfigByKey("gxt.autoSuspend.time");
                String suspendEndTime = configService.selectConfigByKey("gxt.autoSuspend.endTime");
                if (StringUtils.isNotEmpty(suspendTime)) {
                    // 1. 将字符串解析为 LocalTime
                    LocalTime startTime = LocalTime.parse(suspendTime, DateTimeFormatter.ofPattern("H:mm:ss"));
                    LocalTime endTime = LocalTime.parse(suspendEndTime, DateTimeFormatter.ofPattern("H:mm:ss"));

                    // 2. 获取当前时间（仅时分秒，不含日期）
                    LocalTime now = LocalTime.now();
                    // 当前时间晚于挂起时间
                    if (now.isAfter(startTime) || now.isBefore(endTime)) {
                        gxtRepairOrder.setWorkOrderStatus("auto_suspend");
                        gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);
                        flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
                        flow.setActionType("auto_suspend");
                        flow.setFromStatus("assigned");
                        flow.setToStatus("auto_suspend");
                        flow.setOperatorId(1L);
                        flow.setOperatorName("系统");
                        flow.setActionTime(DateUtils.getNowDate());
                        flow.setCreateBy("admin");
                        flow.setCreateTime(DateUtils.getNowDate());
                        gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
                    }
                }
            }
        }
        return result;
    }

    /**
     * 撤回维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int revokeGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录撤回流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(oldOrder.getId());
            flow.setOrderCode(oldOrder.getWorkOrderProjectNo());
            flow.setActionType("revoke");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("撤回工单");
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }

        return result;
    }

    /**
     * 作废维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int invalidateGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        gxtRepairOrder.setWorkOrderStatus("invalid");
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录作废流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(oldOrder.getId());
            flow.setOrderCode(oldOrder.getWorkOrderProjectNo());
            flow.setActionType("invalid");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("作废工单，原因：" + gxtRepairOrder.getInvalidReason());
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }

        return result;
    }

    /**
     * 递归获取部门信息，查找父部门直到level为3
     * @param deptId 部门ID
     * @return 返回level为3的部门对象
     */
    private SysDept getDeptInfoAndParent(Long deptId) {
        SysDept dept = sysDeptService.selectDeptById(deptId);
        // 如果部门level为3，直接返回
        if (dept != null && "3".equals(dept.getLevel())) {
            return dept;
        }
        // 如果有祖先部门，则继续向上查找
        else if (dept != null && StringUtils.isNotEmpty(dept.getAncestors())) {
            // 从ancestors中提取父部门ID
            // ancestors格式类似 "0,100,101,102"
            String[] ancestorIds = dept.getAncestors().split(",");
            if (ancestorIds.length > 1){
                Long parentDeptId = Long.valueOf(ancestorIds[ancestorIds.length - 1]);
                // 递归获取父部门信息
                return getDeptInfoAndParent(parentDeptId);
            } else {
                return dept;
            }
        }
        // 其他情况也直接返回
        else {
            return dept;
        }
    }

    /**
     * 批量删除维修工单
     *
     * @param ids 需要删除的维修工单主键
     * @return 结果
     */
    @Override
    public int deleteGxtRepairOrderByIds(Long[] ids)
    {
        return gxtRepairOrderMapper.deleteGxtRepairOrderByIds(ids);
    }

    /**
     * 删除维修工单信息
     *
     * @param id 维修工单主键
     * @return 结果
     */
    @Override
    public int deleteGxtRepairOrderById(Long id)
    {
        return gxtRepairOrderMapper.deleteGxtRepairOrderById(id);
    }

    /**
     * 派单维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int assignGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        gxtRepairOrder.setWorkOrderStatus("assigned");
        gxtRepairOrder.setAssignTime(DateUtils.getNowDate());
        gxtRepairOrder.setAssignUserId(SecurityUtils.getUserId());
        gxtRepairOrder.setAssignUserName(nickName);
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录派单流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            flow.setActionType("assign");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("下发维修工单");
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }

        return result;
    }

    /**
     * 接单维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int acceptGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        //gxtRepairOrder.setWorkOrderStatus("accepted");
        //gxtRepairOrder.setWorkOrderStatus("processing");
        gxtRepairOrder.setWorkOrderStatus("to_finish");
        gxtRepairOrder.setAcceptTime(DateUtils.getNowDate());
        gxtRepairOrder.setAcceptUserId(SecurityUtils.getUserId());
        gxtRepairOrder.setAcceptUserName(nickName);
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        /*String memberNames = null;
        if(gxtRepairOrder.getRepairOrderPersonList() != null && !gxtRepairOrder.getRepairOrderPersonList().isEmpty()){
            memberNames = gxtRepairOrder.getRepairOrderPersonList().stream()
                    .map(GxtRepairOrderPerson::getNickName)
                    .collect(java.util.stream.Collectors.joining(","));
            gxtRepairOrder.setWorkGroupMemberName(memberNames);
        } else {
            memberNames = "无";
        }*/
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);
        // 记录接单流转信息
        if (result > 0) {
            if (null != gxtRepairOrder.getTeamLeaderId()) {
                // 工作负责人存入工单工作组员名单
                GxtRepairOrderPerson person = new GxtRepairOrderPerson();
                person.setIsLeader(1);
                person.setUserId(gxtRepairOrder.getTeamLeaderId());
                person.setNickName(gxtRepairOrder.getTeamLeaderName());
                person.setOrderId(oldOrder.getId());
                person.setOrderCode(oldOrder.getWorkOrderProjectNo());
                person.setStatus(1);
                person.setCreateBy(SecurityUtils.getUsername());
                person.setCreateTime(DateUtils.getNowDate());
                gxtRepairOrderPersonMapper.insertGxtRepairOrderPerson(person);

                gxtUserOperatorHistoryService.insertHistoryRepairOrder(UserConstants.OP_TYPE_LEADER, gxtRepairOrder);
            }

            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            //flow.setActionType("accept");
            flow.setActionType("process");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("开始处理维修工单，负责人：" + gxtRepairOrder.getTeamLeaderName());
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }

        return result;
    }

    /**
     * 开始维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int startGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        /*if(oldOrder.getRealStartTime() != null){
            gxtRepairOrder.setRealStartTime(DateUtils.getNowDate());
        }*/
        //gxtRepairOrder.setWorkOrderStatus("processing");
        gxtRepairOrder.setWorkOrderStatus("to_finish");
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录开始流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            flow.setActionType("process");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("开始处理维修工单");
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }

        return result;
    }

    /**
     * 暂停维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int pauseGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录暂停流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            flow.setActionType("pause");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("暂停处理维修工单");
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }

        return result;
    }

    /**
     * 恢复维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int resumeGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录恢复流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(oldOrder.getId());
            flow.setOrderCode(oldOrder.getWorkOrderProjectNo());
            flow.setActionType("resume");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("恢复处理工单");
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }

        return result;
    }

    /**
     * 维修处理完成（进入待结单状态）
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int processDoneGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        gxtRepairOrder.setWorkOrderStatus("to_be_finalized");
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录处理完成流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            flow.setActionType("处理完成");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus("to_be_finalized");
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("维修处理完成，等待结单");
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }

        return result;
    }

    /**
     * 评分维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int ratingGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        if (gxtRepairOrder.getRestartTime() != null) {
            gxtRepairOrder.setWorkOrderStatus("to_archive");
        }
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录评分流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            flow.setActionType("rating");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("对维修工单进行评分。分数："+gxtRepairOrder.getScore());
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
            if (gxtRepairOrder.getRestartTime() != null) {
                GxtRepairOrderFlow flowArchive = new GxtRepairOrderFlow();
                flowArchive.setOrderId(gxtRepairOrder.getId());
                flowArchive.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
                flowArchive.setActionType("to_archive");
                flowArchive.setFromStatus(oldOrder.getWorkOrderStatus());
                flowArchive.setToStatus(gxtRepairOrder.getWorkOrderStatus());
                flowArchive.setOperatorId(SecurityUtils.getUserId());
                flowArchive.setOperatorName(nickName);
                flowArchive.setActionTime(DateUtils.getNowDate());
                flowArchive.setActionRemark("工单待归档");
                gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flowArchive);
            }
        }

        return result;
    }

    /**
     * 挂起维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int suspendGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        gxtRepairOrder.setWorkOrderStatus("to_approve");
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        // 负责人为空
        if (null == gxtRepairOrder.getTeamLeaderName() && StringUtils.isEmpty(gxtRepairOrder.getTeamLeaderName())) {
            gxtRepairOrder.setTeamLeaderId(SecurityUtils.getUserId());
            gxtRepairOrder.setTeamLeaderName(SecurityUtils.getLoginUser().getUser().getNickName());
            GxtRepairOrderPerson person = new GxtRepairOrderPerson();
            person.setUserId(SecurityUtils.getUserId());
            person.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
            person.setIsLeader(1);
            person.setOrderId(gxtRepairOrder.getId());
            person.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            person.setStatus(1);
            person.setCreateBy(SecurityUtils.getUsername());
            gxtRepairOrderPersonMapper.insertGxtRepairOrderPerson(person);
        }

        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录挂起流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            flow.setActionType("to_approve");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            // 修改为从数据字典获取挂起原因的标签
            String suspendReasonLabel = DictUtils.getDictLabel("gxt_order_suspend_reason", gxtRepairOrder.getSuspendReason());
            flow.setActionRemark("申请挂起维修工单。挂起原因: " + suspendReasonLabel);
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }

        return result;
    }

    /**
     * 审批挂起维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int approveSuspendGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        if ("approved".equals(gxtRepairOrder.getApprovalStatus())) {
            gxtRepairOrder.setWorkOrderStatus("suspended");
        }else if ("rejected".equals(gxtRepairOrder.getApprovalStatus())) {
            //gxtRepairOrder.setWorkOrderStatus("processing");
            gxtRepairOrder.setWorkOrderStatus("to_finish");
        }
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录审批流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            // 根据审批结果设置操作类型
            String actionType = "";
            if ("approved".equals(gxtRepairOrder.getApprovalStatus())) {
                actionType = "approved";
            }else if ("rejected".equals(gxtRepairOrder.getApprovalStatus())) {
                actionType = "rejected";
            }
            flow.setActionType(actionType);
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            String actionRemark = "审批挂起申请";
            if ("approved".equals(gxtRepairOrder.getApprovalStatus())) {
                actionRemark = "挂起申请审批通过";
            }else if ("rejected".equals(gxtRepairOrder.getApprovalStatus())) {
                actionRemark = "挂起申请被驳回。审批意见："+gxtRepairOrder.getRejectionReason();
            }
            flow.setActionRemark(actionRemark);
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }

        return result;
    }

    /**
     * 正式结单（完结工单）
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int finalizeGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        /*String memberNames = null;
        if(gxtRepairOrder.getRepairOrderPersonList() != null && !gxtRepairOrder.getRepairOrderPersonList().isEmpty()){
            memberNames = gxtRepairOrder.getRepairOrderPersonList().stream()
                    .map(GxtRepairOrderPerson::getNickName)
                    .collect(java.util.stream.Collectors.joining(","));
            gxtRepairOrder.setWorkGroupMemberName(memberNames);
        } else {
            memberNames = "无";
        }*/
        // 结单：仅有待结单的工单才能结单
        if (!"to_finish".equals(oldOrder.getWorkOrderStatus()))
        {
            throw new ServiceException("仅有待结单的工单才能结单");
        }
        String memberNames = null;
        if(StringUtils.isNotEmpty(gxtRepairOrder.getWorkGroupMemberName())){
            memberNames = gxtRepairOrder.getWorkGroupMemberName();
        }else{
            memberNames = "无";
        }
        gxtRepairOrder.setWorkOrderStatus("completed");
        if("1".equals(gxtRepairOrder.getRepairMethod())){
            gxtRepairOrder.setScoringStatus("to_self");
        }
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        // 负责人为空
        if (null == gxtRepairOrder.getTeamLeaderName() && StringUtils.isEmpty(gxtRepairOrder.getTeamLeaderName())) {
            gxtRepairOrder.setTeamLeaderId(SecurityUtils.getUserId());
            gxtRepairOrder.setTeamLeaderName(SecurityUtils.getLoginUser().getUser().getNickName());
            GxtRepairOrderPerson person = new GxtRepairOrderPerson();
            person.setUserId(SecurityUtils.getUserId());
            person.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
            person.setIsLeader(1);
            person.setOrderId(gxtRepairOrder.getId());
            person.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            person.setStatus(1);
            person.setCreateBy(SecurityUtils.getUsername());
            gxtRepairOrderPersonMapper.insertGxtRepairOrderPerson(person);
        }

        // 修改工作负责人
        if(StringUtils.isNotEmpty(gxtRepairOrder.getTeamLeaderName())){
            List<SysUser> sysUsers = sysUserService.selectUserByNickName(gxtRepairOrder.getTeamLeaderName());
            SysUser sysUser = new SysUser();
            if(sysUsers != null && !sysUsers.isEmpty()){
                if (sysUsers.size() == 1) {
                    sysUser = sysUsers.get(0);
                } else {
                    // 如果有多个用户，查找部门ID与pcsStationPid相同的用户
                    for (SysUser user : sysUsers) {
                        if (user.getDeptId() != null && (user.getDeptId().equals(gxtRepairOrder.getPcsStationPid()) || user.getDeptId().equals(gxtRepairOrder.getPcsStationId()))) {
                            sysUser = user;
                            break;
                        }
                    }
                    // 如果没找到部门匹配的用户，则使用第一个用户
                    if (sysUser == null) {
                        sysUser = sysUsers.get(0);
                    }
                }
                gxtRepairOrder.setTeamLeaderId(sysUser.getUserId());
                gxtRepairOrder.setTeamLeaderName(sysUser.getNickName());
                // 删除旧的工作班成员
                gxtRepairOrderPersonMapper.deleteGxtRepairOrderPersonByOrderId(gxtRepairOrder.getId());
                // 工作票方式工作班成员新增负责人
                if (StringUtils.isNotEmpty(gxtRepairOrder.getInfoEntry()) && "2".equals(gxtRepairOrder.getInfoEntry())) {
                    GxtRepairOrderPerson person = new GxtRepairOrderPerson();
                    person.setUserId(sysUser.getUserId());
                    person.setIsLeader(1);
                    person.setUserId(sysUser.getUserId());
                    person.setUserName(sysUser.getUserName());
                    person.setNickName(sysUser.getNickName());
                    person.setOrderId(gxtRepairOrder.getId());
                    person.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
                    person.setStatus(1);
                    person.setCreateBy(SecurityUtils.getUsername());
                    person.setCreateTime(DateUtils.getNowDate());
                    gxtRepairOrderPersonMapper.insertGxtRepairOrderPerson(person);
                }
            }
        }
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录结单流转信息
        if (result > 0) {
//            String getMisData = configService.selectConfigByKey("gxt.repairOder.getMisData");
//            if(StringUtils.isNotEmpty(getMisData) && getMisData.equals("1")){
            if (StringUtils.isNotEmpty(gxtRepairOrder.getInfoEntry()) && "1".equals(gxtRepairOrder.getInfoEntry())) {   //信息录入选择“关联mis工单”
//                gxtRepairOrderPersonMapper.deleteGxtRepairOrderPersonByOrderId(gxtRepairOrder.getId());
                if(gxtRepairOrder.getRepairOrderPersonList() != null && !gxtRepairOrder.getRepairOrderPersonList().isEmpty()){
                    for (GxtRepairOrderPerson person : gxtRepairOrder.getRepairOrderPersonList())
                    {
                        SysUser sysUser = new SysUser();
                        sysUser.setUserName(person.getUserName());
                        sysUser.setNickName(person.getNickName());
                        List<SysUser> sysUserList = sysUserService.selectUserListNoDataScope(sysUser);
                        if (sysUserList.size() > 0) {
                            sysUser = sysUserList.get(0);
//                            if (sysUser.getUserId().equals(gxtRepairOrder.getTeamLeaderId())) continue; //检修人员是否已存在
//                            //修改工单负责人
//                            if (1 == person.getIsLeader()) {
//                                gxtRepairOrder.setTeamLeaderName(sysUser.getNickName());
//                                gxtRepairOrder.setTeamLeaderId(sysUser.getUserId());
//                                gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);
//                            }
                        } else {
                            throw new ServiceException("检修人员不存在");
                        }
//                        SysUser sysUser = null;
//                        if(StringUtils.isNotEmpty(person.getUserName())){
//                            sysUser = sysUserService.selectUserByUserName(person.getUserName());
//                        }
//                        if(sysUser == null){
//                            if(StringUtils.isNotEmpty(person.getNickName())){
//                                List<SysUser> sysUsers = sysUserService.selectUserByNickName(person.getNickName());
//                                if(sysUsers != null && !sysUsers.isEmpty()){
//                                    if (sysUsers.size() == 1) {
//                                        sysUser = sysUsers.get(0);
//                                    } else {
//                                        // 如果有多个用户，查找部门ID与pcsStationPid相同的用户
//                                        for (SysUser user : sysUsers) {
//                                            if (user.getDeptId() != null && (user.getDeptId().equals(gxtRepairOrder.getPcsStationPid()) || user.getDeptId().equals(gxtRepairOrder.getPcsStationId()))) {
//                                                sysUser = user;
//                                                break;
//                                            }
//                                        }
//                                        // 如果没找到部门匹配的用户，则使用第一个用户
//                                        if (sysUser == null) {
//                                            sysUser = sysUsers.get(0);
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                        if(sysUser == null) continue;
                        person.setUserId(sysUser.getUserId());
                        if (Objects.equals(sysUser.getUserId(), gxtRepairOrder.getTeamLeaderId())) {
                            person.setIsLeader(1);
                        } else {
                            person.setIsLeader(0);
                        }
                        person.setUserId(sysUser.getUserId());
                        person.setOrderId(gxtRepairOrder.getId());
                        person.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
                        person.setStatus(1);
                        person.setCreateBy(SecurityUtils.getUsername());
                        person.setCreateTime(DateUtils.getNowDate());
                        gxtRepairOrderPersonMapper.insertGxtRepairOrderPerson(person);
                    }
                }
            }else{
                if(StringUtils.isNotEmpty(gxtRepairOrder.getWorkGroupMemberName())){
//                    gxtRepairOrderPersonMapper.deleteGxtRepairOrderPersonByOrderId(gxtRepairOrder.getId());
                    String[] splitNames = gxtRepairOrder.getWorkGroupMemberName().split(",");
                    for (String name : splitNames) {
                        List<SysUser> sysUsers = sysUserService.selectUserByNickName(name);
                        if(sysUsers != null && !sysUsers.isEmpty()){
                            SysUser sysUser = null;
                            // 如果只有一个用户，直接使用
                            if (sysUsers.size() == 1) {
                                sysUser = sysUsers.get(0);
                                if (sysUser.getUserId().equals(gxtRepairOrder.getTeamLeaderId())) continue; //检修人员是否已存在
                            } else {
                                // 如果有多个用户，查找部门ID与pcsStationPid相同的用户
                                for (SysUser user : sysUsers) {
                                    if (user.getDeptId() != null && (user.getDeptId().equals(gxtRepairOrder.getPcsStationPid()) || user.getDeptId().equals(gxtRepairOrder.getPcsStationId()))) {
                                        sysUser = user;
                                        break;
                                    }
                                }
                                // 如果没找到部门匹配的用户，则使用第一个用户
                                if (sysUser == null) {
                                    sysUser = sysUsers.get(0);
                                }

                                if (sysUser.getUserId().equals(gxtRepairOrder.getTeamLeaderId())) continue; //检修人员是否已存在
                            }
                            GxtRepairOrderPerson person = new GxtRepairOrderPerson();
                            person.setUserId(sysUser.getUserId());
                            if (Objects.equals(sysUser.getUserId(), gxtRepairOrder.getTeamLeaderId())) {
                                person.setIsLeader(1);
                            } else {
                                person.setIsLeader(0);
                            }
                            person.setUserId(sysUser.getUserId());
                            person.setUserName(sysUser.getUserName());
                            person.setNickName(sysUser.getNickName());
                            person.setOrderId(gxtRepairOrder.getId());
                            person.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
                            person.setStatus(1);
                            person.setCreateBy(SecurityUtils.getUsername());
                            person.setCreateTime(DateUtils.getNowDate());
                            gxtRepairOrderPersonMapper.insertGxtRepairOrderPerson(person);
                        } else {
                            throw new ServiceException("您输入的人员不存在");
                        }
                    }
                }
            }

            gxtUserOperatorHistoryService.insertHistoryRepairOrder(UserConstants.OP_TYPE_TICKET, gxtRepairOrder);

            if ("1".equals(gxtRepairOrder.getRepairMethod()) && gxtRepairOrder.getRepairOrderFlowList() != null && gxtRepairOrder.getRepairOrderFlowList().size() > 0) { // 修改挂起结束时间
                GxtRepairOrderFlow  gxtRepairOrderFlow = gxtRepairOrder.getRepairOrderFlowList().get(0);
                gxtRepairOrderFlowService.updateGxtRepairOrderFlow(gxtRepairOrderFlow);
            }

            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            flow.setActionType("complete");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("维修工单已自评。维修人员："+memberNames);
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }
        return result;
    }

    /**
     * 复运维修工单
     *
     * @param gxtRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional
    public int restartGxtRepairOrder(GxtRepairOrder gxtRepairOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        /*if (gxtRepairOrder.getScore() != null) {
            gxtRepairOrder.setWorkOrderStatus("to_archive");
        }*/
        if(StringUtils.isNotEmpty(gxtRepairOrder.getRepairMethod()) && "2".equals(gxtRepairOrder.getRepairMethod())){
            gxtRepairOrder.setWorkOrderStatus("archived");
        }else{
            // 检查是否终评
            if ("to_archive".equals(oldOrder.getScoringStatus()))
            {
                // 已终评：工单状态改变为已归档
                gxtRepairOrder.setWorkOrderStatus("archived");
                gxtRepairOrder.setScoringStatus("archived");
            }
        }
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录复运流转信息
        if (result > 0) {
            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(gxtRepairOrder.getId());
            flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
            flow.setActionType("restart");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("设备恢复运行");
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
            //if (gxtRepairOrder.getScore() != null) {

            //}
            if("archived".equals(gxtRepairOrder.getWorkOrderStatus())){
                GxtRepairOrderFlow flowArchive = new GxtRepairOrderFlow();
                flowArchive.setOrderId(gxtRepairOrder.getId());
                flowArchive.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
                flowArchive.setActionType("archive");
                flowArchive.setFromStatus(oldOrder.getWorkOrderStatus());
                flowArchive.setToStatus(gxtRepairOrder.getWorkOrderStatus());
                flowArchive.setOperatorId(SecurityUtils.getUserId());
                flowArchive.setOperatorName(nickName);
                flowArchive.setActionTime(DateUtils.getNowDate());
                flowArchive.setActionRemark("工单归档");
                gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flowArchive);
            }
        }
        return result;
    }

    @Override
    @Transactional
    public int returnGxtRepairOrder(GxtRepairOrder gxtRepairOrder) {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        GxtRepairOrder oldOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(gxtRepairOrder.getId());
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        int result = gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);

        // 记录退回流转信息
        if (result > 0) {
            // 退回删除旧的工作负责人
            gxtRepairOrderPersonMapper.deleteGxtRepairOrderPersonByOrderId(gxtRepairOrder.getId());

            GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
            flow.setOrderId(oldOrder.getId());
            flow.setOrderCode(oldOrder.getWorkOrderProjectNo());
            flow.setActionType("return");
            flow.setFromStatus(oldOrder.getWorkOrderStatus());
            flow.setToStatus(gxtRepairOrder.getWorkOrderStatus());
            flow.setOperatorId(SecurityUtils.getUserId());
            flow.setOperatorName(nickName);
            flow.setActionTime(DateUtils.getNowDate());
            flow.setActionRemark("退回工单");
            gxtRepairOrderFlowService.insertGxtRepairOrderFlow(flow);
        }

        return result;
    }

    /**
     * 添加业务特定的数据权限过滤条件
     * 基于角色的数据范围进行自定义权限控制
     *
     * @param gxtRepairOrder 维修工单查询条件
     */
    private void addBusinessDataScopeFilter(GxtRepairOrder gxtRepairOrder) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        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()));

        // 如果有任何一个角色有全部数据权限，则不过滤数据范围
        if (!hasAllDataPermission) {
            // 构建业务特定的数据权限SQL
            StringBuilder businessSql = 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 (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }

                    if (customRoleIds.size() > 1) {
                        // 多个自定义数据权限角色使用IN查询
                        businessSql.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 {
                        // 单个自定义数据权限角色查询
                        businessSql.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 (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }
                    businessSql.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 (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }
                    businessSql.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 (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }
                    businessSql.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 (businessSql.length() > 0) {
                    businessSql.append(" OR ");
                }
                businessSql.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 (businessSql.length() > 0) {
                String businessDataScopeSql = " AND (" + businessSql.toString() + ")";
                gxtRepairOrder.getParams().put("businessDataScope", businessDataScopeSql);
            }
        }

        // 对于已作废(work_order_status = 'invalid')的工单，只有admin用户才能查看
        if (!SecurityUtils.isAdmin(currentUser.getUserId())) {
            String invalidFilterSql = " AND (t.work_order_status != 'invalid')";
            if (gxtRepairOrder.getParams().get("businessDataScope") != null) {
                String existingSql = gxtRepairOrder.getParams().get("businessDataScope").toString();
                gxtRepairOrder.getParams().put("businessDataScope", existingSql + invalidFilterSql);
            } else {
                gxtRepairOrder.getParams().put("businessDataScope", invalidFilterSql);
            }
        }
    }

    /**
     * 添加业务特定的数据权限过滤条件
     * 基于若依框架的数据权限基础上，根据业务字段进行精细化控制
     *
     * @param gxtRepairOrder 维修工单查询条件
     */
    private void addBusinessDataScopeFilterV0(GxtRepairOrder gxtRepairOrder) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        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;
        }

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

        // 遍历用户角色，根据角色类型添加业务特定的权限控制
        for (SysRole role : roles) {
            String roleKey = role.getRoleKey();

            // 从系统配置中获取角色对应的数据权限规则
            String stationManagerRoleKey = configService.selectConfigByKey("gxt.permission.rule.station_manager.roleKey");
            String mainRepairerRoleKey = configService.selectConfigByKey("gxt.permission.rule.main_repairer.roleKey");

            // 检查当前角色是否为场站班长角色
            if (stationManagerRoleKey != null && stationManagerRoleKey.equals(roleKey)) {
                if (businessSql.length() > 0) {
                    businessSql.append(" OR ");
                }
                businessSql.append("(t.pcs_station_pid = ")
                          .append(currentUser.getDeptId())
                          .append(" OR 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)))");
                continue;
            }

            // 检查当前角色是否为主检修员角色
            if (mainRepairerRoleKey != null && mainRepairerRoleKey.equals(roleKey)) {
                if (businessSql.length() > 0) {
                    businessSql.append(" OR ");
                }
                businessSql.append("(t.team_leader_id = ")
                          .append(currentUser.getUserId())
                          .append(" OR (t.team_leader_id IS NULL AND t.work_order_status = 'to_assign'))");
                continue;
            }
        }

        // 如果构建了业务特定的过滤条件，则添加到查询参数中
        if (businessSql.length() > 0) {
            String businessDataScopeSql = " AND (" + businessSql.toString() + ")";
            gxtRepairOrder.getParams().put("businessDataScope", businessDataScopeSql);
        }
    }

    /**
     * 检查角色权限字符是否在配置的角色权限字符列表中
     *
     * @param roleKeyConfig 配置的角色权限字符列表，以逗号分隔
     * @param roleKey 要检查的角色权限字符
     * @return 是否包含该角色权限字符
     */
    private boolean containsRoleKey(String roleKeyConfig, String roleKey) {
        if (roleKeyConfig == null || roleKey == null) {
            return false;
        }

        String[] roleKeys = roleKeyConfig.split(",");
        for (String key : roleKeys) {
            if (key.trim().equals(roleKey)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 验证工单编码是否唯一
     *
     * @param gxtRepairOrder 维修工单信息
     * @return 结果
     */
    @Override
    public boolean checkWorkOrderProjectNoUnique(GxtRepairOrder gxtRepairOrder) {
        Long id = gxtRepairOrder.getId() == null ? -1L : gxtRepairOrder.getId();
        GxtRepairOrder info = gxtRepairOrderMapper.selectGxtRepairOrderByWorkOrderProjectNo(gxtRepairOrder.getWorkOrderProjectNo());
        if (info != null && info.getId().longValue() != id.longValue()) {
            return false;
        }
        return true;
    }

    @Override
    public String importGxtRepairOrderMis(List<GxtRepairOrder> repairOrderList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(repairOrderList) || repairOrderList.isEmpty())
        {
            throw new ServiceException("导入MIS工单数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 1;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (GxtRepairOrder repairOrder : repairOrderList)
        {
            try
            {
                row++;
                if (StringUtils.isEmpty(repairOrder.getMisOrderNo())) {
                    throw new ServiceException("第" + row + "行MIS工单编码不能为空！");
                }
                if (repairOrder.getRealStartTime() == null) {
                    throw new ServiceException("第" + row + "行开始时间不能为空！");
                }
                if (repairOrder.getRealEndTime() == null) {
                    throw new ServiceException("第" + row + "行结束时间不能为空！");
                }
                /*if (StringUtils.isEmpty(repairOrder.getWorkGroupMemberName())) {
                    throw new ServiceException("第" + row + "行检修人员不能为空！");
                }*/
                // 根据misOrderNo验证是否存在这个工单
                GxtRepairOrder repairOrderQuery = new GxtRepairOrder();
                repairOrderQuery.setMisOrderNo(repairOrder.getMisOrderNo());
                List<GxtRepairOrder> gxtRepairOrders = gxtRepairOrderMapper.selectGxtRepairOrderListNoPermi(repairOrderQuery);
                if (gxtRepairOrders == null || gxtRepairOrders.isEmpty())
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、MIS工单编码 " + repairOrder.getMisOrderNo()
                            + " 在维修工单中不存在");
                }
                else if (gxtRepairOrders.size() > 1)
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、MIS工单编码 " + repairOrder.getMisOrderNo()
                            + " 存在于多个维修工单中");
                }
                else
                {
                    GxtRepairOrder repairOrderI = gxtRepairOrders.get(0);
                    repairOrder.setId(repairOrderI.getId());
                    gxtRepairOrderMapper.updateGxtRepairOrder(repairOrder);
                    String workGroupMemberName = repairOrder.getWorkGroupMemberName();
                    if(StringUtils.isNotEmpty(workGroupMemberName)){
                        gxtRepairOrderPersonMapper.deleteGxtRepairOrderPersonByOrderId(repairOrder.getId());
                        String[] splitNames = repairOrder.getWorkGroupMemberName().split(",");
                        for (String name : splitNames) {
                            List<SysUser> sysUsers = sysUserService.selectUserByNickName(name);
                            if(sysUsers != null && !sysUsers.isEmpty()){
                                SysUser sysUser = null;
                                // 如果只有一个用户，直接使用
                                if (sysUsers.size() == 1) {
                                    sysUser = sysUsers.get(0);
                                } else {
                                    // 如果有多个用户，查找部门ID与pcsStationPid相同的用户
                                    for (SysUser user : sysUsers) {
                                        if (user.getDeptId() != null && (user.getDeptId().equals(repairOrder.getPcsStationPid()) || user.getDeptId().equals(repairOrder.getPcsStationId()))) {
                                            sysUser = user;
                                            break;
                                        }
                                    }
                                    // 如果没找到部门匹配的用户，则使用第一个用户
                                    if (sysUser == null) {
                                        sysUser = sysUsers.get(0);
                                    }
                                }
                                GxtRepairOrderPerson person = new GxtRepairOrderPerson();
                                person.setUserId(sysUser.getUserId());
                                person.setNickName(sysUser.getNickName());
                                person.setOrderId(repairOrder.getId());
                                person.setOrderCode(repairOrderI.getWorkOrderProjectNo());
                                person.setStatus(1);
                                person.setCreateBy(SecurityUtils.getUsername());
                                person.setCreateTime(DateUtils.getNowDate());
                                gxtRepairOrderPersonMapper.insertGxtRepairOrderPerson(person);
                            }
                        }
                    }
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、MIS工单编码 " + repairOrder.getMisOrderNo() + " 更新成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、MIS工单编码 " + repairOrder.getMisOrderNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String importGxtRepairOrder(List<GxtRepairOrder> repairOrderList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(repairOrderList) || repairOrderList.isEmpty())
        {
            throw new ServiceException("导入维修工单数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 1;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (GxtRepairOrder repairOrder : repairOrderList)
        {
            try
            {
                row++;
                if (StringUtils.isEmpty(repairOrder.getWorkOrderProjectNo())) {
                    throw new ServiceException("第" + row + "行维修工单编码不能为空！");
                }
                if (StringUtils.isEmpty(repairOrder.getWorkOrderStatusName())) {
                    throw new ServiceException("第" + row + "行工单状态不能为空！");
                }
                if (StringUtils.isEmpty(repairOrder.getGxtCenter())) {
                    throw new ServiceException("第" + row + "行维保中心不能为空！");
                }
                if (StringUtils.isEmpty(repairOrder.getPcsStationName())) {
                    throw new ServiceException("第" + row + "行场站不能为空！");
                }
                if (StringUtils.isEmpty(repairOrder.getPcsDeviceName())) {
                    throw new ServiceException("第" + row + "行风机编号不能为空！");
                }
                /*if (StringUtils.isEmpty(repairOrder.getBrand())) {
                    throw new ServiceException("第" + row + "行风机品牌不能为空！");
                }
                if (StringUtils.isEmpty(repairOrder.getModel())) {
                    throw new ServiceException("第" + row + "行风机型号不能为空！");
                }*/
                if (repairOrder.getOccurTime() == null) {
                    throw new ServiceException("第" + row + "行发生时间不能为空！");
                }

                //验证是否存在这个工单
                GxtRepairOrder repairOrderQuery = gxtRepairOrderMapper.selectGxtRepairOrderByWorkOrderProjectNo(repairOrder.getWorkOrderProjectNo());
                if (StringUtils.isNull(repairOrderQuery))
                {
                    // 处理工单导入数据
                    processImportData(repairOrder, row);
                    repairOrder.setCreateBy(operName);
                    repairOrder.setCreateTime(DateUtils.getNowDate());
                    gxtRepairOrderMapper.insertGxtRepairOrder(repairOrder);
                    processImportDataPerson(repairOrder, row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、维修工单 " + repairOrder.getWorkOrderProjectNo() + " 导入成功");

                }
                else if (updateSupport)
                {
                    // 处理工单导入数据
                    processImportData(repairOrder, row);
                    repairOrder.setId(repairOrderQuery.getId());
                    repairOrder.setUpdateBy(operName);
                    repairOrder.setUpdateTime(DateUtils.getNowDate());
                    gxtRepairOrderMapper.updateGxtRepairOrder(repairOrder);
                    processImportDataPerson(repairOrder, row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、维修工单 " + repairOrder.getWorkOrderProjectNo() + " 更新成功");

                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、维修工单 " + repairOrder.getWorkOrderProjectNo()
                            + "已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、维修工单 " + repairOrder.getWorkOrderProjectNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 处理工单导入数据
     *
     * @param repairOrder 维修工单
     * @param row 行号
     */
    private void processImportData(GxtRepairOrder repairOrder, int row) {
        //处理工单状态
        String workOrderStatus = DictUtils.getDictValue("gxt_work_order_status", repairOrder.getWorkOrderStatusName());
        if(StringUtils.isEmpty(workOrderStatus)){
            throw new ServiceException("第" + row + "行工单状态不存在！");
        }else{
            repairOrder.setWorkOrderStatus(workOrderStatus);
        }
        // 处理维保中心ID
        if (StringUtils.isNotEmpty(repairOrder.getGxtCenter())) {
            SysDept dept = new SysDept();
            dept.setDeptNameNoLike(repairOrder.getGxtCenter());
            List<SysDept> depts = sysDeptService.selectDeptList(dept);
            if (depts != null && depts.size() == 1) {
                repairOrder.setGxtCenterId(depts.get(0).getDeptId());
            }else if (depts != null && depts.size() > 1) {
                throw new ServiceException("第" + row + "行维保中心存在多个！");
            }else {
                throw new ServiceException("第" + row + "行维保中心不存在！");
            }
        }

        // 处理场站ID
        if (StringUtils.isNotEmpty(repairOrder.getPcsStationName())) {
            SysDept dept = new SysDept();
            dept.setDeptNameNoLike(repairOrder.getPcsStationName());
            List<SysDept> depts = sysDeptService.selectDeptList(dept);
            if (depts != null && depts.size() == 1) {
                repairOrder.setPcsStationId(depts.get(0).getDeptId());
                SysDept deptParent = getDeptInfoAndParent(repairOrder.getPcsStationId());
                if (deptParent != null && "3".equals(deptParent.getLevel())) {
                    repairOrder.setPcsStationPid(deptParent.getDeptId());
                }else{
                    repairOrder.setPcsStationPid(repairOrder.getPcsStationId());
                }
            }else if (depts != null && depts.size() > 1) {
                throw new ServiceException("第" + row + "行场站存在多个！");
            }else {
                throw new ServiceException("第" + row + "行场站不存在！");
            }
        }

        GxtEquipment equipment = new GxtEquipment();
        equipment.setEquipmentCode(repairOrder.getPcsDeviceName());
        equipment.setMaintenanceCenter(repairOrder.getGxtCenter());
        equipment.setStation(repairOrder.getPcsStationName());
        GxtEquipment e = gxtEquipmentMapper.selectGxtEquipmentByCodeAndLocation(equipment);
        if (StringUtils.isNull(e))
        {
            throw new ServiceException("第" + row + "行找不到对应的风机设备！");
        }else{
            repairOrder.setPcsDeviceId(e.getEquipmentId());
            repairOrder.setBrand(e.getBrand());
            repairOrder.setModel(e.getModel());
        }

        // 如果派单人姓名不为空，则尝试查找对应的用户
        if (StringUtils.isNotEmpty(repairOrder.getAssignUserName())) {
            List<SysUser> users = sysUserService.selectUserByNickName(repairOrder.getAssignUserName());
            // 如果只找到一个用户，则ID
            if (users != null && users.size() == 1) {
                repairOrder.setAssignUserId(users.get(0).getUserId());
            } else if (users != null && users.size() > 1) {
                throw new ServiceException("第" + row + "行派单人存在多个同名用户！");
            }else {
                throw new ServiceException("第" + row + "行派单人不存在！");
            }
        }

        // 如果接单人姓名不为空，则尝试查找对应的用户
        if (StringUtils.isNotEmpty(repairOrder.getAcceptUserName())) {
            List<SysUser> users = sysUserService.selectUserByNickName(repairOrder.getAcceptUserName());
            // 如果只找到一个用户，则ID
            if (users != null && users.size() == 1) {
                repairOrder.setAcceptUserId(users.get(0).getUserId());
            } else if (users != null && users.size() > 1) {
                SysUser sysUser = null;
                for (SysUser user : users) {
                    if (user.getDeptId() != null && (user.getDeptId().equals(repairOrder.getPcsStationPid()) || user.getDeptId().equals(repairOrder.getPcsStationId()))) {
                        sysUser = user;
                        break;
                    }
                }
                // 如果没找到部门匹配的用户，则使用第一个用户
                if (sysUser == null) {
                    throw new ServiceException("第" + row + "行接单人存在多个同名用户！");
                } else{
                    repairOrder.setAcceptUserId(sysUser.getUserId());
                }
            }else {
                throw new ServiceException("第" + row + "行接单人不存在！");
            }
        }

        // 如果工作负责人姓名不为空，则尝试查找对应的用户
        if (StringUtils.isNotEmpty(repairOrder.getTeamLeaderName())) {
            List<SysUser> users = sysUserService.selectUserByNickName(repairOrder.getTeamLeaderName());
            // 如果只找到一个用户，则ID
            if (users != null && users.size() == 1) {
                repairOrder.setTeamLeaderId(users.get(0).getUserId());
            } else if (users != null && users.size() > 1) {
                SysUser sysUser = null;
                for (SysUser user : users) {
                    if (user.getDeptId() != null && (user.getDeptId().equals(repairOrder.getPcsStationPid()) || user.getDeptId().equals(repairOrder.getPcsStationId()))) {
                        sysUser = user;
                        break;
                    }
                }
                // 如果没找到部门匹配的用户，则使用第一个用户
                if (sysUser == null) {
                    throw new ServiceException("第" + row + "行工作负责人存在多个同名用户！");
                } else{
                    repairOrder.setTeamLeaderId(users.get(0).getUserId());
                }
            }else {
                throw new ServiceException("第" + row + "行工作负责人不存在！");
            }
        }
    }

    /**
     * 处理工单导入检修人员数据
     *
     * @param repairOrder 维修工单
     * @param row 行号
     */
    private void processImportDataPerson(GxtRepairOrder repairOrder, int row) {
        String workGroupMemberName = repairOrder.getWorkGroupMemberName();
        if(StringUtils.isNotEmpty(workGroupMemberName)){
            gxtRepairOrderPersonMapper.deleteGxtRepairOrderPersonByOrderId(repairOrder.getId());
            String[] splitNames = repairOrder.getWorkGroupMemberName().split(",");
            for (String name : splitNames) {
                List<SysUser> sysUsers = sysUserService.selectUserByNickName(name);
                if(sysUsers != null && !sysUsers.isEmpty()){
                    SysUser sysUser = null;
                    // 如果只有一个用户，直接使用
                    if (sysUsers.size() == 1) {
                        sysUser = sysUsers.get(0);
                    } else {
                        // 如果有多个用户，查找部门ID与pcsStationPid相同的用户
                        for (SysUser user : sysUsers) {
                            if (user.getDeptId() != null && (user.getDeptId().equals(repairOrder.getPcsStationPid()) || user.getDeptId().equals(repairOrder.getPcsStationId()))) {
                                sysUser = user;
                                break;
                            }
                        }
                        // 如果没找到部门匹配的用户，则使用第一个用户
                        if (sysUser == null) {
                            sysUser = sysUsers.get(0);
                        }
                    }
                    GxtRepairOrderPerson person = new GxtRepairOrderPerson();
                    person.setUserId(sysUser.getUserId());
                    person.setNickName(sysUser.getNickName());
                    person.setOrderId(repairOrder.getId());
                    person.setOrderCode(repairOrder.getWorkOrderProjectNo());
                    person.setStatus(1);
                    person.setCreateBy(SecurityUtils.getUsername());
                    person.setCreateTime(DateUtils.getNowDate());
                    gxtRepairOrderPersonMapper.insertGxtRepairOrderPerson(person);
                }
            }
        }
    }

    /**
     * 根据MIS工单编码查询工单信息
     *
     * @return 维修工单信息
     */
    @Override
    public GxtRepairOrder selectGxtRepairOrderByMisOrderNo(GxtRepairOrder repairOrder) {
        /*Long id = repairOrder.getId();
        GxtRepairOrder gxtRepairOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(id);
        gxtRepairOrder.setMisOrderNo(repairOrder.getMisOrderNo());*/
        Connection conn = null;

        try {
            // 获取源数据库连接
            conn = sourceDataSource.getConnection();

            // 查询源数据库中的工单数据
            String sql = "SELECT real_start_time, real_end_time FROM wo_workorder_info WHERE work_order_project_no = ?";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, repairOrder.getMisOrderNo());
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                GxtRepairOrder order = new GxtRepairOrder();
                order.setRealStartTime(rs.getTimestamp("real_start_time"));
                order.setRealEndTime(rs.getTimestamp("real_end_time"));

                // 查询检修人员信息
                List<GxtRepairOrderPerson> personList = selectRepairOrderPersonListByMisOrderNo(conn, repairOrder);
                if(personList != null && !personList.isEmpty()){
                    String memberNames = personList.stream()
                                .map(GxtRepairOrderPerson::getNickName)
                                .collect(java.util.stream.Collectors.joining(","));
                    order.setWorkGroupMemberName(memberNames);
                    order.setRepairOrderPersonList(personList);
                }
                return order;
            }

            // 关闭资源
            rs.close();
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 根据MIS工单编码查询工单检修人员列表
     *
     * @param conn 数据库连接
     * @return 检修人员列表
     */
    private List<GxtRepairOrderPerson> selectRepairOrderPersonListByMisOrderNo(Connection conn, GxtRepairOrder repairOrder) {
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<GxtRepairOrderPerson> personList = new ArrayList<>();

        try {
            // 查询源数据库中的工单检修人员数据
            String sql = "SELECT person_id , person_name FROM wo_gdnb_bzcy WHERE work_order_project_no = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, repairOrder.getMisOrderNo());
            rs = stmt.executeQuery();

            while (rs.next()) {
                GxtRepairOrderPerson person = new GxtRepairOrderPerson();
                person.setNickName(rs.getString("person_name"));
                person.setUserName(rs.getString("person_id"));
                personList.add(person);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return personList;
    }

    /**
     * 根据工单ID查询维修工单人员列表
     *
     * @param orderId 工单ID
     * @return 维修工单人员列表
     */
    @Override
    public List<GxtRepairOrderPerson> selectRepairOrderPersonListByOrderId(Long orderId) {
        GxtRepairOrderPerson person = new GxtRepairOrderPerson();
        person.setOrderId(orderId);
        return gxtRepairOrderPersonMapper.selectGxtRepairOrderPersonList(person);
    }

    /**
     * 更新维修工单人员列表
     *
     * @param personList 人员列表
     * @return 结果
     */
    @Override
    public int updateRepairOrderPersonList(List<GxtRepairOrderPerson> personList) {
        int count = 0;
        for (GxtRepairOrderPerson person : personList) {
            count += gxtRepairOrderPersonMapper.updateGxtRepairOrderPerson(person);
        }
        return count;
    }

    @Override
    public int updateGxtRepairOrderForScore(GxtRepairOrder gxtRepairOrder) {
        gxtRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
        return gxtRepairOrderMapper.updateGxtRepairOrder(gxtRepairOrder);
    }

    @Override
    public GxtOrderData selectHomePageData() {
        Integer workOrderFlowRecordsSize = orderPersonMapper.selectWorkOrderFlowRecordsSize();
        Integer repairOrderFlowRecordsSize = orderPersonMapper.selectRepairOrderFlowRecordsSize();
        Integer workOrderFlowRecordsSizeNext = orderPersonMapper.selectWorkOrderFlowRecordsSize();
        Integer repairOrderFlowRecordsSizeNext = orderPersonMapper.selectRepairOrderFlowRecordsSize();

        if (workOrderFlowRecordsSize != null && workOrderFlowRecordsSizeNext != null && !workOrderFlowRecordsSizeNext.equals(workOrderFlowRecordsSize)) {
            orderPersonMapper.delWorkOrderFlowRecordsNext();
            orderPersonMapper.delWorkOrderFlowRecords();
            orderPersonMapper.addWorkOrderFlowRecords();
            orderPersonMapper.addWorkOrderFlowRecordsNext();
        }

        if (repairOrderFlowRecordsSize != null && repairOrderFlowRecordsSizeNext != null && !repairOrderFlowRecordsSizeNext.equals(repairOrderFlowRecordsSize)) {
            orderPersonMapper.delRepairOrderFlowRecordsNext();
            orderPersonMapper.delRepairOrderFlowRecords();
            orderPersonMapper.addRepairOrderFlowRecords();
            orderPersonMapper.addRepairOrderFlowRecordsNext();
        }
        Long userId = SecurityUtils.getUserId();
        Long deptId = SecurityUtils.getDeptId();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long centerId = loginUser.getUser().getDept().getParentId();
        YearMonth currentYearMonth = YearMonth.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        String monthPeriod = currentYearMonth.format(formatter);
        GxtOrderData result = gxtRepairOrderMapper.selectHomePageData(userId,monthPeriod);
        BigDecimal wbgs = result.getWbgs();
        BigDecimal wbgsLast = result.getWbgsLast();
        BigDecimal wxgs = result.getWxgs();
        BigDecimal wxgsLast = result.getWxgsLast();
        BigDecimal score = result.getScore();
        BigDecimal scoreLast = result.getScoreLast();
        BigDecimal wbjsy = BigDecimal.ZERO;
        BigDecimal gfjsy = BigDecimal.ZERO;
        double wjsy = 0;
        double rjsy = 0;
        if (result.getWorkOrderNumLast()!=0 && !result.getWorkOrderNumLast().equals(result.getWorkOrderNum())) {
            wjsy =  (double) ((result.getWorkOrderNum() - result.getWorkOrderNumLast()) * 100) / result.getWorkOrderNumLast();
            wjsy = Math.round(wjsy * 10) /10.0;
        } else if (result.getWorkOrderNumLast()==0 && result.getWorkOrderNum()>0) {
            wjsy = 100.0;
        }
        if (result.getRepairOrderNumLast()!=0 && !result.getRepairOrderNumLast().equals(result.getRepairOrderNum())) {
            rjsy = (double) ((result.getRepairOrderNum() - result.getRepairOrderNumLast()) * 100) / result.getRepairOrderNumLast();
            rjsy = Math.round(rjsy * 10) /10.0;
        } else if (result.getRepairOrderNumLast()==0 && result.getRepairOrderNum()>0) {
            rjsy = 100.0;
        }
        if (wbgsLast.add(wxgsLast).compareTo(BigDecimal.ZERO)!=0) {
            BigDecimal dif = wbgs.add(wxgs).subtract(wbgsLast).subtract(wxgsLast);
            if (dif.compareTo(BigDecimal.ZERO)!=0) {
                wbjsy = dif
                        .divide(wbgsLast.add(wxgsLast), 10, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .setScale(1, RoundingMode.HALF_UP);
            }
        } else if (wbgs.add(wxgs).compareTo(BigDecimal.ZERO)>0) {
            wbjsy = new BigDecimal(100.0);
        }
        if (scoreLast.compareTo(BigDecimal.ZERO)!=0) {
            BigDecimal dif = score.subtract(scoreLast);
            if (dif.compareTo(BigDecimal.ZERO)!=0) {
                gfjsy = dif
                        .divide(scoreLast, 10, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .setScale(1, RoundingMode.HALF_UP);
            }
        } else if (wbgs.add(wxgs).compareTo(BigDecimal.ZERO)>0) {
            gfjsy = new BigDecimal(100.0);
        }
        result.setWorkOrderJsy(wjsy);
        result.setRepairOrderJsy(rjsy);
        result.setWbgs(wbgs.add(wxgs));
        result.setWbjsy(wbjsy);
        result.setGfjsy(gfjsy);

        // 排名权限
        String permission = getJXY(loginUser.getUsername());
        if (StringUtil.isNotEmpty(permission)) {
            GxtUserScore userScoreC = new GxtUserScore();
            userScoreC.setPermission(permission);
            List<GxtUserScore> scoreCompany = gxtRepairOrderMapper.selectHomePageRank(userScoreC);
            Integer companySort = getSort(scoreCompany,userId);
            GxtUserScore userScoreCenter = new GxtUserScore();
            userScoreCenter.setPermission(permission);
            userScoreCenter.setCenterId(centerId);
            List<GxtUserScore> scoreCenter = gxtRepairOrderMapper.selectHomePageRank(userScoreCenter);
            Integer centerSort = getSort(scoreCenter,userId);
            GxtUserScore userScoreD = new GxtUserScore();
            userScoreD.setPermission(permission);
            userScoreD.setDeptId(deptId);
            List<GxtUserScore> scoreDept = gxtRepairOrderMapper.selectHomePageRank(userScoreD);
            Integer deptSort = getSort(scoreDept,userId);
            result.setScoreCompany(scoreCompany);
            result.setCompanySort(companySort);
            result.setScoreCenter(scoreCenter);
            result.setCenterSort(centerSort);
            result.setScoreDept(scoreDept);
            result.setDeptSort(deptSort);
        }else {
            String level = SecurityUtils.getLoginUser().getUser().getDept().getLevel();
            if (("3").equals(level)) {
                result.setWorkOrderNum(result.getPcsWorkOrderNum());
                result.setRepairOrderNum(result.getPcsRepairOrderNum());
            } else if (("2").equals(level)) {
                result.setWorkOrderNum(result.getCenterWorkOrderNum());
                result.setRepairOrderNum(result.getCenterRepairOrderNum());
            } else if (("1").equals(level)){
                result.setWorkOrderNum(result.getCompanyWorkOrderNum());
                result.setRepairOrderNum(result.getCompanyRepairOrderNum());
            }
        }
        return result;
    }

    private Integer getSort(List<GxtUserScore> scoreList, Long userId) {
        // 1. 空列表直接返回第1名（保持原逻辑）
        if (scoreList.isEmpty()) {
            return 1;
        }

        // 2. 第一步：找到目标用户的分数
        BigDecimal targetScore = null;
        for (GxtUserScore score : scoreList) {
            if (score.getUserId().equals(userId)) {
                targetScore = score.getFinalScore();
                break; // 找到后立即终止遍历
            }
        }

        // 未找到目标用户，返回第1名（保持原逻辑）
        if (targetScore == null) {
            return 1;
        }

        // 3. 第二步：找到该分数在列表中第一次出现的索引
        int firstSameScoreIndex = 0;
        for (int i = 0; i < scoreList.size(); i++) {
            if (scoreList.get(i).getFinalScore().compareTo(targetScore) == 0) {
                firstSameScoreIndex = i;
                break; // 找到第一个匹配的就终止，保证是最靠前的位置
            }
        }

        // 4. 排名 = 第一个相同分数的索引 + 1
        return firstSameScoreIndex + 1;
    }

    private String getJXY(String userName) {
        List<SysRole> roleList = sysRoleService.selectRolesByUserName(userName);
        if (!roleList.isEmpty()) {
            Integer roleSort = null;
            Long userHighRoleId = null;
            for (SysRole sysRole : roleList) {
                if (roleSort==null || (sysRole.getRoleSort()!=null && roleSort>sysRole.getRoleSort())) {
                    roleSort = sysRole.getRoleSort();
                    userHighRoleId = sysRole.getRoleId();
                }
            }
            if (userHighRoleId!=null) {
                SysPostHomePage postHomePage = new SysPostHomePage();
                postHomePage.setStatus("0");
                List<SysPostHomePage> list = sysPostHomePageService.selectSysPostHomePageList(postHomePage);
                if (!list.isEmpty()) {
                    for (SysPostHomePage homePage : list) {
                        if (StringUtil.isNotEmpty(homePage.getHomePageType()) && !"-1".equals(homePage.getHomePageType())) {
                            String[] roleIdStrings = homePage.getPostIds().split(",");
                            for (String roleStr : roleIdStrings) {
                                if (Long.parseLong(roleStr) == userHighRoleId) {
                                    String permission = "";
                                    SysPost post = new SysPost();
                                    post.setStatus("0");
                                    post.setIsRank("1");
                                    List<SysPost> postList = sysPostService.selectPostList(post);
                                    List<Long> postIds = new ArrayList<>();
                                    if (!postList.isEmpty()) {
                                        for (SysPost sysPost:postList) {
                                            postIds.add(sysPost.getPostId());
                                        }
                                        List<SysUser> users = sysUserService.selectUserListByPostIds(postIds);
                                        if (!users.isEmpty()) {
                                            for (SysUser user:users) {
                                                permission += user.getUserId() + ",";
                                            }
                                            permission = permission.substring(1);
                                        }
                                    }
                                    return permission;
                                }
                            }
                        }
                    }
                }
            }
        }
        return "";
    }

    @Override
    public int getUnfinishedOrder() {
        GxtRepairOrder repairOrder = new GxtRepairOrder();
        repairOrder.setHomePageParam("toBe");
        List<GxtRepairOrder> list = selectGxtRepairOrderList(repairOrder);
        return list.size();
    }

    @Override
    public List<GxtRepairOrder> selectLatestGxtRepairOrderByDeviceId(Long pcsDeviceId, Integer limit) {
        return gxtRepairOrderMapper.selectLatestGxtRepairOrderByDeviceId(pcsDeviceId, limit);
    }
    
    @Override
    public List<GxtRepairOrder> selectGxtRepairOrderByDeviceIdWithCondition(Long pcsDeviceId, String workOrderStatus, boolean excludeStatus, String orderByField, Integer limit) {
        return gxtRepairOrderMapper.selectGxtRepairOrderByDeviceIdWithCondition(pcsDeviceId, workOrderStatus, excludeStatus, orderByField, limit);
    }
}
