package com.ygtx.gxt.service.impl;

import java.io.File;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.ygtx.common.constant.Constants;
import com.ygtx.common.constant.UserConstants;
import com.ygtx.common.core.domain.entity.SysDept;
import com.ygtx.common.core.domain.entity.SysRole;
import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.common.utils.DictUtils;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.framework.aspectj.DataScopeAspect;
import com.ygtx.gxt.domain.*;
import com.ygtx.gxt.mapper.*;
import com.ygtx.gxt.mapper.source.GxtMisInfoMapper;
import com.ygtx.gxt.service.IGxtUserOperatorHistoryService;
import com.ygtx.system.mapper.SysDeptMapper;
import com.ygtx.system.service.ISysConfigService;
import com.ygtx.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.ygtx.gxt.service.IGxtWorkOrderService;
import com.ygtx.common.exception.ServiceException;

/**
 * 维保工单Service业务层处理
 *
 * @author ygtx
 * @date 2025-10-25
 */
@Service
public class GxtWorkOrderServiceImpl implements IGxtWorkOrderService
{
    private static final Logger logger = LoggerFactory.getLogger(GxtWorkOrderServiceImpl.class);
    @Autowired
    private GxtWorkOrderMapper gxtWorkOrderMapper;

    @Autowired
    private GxtWorkOrderFlowMapper gxtWorkOrderFlowMapper;

    @Autowired
    private GxtWorkOrderPersonMapper gxtWorkOrderPersonMapper;

    @Autowired
    private GxtWorkOrderAttachmentMapper gxtWorkOrderAttachmentMapper;

    @Autowired
    private IGxtUserOperatorHistoryService gxtUserOperatorHistoryService;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private GxtMisInfoMapper misInfoMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private GxtOrderPersonMapper orderPersonMapper;

    /**
     * 查询维保工单
     *
     * @param id 维保工单主键
     * @return 维保工单
     */
    @Override
    public GxtWorkOrder selectGxtWorkOrderById(Long id)
    {
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
            if (order != null) {
            // 查询工单流转记录
//            GxtWorkOrderFlow flowQuery = new GxtWorkOrderFlow();
//            flowQuery.setOrderId(id);
            List<GxtWorkOrderFlow> flowList = selectWorkOrderFlowByOrderId(id);
            order.setWorkOrderFlowList(flowList);
//            GxtWorkOrderAttachment workOrderAttachment = new GxtWorkOrderAttachment();
//            workOrderAttachment.setWorkOrderId(id);
//            List<GxtWorkOrderAttachment> workOrderAttachments = gxtWorkOrderAttachmentMapper.selectGxtWorkOrderAttachmentByOrderId(id);
//            order.setAttachments(workOrderAttachments);
            GxtWorkOrderPerson  workOrderPerson= new GxtWorkOrderPerson();
            workOrderPerson.setOrderId(id);
            List<GxtWorkOrderPerson> orderPersonList = gxtWorkOrderPersonMapper.selectGxtWorkOrderPersonList(workOrderPerson);
            order.setWorkOrderPersonList(orderPersonList);

        }
        return order;
    }

    /**
     * 查询维保工单列表
     *
     * @param gxtWorkOrder 维保工单
     * @return 维保工单
     */
    @Override
    public List<GxtWorkOrder> selectGxtWorkOrderList(GxtWorkOrder gxtWorkOrder)
    {
        // 添加业务特定的数据权限过滤
        addBusinessDataScopeFilter(gxtWorkOrder);

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

        return gxtWorkOrderMapper.selectGxtWorkOrderList(gxtWorkOrder);
    }

    /**
     * 新增维保工单
     *
     * @param gxtWorkOrder 维保工单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertGxtWorkOrder(GxtWorkOrder gxtWorkOrder)
    {
        // 检查工单编码是否已存在
        GxtWorkOrder existOrder = gxtWorkOrderMapper.selectGxtWorkOrderByCode(gxtWorkOrder.getWorkOrderProjectNo());
        if (existOrder != null)
        {
            throw new ServiceException("工单编码已存在");
        }

        // 设置默认状态为待下发
        if (gxtWorkOrder.getWorkOrderStatus() == null || gxtWorkOrder.getWorkOrderStatus().isEmpty())
        {
            gxtWorkOrder.setWorkOrderStatus("to_issue");
        } else {
            gxtWorkOrder.setAssignTime(DateUtils.getNowDate());
            gxtWorkOrder.setAssignUserId(SecurityUtils.getUserId());
            gxtWorkOrder.setAssignUserName(SecurityUtils.getLoginUser().getUser().getNickName());
        }
        SysDept dept = deptMapper.selectDeptByDeptName(gxtWorkOrder.getPcsStationName());
        if (dept != null) {
            gxtWorkOrder.setPcsStationId(dept.getDeptId());
            // 设备场站
            if ("4".equals(dept.getLevel())) {
                SysDept pDept = deptMapper.selectDeptById(dept.getParentId());
                gxtWorkOrder.setGxtCenterId(pDept.getParentId());
                gxtWorkOrder.setGxtCenter(pDept.getParentName());
                gxtWorkOrder.setPcsStationPid(pDept.getDeptId());
            } else if ("3".equals(dept.getLevel())) {
//                        SysDept pDept = deptMapper.selectDeptById(dept.getDeptId());
                gxtWorkOrder.setGxtCenterId(dept.getParentId());
                gxtWorkOrder.setGxtCenter(dept.getParentName());
                gxtWorkOrder.setPcsStationPid(dept.getDeptId());
            }
        } else {
            throw new ServiceException("新增失败！" + gxtWorkOrder.getPcsStationName()+"不存在！");
        }

        gxtWorkOrder.setOrderType(2L);
        gxtWorkOrder.setCreateTime(DateUtils.getNowDate());
        gxtWorkOrder.setCreateBy(SecurityUtils.getUsername());
        int result = gxtWorkOrderMapper.insertGxtWorkOrder(gxtWorkOrder);
        String actionType = null;
        if ("to_issue".equals(gxtWorkOrder.getWorkOrderStatus())) {
            actionType = "create";
        } else {
            actionType = "create_to_assign";
        }

        // 记录创建流转
        if (result > 0)
        {
            recordWorkOrderFlow(gxtWorkOrder.getId(), gxtWorkOrder.getWorkOrderProjectNo(),
                    actionType, null, gxtWorkOrder.getWorkOrderStatus(), null);

            gxtWorkOrder.setAcceptUserId(SecurityUtils.getUserId());
            gxtWorkOrder.setUpdateBy(SecurityUtils.getUsername());
            gxtUserOperatorHistoryService.insertHistoryWorkOrder(UserConstants.OP_TYPE_TICKET, gxtWorkOrder);


            if("assigned".equals(gxtWorkOrder.getWorkOrderStatus())) {
                // 自动挂起时间
                String suspendTime = configService.selectConfigByKey("gxt.autoSuspend.time");
                String suspendEndTime = configService.selectConfigByKey("gxt.autoSuspend.endTime");
                if (StringUtils.isNotEmpty(suspendTime) && StringUtils.isNotEmpty(suspendEndTime)) {
                    // 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)) {
                        gxtWorkOrder.setWorkOrderStatus("auto_suspend");
                        gxtWorkOrderMapper.updateGxtWorkOrder(gxtWorkOrder);
                        GxtWorkOrderFlow flow = new GxtWorkOrderFlow();
                        flow.setOrderId(gxtWorkOrder.getId());
                        flow.setOrderCode(gxtWorkOrder.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());
                        gxtWorkOrderFlowMapper.insertGxtWorkOrderFlow(flow);
                    }
                }
            }

        }

        return result;
    }

    /**
     * 修改维保工单
     *
     * @param gxtWorkOrder 维保工单
     * @return 结果
     */
    @Override
    public int updateGxtWorkOrder(GxtWorkOrder gxtWorkOrder)
    {
        // 检查工单编码是否与其他工单重复
        GxtWorkOrder existOrder = gxtWorkOrderMapper.selectGxtWorkOrderByCode(gxtWorkOrder.getWorkOrderProjectNo());
        if (existOrder != null && !existOrder.getId().equals(gxtWorkOrder.getId()))
        {
            throw new ServiceException("工单编码已存在");
        }
        SysDept dept = deptMapper.selectDeptByDeptName(gxtWorkOrder.getPcsStationName());
        if (dept != null) {
            gxtWorkOrder.setPcsStationId(dept.getDeptId());
            // 设备场站
            if ("4".equals(dept.getLevel())) {
                SysDept pDept = deptMapper.selectDeptById(dept.getParentId());
                gxtWorkOrder.setGxtCenterId(pDept.getParentId());
                gxtWorkOrder.setGxtCenter(pDept.getParentName());
                gxtWorkOrder.setPcsStationPid(pDept.getDeptId());
            } else if ("3".equals(dept.getLevel())) {
                gxtWorkOrder.setGxtCenterId(dept.getParentId());
                gxtWorkOrder.setGxtCenter(dept.getParentName());
                gxtWorkOrder.setPcsStationPid(dept.getDeptId());
            }
        } else {
            throw new ServiceException("编辑失败！" + gxtWorkOrder.getPcsStationName()+"不存在！");
        }
        if("assigned".equals(gxtWorkOrder.getWorkOrderStatus())){
            gxtWorkOrder.setAssignTime(DateUtils.getNowDate());
            gxtWorkOrder.setAssignUserId(SecurityUtils.getUserId());
            gxtWorkOrder.setAssignUserName(SecurityUtils.getLoginUser().getUser().getNickName());
        }
        gxtWorkOrder.setUpdateTime(DateUtils.getNowDate());
        gxtWorkOrder.setUpdateBy(SecurityUtils.getUsername());
        int result = gxtWorkOrderMapper.updateGxtWorkOrder(gxtWorkOrder);
        String actionType = null;
        actionType = "assign";
//        if ("draft".equals(gxtWorkOrder.getWorkOrderStatus())) {
//            actionType = "create";
//        } else {
//            actionType = "assign";
//        }
        // 记录创建流转
        if (result > 0)
        {
            recordWorkOrderFlow(gxtWorkOrder.getId(), gxtWorkOrder.getWorkOrderProjectNo(),
                    actionType, null, gxtWorkOrder.getWorkOrderStatus(), null);


            if(gxtWorkOrder.getWorkOrderStatus().equals("assigned")) {
                // 自动挂起时间
                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)) {
                        gxtWorkOrder.setWorkOrderStatus("auto_suspend");
                        gxtWorkOrderMapper.updateGxtWorkOrder(gxtWorkOrder);
                        GxtWorkOrderFlow flow = new GxtWorkOrderFlow();
                        flow.setOrderId(gxtWorkOrder.getId());
                        flow.setOrderCode(gxtWorkOrder.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());
                        gxtWorkOrderFlowMapper.insertGxtWorkOrderFlow(flow);
                    }
                }

            }

        }
        return result;
    }

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

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

    /**
     * 派单给班组组长
     *
     * @param id 工单ID
     * @param teamLeaderId 班组组长ID
     * @param teamLeaderName 班组组长姓名
     * @return 结果
     */
    @Override
    @Transactional
    public int assignToTeamLeader(Long id, Long teamLeaderId, String teamLeaderName)
    {
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }

        // 只有草稿或待派单状态才能派单
        if (!"draft".equals(order.getWorkOrderStatus()) && !"to_assign".equals(order.getWorkOrderStatus()))
        {
            throw new ServiceException("当前工单状态不允许派单");
        }

        String oldStatus = order.getWorkOrderStatus();

        order.setTeamLeaderId(teamLeaderId);
        order.setTeamLeaderName(teamLeaderName);
        order.setAssignTime(DateUtils.getNowDate());
        order.setAssignUserId(SecurityUtils.getUserId());
        order.setAssignUserName(SecurityUtils.getUsername());
        order.setWorkOrderStatus("assigned");
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

        // 记录流转
        if (result > 0)
        {
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "assign", oldStatus, "assigned",
                    "派单给班组组长：" + teamLeaderName);
        }

        return result;
    }

    /**
     * 班组组长接单
     *
     * @param id 工单ID
     * @return 结果
     */
    @Override
    @Transactional
    public int acceptByTeamLeader(Long id)
    {
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }

        // 只有已派单状态才能接单
        if (!"assigned".equals(order.getWorkOrderStatus()))
        {
            throw new ServiceException("当前工单状态不允许接单");
        }

        // 验证是否为班组组长
        Long currentUserId = SecurityUtils.getUserId();
        if (!currentUserId.equals(order.getTeamLeaderId()))
        {
            throw new ServiceException("只有被指派的班组组长才能接单");
        }

        String oldStatus = order.getWorkOrderStatus();

        order.setAcceptTime(DateUtils.getNowDate());
        order.setAcceptUserId(currentUserId);
        order.setAcceptUserName(SecurityUtils.getUsername());
        order.setWorkOrderStatus("accepted");
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

        // 记录流转
        if (result > 0)
        {
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "accept", oldStatus, "accepted",
                    "班组组长接单");
        }

        return result;
    }

    /**
     * 班组组长派单给工作组成员
     *
     * @param id 工单ID
     * @param workGroupMemberId 工作组成员ID
     * @param workGroupMemberName 工作组成员姓名
     * @return 结果
     */
    @Override
    @Transactional
    public int assignToWorkGroupMember(Long id, Long workGroupMemberId, String workGroupMemberName)
    {
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }

        // 只有已接单状态才能派给工作组成员
        if (!"accepted".equals(order.getWorkOrderStatus()))
        {
            throw new ServiceException("当前工单状态不允许派单给工作组成员");
        }

        // 验证是否为班组组长
        Long currentUserId = SecurityUtils.getUserId();
        if (!currentUserId.equals(order.getTeamLeaderId()))
        {
            throw new ServiceException("只有班组组长才能派单给工作组成员");
        }

        String oldStatus = order.getWorkOrderStatus();

        order.setWorkGroupMemberId(workGroupMemberId);
        order.setWorkGroupMemberName(workGroupMemberName);
        order.setWorkOrderStatus("assigned");
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

        // 记录流转
        if (result > 0)
        {
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "assign", oldStatus, "assigned",
                    "派单给工作组成员：" + workGroupMemberName);
        }

        return result;
    }

    /**
     * 工作组成员接单
     *
     * @param id 工单ID
     * @return 结果
     */
    @Override
    @Transactional
    public int acceptByWorkGroupMember(Long id)
    {
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }

        // 只有已派单状态才能接单
        if (!"assigned".equals(order.getWorkOrderStatus()))
        {
            throw new ServiceException("当前工单状态不允许接单");
        }

        // 验证是否为工作组成员
        Long currentUserId = SecurityUtils.getUserId();
        if (order.getWorkGroupMemberId() == null || !currentUserId.equals(order.getWorkGroupMemberId()))
        {
            throw new ServiceException("只有被指派的工作组成员才能接单");
        }

        String oldStatus = order.getWorkOrderStatus();

        order.setAcceptTime(DateUtils.getNowDate());
        order.setAcceptUserId(currentUserId);
        order.setAcceptUserName(SecurityUtils.getUsername());
        order.setWorkOrderStatus("processing");
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

        // 记录流转
        if (result > 0)
        {
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "accept", oldStatus, "processing",
                    "工作组成员接单，开始处理");
        }

        return result;
    }

    /**
     * 挂起工单申请
     *
     * @param gxtWorkOrder 工单对象，包含挂起原因不会
     * @return 结果
     */
    @Override
    @Transactional
    public int suspendWorkOrder(GxtWorkOrder gxtWorkOrder)
    {
        Long id = gxtWorkOrder.getId();
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }

        // 仅有处理中状态才能申请挂起
        if (!"to_finish".equals(order.getWorkOrderStatus()))
        {
            throw new ServiceException("当前工单状态不允许申请挂起");
        }

        String oldStatus = order.getWorkOrderStatus();

        // 更新工单信息 - 挂起申请后状态变为TO_APPROVE，待审批通过才能正式挂起
        order.setSuspendReason(gxtWorkOrder.getSuspendReason());
        order.setSuspendTime(DateUtils.getNowDate());
        order.setWorkOrderStatus("to_approve");
        order.setSuspendExplain(gxtWorkOrder.getSuspendExplain());
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());
        if (null == order.getTeamLeaderName() && StringUtils.isEmpty(order.getTeamLeaderName())) {
            order.setTeamLeaderId(SecurityUtils.getUserId());
            order.setTeamLeaderName(SecurityUtils.getLoginUser().getUser().getNickName());
            GxtWorkOrderPerson person = new GxtWorkOrderPerson();
            person.setUserId(SecurityUtils.getUserId());
            person.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
            person.setIsLeader(1);
            person.setOrderId(order.getId());
            person.setOrderCode(order.getWorkOrderProjectNo());
            person.setStatus(1);
            person.setCreateBy(SecurityUtils.getUsername());
            gxtWorkOrderPersonMapper.insertGxtWorkOrderPerson(person);
        }

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

        if (result > 0)
        {
            String suspendReasonLabel = DictUtils.getDictLabel("gxt_order_suspend_reason", gxtWorkOrder.getSuspendReason());
            // 记录流转
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "to_approve", oldStatus, "to_approve",
                    "申请挂起，原因: " + suspendReasonLabel);
        }
        return result;
    }

    /**
     * 审批挂起申请
     *
     * @param gxtWorkOrder 工单对象，包含审批结果和驳回理由
     * @return 结果
     */
    @Override
    @Transactional
    public int approveWorkOrder(GxtWorkOrder gxtWorkOrder)
    {
        Long id = gxtWorkOrder.getId();
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }

        // 仅有待审批状态才能审批
        if (!"to_approve".equals(order.getWorkOrderStatus()))
        {
            throw new ServiceException("当前工单状态不允许审批");
        }

        String oldStatus = order.getWorkOrderStatus();
        String newStatus = gxtWorkOrder.getWorkOrderStatus();
        String actionRemark;
        String actionType;

        // 根据工单状态判断审批结果
        if ("suspended".equals(newStatus))
        {
            actionRemark = "审批挂起申请通过，工单已挂起";
            actionType = "approved";
        }
        else if ("to_finish".equals(newStatus))
        {
            actionRemark = "审批挂起申请驳回，驳回原因: " + gxtWorkOrder.getRejectionReason();
            actionType = "rejected";
        }
        else
        {
            throw new ServiceException("无效的工单状态");
        }

        order.setWorkOrderStatus(newStatus);
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

        if (result > 0)
        {
            // 记录流转
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), actionType, oldStatus, newStatus, actionRemark);
        }

        return result;
    }

    /**
     * 重启工单
     *
     * @param id 工单ID
     * @return 结果
     */
    @Override
    @Transactional
    public int restartWorkOrder(Long id)
    {
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }

        // 只有挂起的工单才能重启
        if (!"suspended".equals(order.getWorkOrderStatus()))
        {
            throw new ServiceException("只有挂起的工单才能重启");
        }

        // 验证是否为班组组长或工作组成员
        Long currentUserId = SecurityUtils.getUserId();
        if (!currentUserId.equals(order.getTeamLeaderId()) && !currentUserId.equals(order.getWorkGroupMemberId()))
        {
            throw new ServiceException("只有班组组长或工作组成员才能重启工单");
        }

        String oldStatus = order.getWorkOrderStatus();

        order.setRestartTime(DateUtils.getNowDate());
        order.setWorkOrderStatus("processing");
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

        // 记录流转
        if (result > 0)
        {
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "restart", oldStatus, "processing",
                    "重启工单，继续处理");
        }

        return result;
    }

    /**
     * 完成工单
     *
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public int completeWorkOrder(GxtWorkOrder gxtWorkOrder)
    {
        Long id = gxtWorkOrder.getId();
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }

        String targetStatus = gxtWorkOrder.getWorkOrderStatus();

        // 判断是结束还是结单还是评分
        if ("to_finish".equals(targetStatus))
        {
            // 结束：仅有处理中的工单才能结束
            if (!"processing".equals(order.getWorkOrderStatus()))
            {
                throw new ServiceException("仅有处理中的工单才能结束");
            }

            String oldStatus = order.getWorkOrderStatus();
            order.setWorkOrderStatus("to_finish");
            order.setRealEndTime(DateUtils.getNowDate());
            order.setUpdateTime(DateUtils.getNowDate());
            order.setUpdateBy(SecurityUtils.getUsername());

            int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

            if (result > 0)
            {
                recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "complete", oldStatus, "to_finish",
                        "处理完成，工单状态变为待结单");
            }

            return result;
        }
        else if ("completed".equals(targetStatus))
        {
            // 结单：仅有待结单的工单才能结单
            if (!"to_finish".equals(order.getWorkOrderStatus()))
            {
                throw new ServiceException("仅有待结单的工单才能结单");
            }

            String oldStatus = order.getWorkOrderStatus();
            order.setWorkOrderStatus("completed");
            order.setScoringStatus("to_self");
            order.setCompleteTime(DateUtils.getNowDate());
            order.setRealContent(gxtWorkOrder.getRealContent());
            order.setUpdateTime(DateUtils.getNowDate());
            order.setUpdateBy(SecurityUtils.getUsername());
            order.setInspectionType(gxtWorkOrder.getInspectionType());
            order.setAttachmentUrls(gxtWorkOrder.getAttachmentUrls());
            order.setWorkGroupMemberName(gxtWorkOrder.getWorkGroupMemberName());
            order.setRealStartTime(gxtWorkOrder.getRealStartTime());
            order.setRealEndTime(gxtWorkOrder.getRealEndTime());
            order.setWlryNum(gxtWorkOrder.getWlryNum());
            order.setWwryNum(gxtWorkOrder.getWwryNum());
            order.setOrderEntryType(gxtWorkOrder.getOrderEntryType());
            order.setWorkPermitNum(gxtWorkOrder.getWorkPermitNum());
            order.setMisNo(gxtWorkOrder.getMisNo());
            order.setInfoEntry(gxtWorkOrder.getInfoEntry());
            order.setFinalizeMethod(gxtWorkOrder.getFinalizeMethod());
            if (null == order.getTeamLeaderName() && StringUtils.isEmpty(order.getTeamLeaderName())) {
                order.setTeamLeaderId(SecurityUtils.getUserId());
                order.setTeamLeaderName(SecurityUtils.getLoginUser().getUser().getNickName());
                GxtWorkOrderPerson person = new GxtWorkOrderPerson();
                person.setUserId(SecurityUtils.getUserId());
                person.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
                person.setIsLeader(1);
                person.setOrderId(order.getId());
                person.setOrderCode(order.getWorkOrderProjectNo());
                person.setStatus(1);
                person.setCreateBy(SecurityUtils.getUsername());
                gxtWorkOrderPersonMapper.insertGxtWorkOrderPerson(person);
            }
            // 修改工作负责人
            if(StringUtils.isNotEmpty(gxtWorkOrder.getTeamLeaderName())){
                List<SysUser> sysUsers = sysUserService.selectUserByNickName(gxtWorkOrder.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(gxtWorkOrder.getPcsStationPid()) || user.getDeptId().equals(gxtWorkOrder.getPcsStationId()))) {
                                sysUser = user;
                                break;
                            }
                        }
                        // 如果没找到部门匹配的用户，则使用第一个用户
                        if (sysUser == null) {
                            sysUser = sysUsers.get(0);
                        }
                    }
                    order.setTeamLeaderId(sysUser.getUserId());
                    order.setTeamLeaderName(sysUser.getNickName());
                }

                // 删除旧的工作班成员
                gxtWorkOrderPersonMapper.deleteGxtWorkOrderPersonByOrderId(gxtWorkOrder.getId());
                // 工作票方式工作班成员新增负责人
                if (StringUtils.isNotEmpty(gxtWorkOrder.getInfoEntry()) && "2".equals(gxtWorkOrder.getInfoEntry())) {
                    GxtWorkOrderPerson person = new GxtWorkOrderPerson();
                    person.setUserId(sysUser.getUserId());
                    person.setIsLeader(1);
                    person.setUserId(sysUser.getUserId());
                    person.setUserName(sysUser.getUserName());
                    person.setNickName(sysUser.getNickName());
                    person.setOrderId(gxtWorkOrder.getId());
                    person.setOrderCode(gxtWorkOrder.getWorkOrderProjectNo());
                    person.setStatus(1);
                    person.setCreateBy(SecurityUtils.getUsername());
                    person.setCreateTime(DateUtils.getNowDate());
                    gxtWorkOrderPersonMapper.insertGxtWorkOrderPerson(person);
                }
            }


            int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

            if (result > 0)
            {
                if (StringUtils.isNotEmpty(gxtWorkOrder.getInfoEntry()) && "1".equals(gxtWorkOrder.getInfoEntry())) {

                    if (gxtWorkOrder.getWorkOrderPersonList().size() > 0) {

                        gxtWorkOrderPersonMapper.deleteGxtWorkOrderPersonByOrderId(id);
                        // 3. 添加新的工作组成员
                        for (GxtWorkOrderPerson person : gxtWorkOrder.getWorkOrderPersonList()) {
                            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 (1 == person.getIsLeader()) {
//                                    order.setTeamLeaderName(sysUser.getNickName());
//                                    order.setTeamLeaderId(sysUser.getUserId());
//                                    gxtWorkOrderMapper.updateGxtWorkOrder(order);
//                                }
                            } 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(gxtWorkOrder.getPcsStationPid()) || user.getDeptId().equals(gxtWorkOrder.getPcsStationId()))) {
//                                            sysUser = user;
//                                            break;
//                                        }
//                                    }
//                                    // 如果没找到部门匹配的用户，则使用第一个用户
//                                    if (sysUser == null) {
//                                        sysUser = sysUsers.get(0);
//                                    }
//                                }
//                            }
//                        }
//                    }
//                    if(sysUser == null) continue;
                            person.setUserId(sysUser.getUserId());
                            if (sysUser.getUserId() == order.getTeamLeaderId()) {
                                person.setIsLeader(1);
                            } else {
                                person.setIsLeader(0);
                            }
                            person.setOrderId(id);
                            person.setOrderCode(order.getWorkOrderProjectNo());
                            person.setStatus(1);
                            person.setCreateBy(SecurityUtils.getUsername());
//                    person.setCreateTime(DateUtils.getNowDate());
                            gxtWorkOrderPersonMapper.insertGxtWorkOrderPerson(person);
                        }
                    }
                } else {
                    if(StringUtils.isNotEmpty(gxtWorkOrder.getWorkGroupMemberName())){
//                    gxtRepairOrderPersonMapper.deleteGxtRepairOrderPersonByOrderId(gxtRepairOrder.getId());
                        String[] splitNames = gxtWorkOrder.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(order.getTeamLeaderId())) continue; //检修人员是否已存在
                                } else {
                                    // 如果有多个用户，查找部门ID与pcsStationPid相同的用户
                                    for (SysUser user : sysUsers) {
                                        if (user.getDeptId() != null && (user.getDeptId().equals(order.getPcsStationPid())
                                                || user.getDeptId().equals(order.getPcsStationId()))) {
                                            sysUser = user;
                                            break;
                                        }
                                    }
                                    // 如果没找到部门匹配的用户，则使用第一个用户
                                    if (sysUser == null) {
                                        sysUser = sysUsers.get(0);
                                    }

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

                if (null != gxtWorkOrder.getWorkOrderFlowList() && gxtWorkOrder.getWorkOrderFlowList().size() > 0) {
                    GxtWorkOrderFlow  workOrderFlow = gxtWorkOrder.getWorkOrderFlowList().get(0);
                    gxtWorkOrderFlowMapper.updateGxtWorkOrderFlow(workOrderFlow);
                }

                recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "complete", oldStatus, "completed",
                        "工单完成，工单状态变为已完成");


            }

            return result;
        }
        else if ("to_archive".equals(targetStatus))
        {
            // 评分：仅有已完成的工单才能评分
            if (!"completed".equals(order.getWorkOrderStatus()))
            {
                throw new ServiceException("仅有已完成的工单才能评分");
            }

            String oldStatus = order.getWorkOrderStatus();
            order.setUpdateTime(DateUtils.getNowDate());
            order.setUpdateBy(SecurityUtils.getUsername());
            order.setScore(gxtWorkOrder.getScore());
            order.setReviewContent(gxtWorkOrder.getReviewContent());

            // 检查 restart_time 是否有值（判断是否已复运）
            if (order.getRestartTime() != null)
            {
                // 已复运：工单状态改变为待归档
                order.setWorkOrderStatus("to_archive");
            }

            // 未复运：工单状态保持不变（仍为 completed）
            // 仅更新其他字段（如 score、reviewContent 等）
            int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);
            if (result > 0)
            {
                recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "rating", oldStatus, oldStatus,
                        "工单已评分但未复运，工单状态保持不变");
            }
            return result;
        }
        else if ("restarted".equals(targetStatus))
        {
            String oldStatus = order.getWorkOrderStatus();
            order.setRestartTime(gxtWorkOrder.getRestartTime());
            order.setLostPower(gxtWorkOrder.getLostPower());
            order.setUpdateTime(DateUtils.getNowDate());
            order.setUpdateBy(SecurityUtils.getUsername());
            // 检查是否终评
            if ("to_archive".equals(order.getScoringStatus()))
            {
                // 已终评：工单状态改变为已归档
                order.setWorkOrderStatus("archived");
                order.setScoringStatus("archived");
            }
            int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

            if (result > 0)
            {
                recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "restart", oldStatus, oldStatus,
                        null);
            }

            return result;
        }
        else
        {
            throw new ServiceException("当前的工单状态不允许此操作");
        }
    }

    /**
     * 查询工单流转记录
     *
     * @param orderId 工单ID
     * @return 流转记录集合
     */
    @Override
    public List<GxtWorkOrderFlow> selectWorkOrderFlowByOrderId(Long orderId)
    {
        return gxtWorkOrderFlowMapper.selectGxtWorkOrderFlowByOrderId(orderId);
    }

    /**
     * 接单（支持一次性选择处理人员）
     *
     * @param gxtWorkOrder 工单
     * @return 结果
     */
    @Override
    @Transactional
    public int acceptOrder(GxtWorkOrder gxtWorkOrder)
    {
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        Long id = gxtWorkOrder.getId();
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }
        // 仅有已派单状态才能接单
        if (!"assigned".equals(order.getWorkOrderStatus()))
        {
            throw new ServiceException("当前工单状态不允许接单");
        }
        String oldStatus = order.getWorkOrderStatus();
        // 1. 更新工单信息
        order.setAcceptTime(DateUtils.getNowDate());
        order.setAcceptUserId(SecurityUtils.getUserId());
        order.setAcceptUserName(nickName);
        order.setWorkOrderStatus(gxtWorkOrder.getWorkOrderStatus());
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());
        order.setTeamLeaderId(gxtWorkOrder.getTeamLeaderId());
        order.setTeamLeaderName(gxtWorkOrder.getTeamLeaderName());

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);
        if (result > 0)
        {
            if (null != gxtWorkOrder.getTeamLeaderId()) {
                // 工作负责人存入工单工作组员名单
                GxtWorkOrderPerson person = new GxtWorkOrderPerson();
                person.setIsLeader(1);
                person.setUserId(gxtWorkOrder.getTeamLeaderId());
                person.setNickName(gxtWorkOrder.getTeamLeaderName());
                person.setMisNo(order.getMisNo());
                person.setOrderId(order.getId());
                person.setOrderCode(order.getWorkOrderProjectNo());
                person.setStatus(1);
                person.setCreateBy(SecurityUtils.getUsername());
                person.setCreateTime(DateUtils.getNowDate());
                gxtWorkOrderPersonMapper.insertGxtWorkOrderPerson(person);
                gxtUserOperatorHistoryService.insertHistoryWorkOrder(UserConstants.OP_TYPE_LEADER, order);
            }
//            String memberNames = gxtWorkOrder.getWorkOrderPersonList().stream()
//                    .map(GxtWorkOrderPerson::getNickName)
//                    .collect(java.util.stream.Collectors.joining(","));
            // 4. 记录流转
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "process", oldStatus, "processing",
                    null);
        }

        return result;
    }

    /**
     * 记录工单流转
     *
     * @param orderId 工单ID
     * @param orderCode 工单编码
     * @param actionType 操作类型
     * @param fromStatus 原状态
     * @param toStatus 目标状态
     * @param remark 备注
     */
    private void recordWorkOrderFlow(Long orderId, String orderCode, String actionType,
                                      String fromStatus, String toStatus, String remark)
    {
        GxtWorkOrderFlow flow = new GxtWorkOrderFlow();
        flow.setOrderId(orderId);
        flow.setOrderCode(orderCode);
        flow.setActionType(actionType);
        flow.setFromStatus(fromStatus);
        flow.setToStatus(toStatus);
        flow.setOperatorId(SecurityUtils.getUserId());
        flow.setOperatorName(SecurityUtils.getLoginUser().getUser().getNickName());
        flow.setActionTime(DateUtils.getNowDate());
        flow.setActionRemark(remark);
        flow.setCreateBy(SecurityUtils.getUsername());
        flow.setCreateTime(DateUtils.getNowDate());

        gxtWorkOrderFlowMapper.insertGxtWorkOrderFlow(flow);
    }

    /**
     * 开始处理工单
     *
     * @param gxtWorkOrder 工单对象，包含工单状态和其他信息
     * @return 结果
     */
    @Override
    @Transactional
    public int startWorkOrder(GxtWorkOrder gxtWorkOrder)
    {
        Long id = gxtWorkOrder.getId();
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }

        // 仅有已接单状态才能开始处理
        if (!"accepted".equals(order.getWorkOrderStatus()) && !"suspended".equals(order.getWorkOrderStatus()))
        {
            throw new ServiceException("当前工单状态不允许开始处理");
        }

        String oldStatus = order.getWorkOrderStatus();

        // 更新工单信息
        order.setWorkOrderStatus("processing");
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

        if (result > 0)
        {
            // 记录流转
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "start", oldStatus, "processing",
                    "开始处理");
        }

        return result;
    }

    /**
     * 暂停工单
     *
     * @param gxtWorkOrder 工单对象，包含暂停原因不会
     * @return 结果
     */
    @Override
    @Transactional
    public int pauseWorkOrder(GxtWorkOrder gxtWorkOrder)
    {
        Long id = gxtWorkOrder.getId();
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }

        // 仅有处理中或已接单状态才能暂停
        if (!"processing".equals(order.getWorkOrderStatus()))
        {
            throw new ServiceException("当前工单状态不允许暂停");
        }

        String oldStatus = order.getWorkOrderStatus();

        // 更新工单信息
        order.setPauseTime(DateUtils.getNowDate());
        order.setPauseReason(gxtWorkOrder.getPauseReason());
        order.setWorkOrderStatus("paused");
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

        if (result > 0)
        {
            // 记录流转
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "pause", oldStatus, "paused",
                    "暂停原因: " + gxtWorkOrder.getPauseReason());
        }

        return result;
    }

    /**
     * 继续处理工单
     *
     * @param gxtWorkOrder 工单对象，仅包含工单ID
     * @return 结果
     */
    @Override
    @Transactional
    public int resumeWorkOrder(GxtWorkOrder gxtWorkOrder) {
        Long id = gxtWorkOrder.getId();
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null) {
            throw new ServiceException("工单不存在");
        }

        String oldStatus = order.getWorkOrderStatus();

        // 更新工单信息
        order.setWorkOrderStatus(gxtWorkOrder.getWorkOrderStatus());
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

        if (result > 0) {
            // 记录流转
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "resume", oldStatus, gxtWorkOrder.getWorkOrderStatus(),
                    "恢复处理工单");

        }

        return result;
    }

    /**
     * 上传工单附件
     * 该方法不再处理文件上传，文件上传由前端调用 /common/uploads 接口处理
     * 后端仅记录文件信息到工单中
     *
     * @param orderId 工单ID
     * @param files 文件数组
     * @return 结果
     */
    @Override
    @Transactional
    public int uploadAttachments(Long orderId, List<GxtWorkOrderAttachment> files) {
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(orderId);
        if (order == null) {
            throw new ServiceException("工单不存在");
        }

        if (files == null || files.size() == 0) {
            logger.info("工单 " + order.getWorkOrderProjectNo() + " 没有文件需要上传");
            return 1; // 没有文件直接返回成功
        }

        int successCount = 0;

        for (GxtWorkOrderAttachment attachment : files) {
            if (attachment == null) {
                continue;
            }

            try {
                // 创建附件记录
//                GxtWorkOrderAttachment attachment = new GxtWorkOrderAttachment();
                attachment.setWorkOrderId(orderId);
                attachment.setWorkOrderCode(order.getWorkOrderProjectNo());
//                attachment.setFileName(file.getOriginalFilename());
//                attachment.setFileSize(file.getSize());
                // 根据文件扩展名判断文件类型
//                attachment.setFileType(getFileExtension(file.getOriginalFilename()));
                attachment.setUploadTime(DateUtils.getNowDate());
                attachment.setUploadUserId(SecurityUtils.getUserId());
                attachment.setUploadUserName(SecurityUtils.getUsername());
                attachment.setCreateBy(SecurityUtils.getUsername());
                attachment.setCreateTime(DateUtils.getNowDate());
                attachment.setRemark("上传时间：" + DateUtils.getNowDate());


                // 生成文件保存路径：/upload/gxt/工单ID/时间戳_原始文件名
//                String filePath = "/upload/gxt/" + orderId + "/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
//                attachment.setFilePath(file.getFilePath());

                // 保存附件记录
                int result = gxtWorkOrderAttachmentMapper.insertGxtWorkOrderAttachment(attachment);
                if (result > 0) {
                    successCount++;
//                    logger.info("工单 " + order.getWorkOrderProjectNo() + " 成功保存附件：" + file.getOriginalFilename());
                }
            } catch (Exception e) {
//                logger.error("保存附件失败：" + file.getOriginalFilename(), e);
//                throw new ServiceException("保存附件失败：" + file.getOriginalFilename());
            }
        }

        if (successCount > 0) {
            logger.info("工单 " + order.getWorkOrderProjectNo() + " 成功上传 " + successCount + " 个附件");
        }

        return successCount > 0 ? 1 : 0;
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName 文件名
     * @return 扩展名
     */
    private String getFileExtension(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            return "unknown";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    }

    /**
     * 导入维保工单数据
     *
     * @param workOrderList 维保工单数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importGxtWorkOrder(List<GxtWorkOrder> workOrderList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(workOrderList) || workOrderList.size() == 0)
        {
            throw new ServiceException("导入工单数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 1;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (GxtWorkOrder workOrder : workOrderList)
        {
            try
            {
                row++;
                if (StringUtils.isEmpty(workOrder.getPcsDeviceName())) {
                    throw new ServiceException("第" + row + "行风机编号不能为空！");
                }
                if (StringUtils.isEmpty(workOrder.getPcsStationName())) {
                    throw new ServiceException("第" + row + "行场站不能为空！");
                }

                SysDept dept = deptMapper.selectDeptByDeptName(workOrder.getPcsStationName());
                if (dept != null) {
                    workOrder.setPcsStationId(dept.getDeptId());
                    // 设备场站
                    if ("4".equals(dept.getLevel())) {
                        SysDept pDept = deptMapper.selectDeptById(dept.getParentId());
                        workOrder.setGxtCenterId(pDept.getParentId());
                        workOrder.setGxtCenter(pDept.getParentName());
                        workOrder.setPcsStationPid(pDept.getDeptId());
                    } else if ("3".equals(dept.getLevel())) {
//                        SysDept pDept = deptMapper.selectDeptById(dept.getDeptId());
                        workOrder.setGxtCenterId(dept.getParentId());
                        workOrder.setGxtCenter(dept.getParentName());
                        workOrder.setPcsStationPid(dept.getDeptId());
                    }
                } else {
                    throw new ServiceException("第" + row + "行该场站不存在！");
                }

                // 设置创建信息
                workOrder.setCreateBy(operName);
                workOrder.setCreateTime(DateUtils.getNowDate());
                workOrder.setWorkOrderStatus("assigned"); // 默认为待接单状态

                // 设置工单编码
                String workOrderProjectNo = getWorkOrderProjectNo();
                workOrder.setWorkOrderProjectNo(workOrderProjectNo);
                gxtWorkOrderMapper.insertGxtWorkOrder(workOrder);
                successNum++;
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、工单导入失败: ";
                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 gxtWorkOrder 保工单查询条件
     */
    private void addBusinessDataScopeFilter(GxtWorkOrder gxtWorkOrder) {
        // 获取当前登录用户
        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_work_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_work_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() + ")";
                gxtWorkOrder.getParams().put("businessDataScope", businessDataScopeSql);
            }
        }
        // 对于已作废(work_order_status = 'invalid')的工单，只有admin用户才能查看
        if (!SecurityUtils.isAdmin(currentUser.getUserId())) {
            String invalidFilterSql = " AND (t.work_order_status != 'invalid')";
            if (gxtWorkOrder.getParams().get("businessDataScope") != null) {
                String existingSql = gxtWorkOrder.getParams().get("businessDataScope").toString();
                gxtWorkOrder.getParams().put("businessDataScope", existingSql + invalidFilterSql);
            } else {
                gxtWorkOrder.getParams().put("businessDataScope", invalidFilterSql);
            }
        }
    }

    // 生成工单编号
    public String getWorkOrderProjectNo() {
        // 根据规则生成工单编码: WB+当前年月日+随机三位数
        String workOrderProjectNo;
        GxtWorkOrder existingOrder;
        int maxRetries = 100; // 最多重试100次
        int retryCount = 0;
        // 获取当前日期
        String dateStr = DateUtils.dateTime(DateUtils.getNowDate()).substring(0, 10).replace("-", ""); // YYYYMMDD
        do {
            int randomNum = (int)(Math.random() * 900); // 生成0-999之间的随机数
            String formattedNum = String.format("%03d", randomNum);
            workOrderProjectNo = "WB" + dateStr + formattedNum;
            existingOrder = gxtWorkOrderMapper.selectGxtWorkOrderByCode(workOrderProjectNo);
            retryCount++;
        } while (existingOrder != null && retryCount < maxRetries);

        if (existingOrder != null) {
            throw new ServiceException("无法生成工单编码，请稍后重试");
        }
        return workOrderProjectNo;
    }

    /**
     * 根据工单ID查询维保工单人员列表
     *
     * @param orderId 工单ID
     * @return 维保工单人员列表
     */
    @Override
    public List<GxtWorkOrderPerson> selectWorkOrderPersonListByOrderId(Long orderId) {
        GxtWorkOrderPerson person = new GxtWorkOrderPerson();
        person.setOrderId(orderId);
        return gxtWorkOrderPersonMapper.selectGxtWorkOrderPersonList(person);
    }

    /**
     * 更新维保工单人员列表
     *
     * @param personList 人员列表
     * @return 结果
     */
    @Override
    public int updateWorkOrderPersonList(List<GxtWorkOrderPerson> personList) {
        int count = 0;
        for (GxtWorkOrderPerson person : personList) {
            count += gxtWorkOrderPersonMapper.updateGxtWorkOrderPerson(person);
        }
        return count;
    }

    @Override
    public int updateGxtWorkOrderForScore(GxtWorkOrder gxtWorkOrder) {
        gxtWorkOrder.setUpdateBy(SecurityUtils.getUsername());
        gxtWorkOrder.setUpdateTime(DateUtils.getNowDate());
        return gxtWorkOrderMapper.updateGxtWorkOrder(gxtWorkOrder);
    }


    @Override
    public List<SysDept> getSummaryList(SysDept sysDept){
        addBusinessDataScopeFilter(sysDept);
        return deptMapper.getSummaryList(sysDept);
    }


    /**
     * 添加业务特定的数据权限过滤条件
     * 基于角色的数据范围进行自定义权限控制
     *
     * @param sysDept 月度工单汇总列表查询条件
     */
    private void addBusinessDataScopeFilter(SysDept sysDept) {
        // 获取当前登录用户
        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) {
            return;
        }

        // 构建业务特定的数据权限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.dept_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                            .append(String.join(",", customRoleIds))
                            .append("))")
                            .append(" OR t.parent_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                            .append(String.join(",", customRoleIds))
                            .append(")))");
                } else {
                    // 单个自定义数据权限角色查询
                    businessSql.append("(t.dept_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                            .append(role.getRoleId())
                            .append(")")
                            .append(" OR t.parent_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.dept_id = ")
                        .append(currentUser.getDeptId())
                        .append(" OR t.parent_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.dept_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.parent_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.dept_id = ")
                        .append(currentUser.getDeptId())
                        .append(" OR t.parent_id = ")
                        .append(currentUser.getDeptId())
                        .append(")");
                continue;
            }
        }
        // 如果构建了业务特定的过滤条件，则添加到查询参数中
        if (businessSql.length() > 0) {
            String businessDataScopeSql = " AND (" + businessSql.toString() + ")";
            sysDept.setDataPermission(businessDataScopeSql);
        }
    }

    /**
     * 添加业务特定的数据权限过滤条件
     * 基于角色的数据范围进行自定义权限控制
     *
     * @param orderData 首页工单列表查询条件
     */
    private void addBusinessDataScopeFilter(GxtOrderData orderData) {
        // 获取当前登录用户
        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) {
            return;
        }

        // 构建业务特定的数据权限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("(wo.pcs_station_pid IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                            .append(String.join(",", customRoleIds))
                            .append("))")
                            .append(" OR wo.pcs_station_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                            .append(String.join(",", customRoleIds))
                            .append("))")
                            .append(" OR wo.gxt_center_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                            .append(String.join(",", customRoleIds))
                            .append(")))");
                } else {
                    // 单个自定义数据权限角色查询
                    businessSql.append("(wo.pcs_station_pid IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                            .append(role.getRoleId())
                            .append(")")
                            .append(" OR wo.pcs_station_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                            .append(role.getRoleId())
                            .append(")")
                            .append(" OR wo.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("(wo.pcs_station_id = ")
                        .append(currentUser.getDeptId())
                        .append(" OR wo.pcs_station_pid = ")
                        .append(currentUser.getDeptId())
                        .append(" OR wo.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("(wo.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 wo.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 wo.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("(wo.team_leader_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR wo.assign_user_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR wo.accept_user_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR wo.id IN (SELECT order_id FROM gxt_work_order_person WHERE user_id = ")
                        .append(currentUser.getUserId())
                        .append(") ")
                        .append(" OR wo.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("(wo.team_leader_id = ")
                    .append(currentUser.getUserId())
                    .append(" OR wo.assign_user_id = ")
                    .append(currentUser.getUserId())
                    .append(" OR wo.accept_user_id = ")
                    .append(currentUser.getUserId())
                    .append(" OR wo.id IN (SELECT order_id FROM gxt_work_order_person WHERE user_id = ")
                    .append(currentUser.getUserId())
                    .append(") ")
                    .append(" OR wo.create_by = '")
                    .append(currentUser.getUserName())
                    .append("')");
        }
        // 如果构建了业务特定的过滤条件，则添加到查询参数中
        if (businessSql.length() > 0) {
            String businessDataScopeSql = " AND (" + businessSql.toString() + ")";
            orderData.setDataPermission(businessDataScopeSql);
        }
    }

    @Override
    public List<GxtOrderData> selectHomePageWorkOrderList(GxtOrderData gxtOrderData) {
        Integer workOrderFlowRecordsSize = orderPersonMapper.selectWorkOrderFlowRecordsSize();
        Integer repairOrderFlowRecordsSize = orderPersonMapper.selectRepairOrderFlowRecordsSize();
        Integer workOrderFlowRecordsSizeNext = orderPersonMapper.selectWorkOrderFlowRecordsSize();
        Integer repairOrderFlowRecordsSizeNext = orderPersonMapper.selectRepairOrderFlowRecordsSize();

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

        if (repairOrderFlowRecordsSize != null && repairOrderFlowRecordsSizeNext != null && repairOrderFlowRecordsSizeNext != repairOrderFlowRecordsSize) {
            orderPersonMapper.delRepairOrderFlowRecordsNext();
            orderPersonMapper.delRepairOrderFlowRecords();
            orderPersonMapper.addRepairOrderFlowRecords();
            orderPersonMapper.addRepairOrderFlowRecordsNext();
        }
        Long deptId = null;
        SysDept dept = deptMapper.selectDeptById(SecurityUtils.getDeptId());
        if (dept!=null && dept.getStatus().equals("0") && dept.getLevel().equals("3")) {
            deptId = dept.getDeptId();
        }else if (dept!=null && dept.getParentId()!=null){
            SysDept parentDept = deptMapper.selectDeptById(dept.getParentId());
            if (parentDept!=null && parentDept.getStatus().equals("0") && parentDept.getLevel().equals("3")) {
                deptId = parentDept.getDeptId();
            }
        }
        if (gxtOrderData!=null && (gxtOrderData.getCenter().equals("true") || gxtOrderData.getPcs().equals("true"))) {
            if (deptId!=null) {
                gxtOrderData.setCenter(null);
                gxtOrderData.setPcs("true");
                gxtOrderData.setPcsId(deptId);
            }
        }
        if (gxtOrderData.getWorkOrder() && !gxtOrderData.getRepairOrder()) {
            gxtOrderData.setOrderType("维保工单");
        } else if (!gxtOrderData.getWorkOrder() && gxtOrderData.getRepairOrder()) {
            gxtOrderData.setOrderType("维修工单");
        }
        addBusinessDataScopeFilter(gxtOrderData);
        return gxtWorkOrderMapper.selectHomePageWorkOrderList(gxtOrderData);
    }

    @Override
    public int getUnfinishedOrder() {
        int num = 0;
        GxtWorkOrder workOrder = new GxtWorkOrder();
        SysDept sysDept = deptMapper.selectDeptById(SecurityUtils.getDeptId());
        if (sysDept!=null && StringUtils.isNotEmpty(sysDept.getLevel()) && sysDept.getLevel().equals("3")) {
            workOrder.setPcsStationPid(SecurityUtils.getDeptId());
        }
        if (SecurityUtils.hasPermi("gxt:maintenance:order:assign")) {
            workOrder.setWorkOrderStatus("to_issue");
            List<GxtWorkOrder> list = gxtWorkOrderMapper.selectGxtWorkOrderList(workOrder);
            num += list.size();
        }
        if (SecurityUtils.hasPermi("gxt:maintenance:order:accept")) {
            workOrder.setWorkOrderStatus("assigned");
            List<GxtWorkOrder> list = gxtWorkOrderMapper.selectGxtWorkOrderList(workOrder);
            num += list.size();
        }
        if (SecurityUtils.hasPermi("gxt:maintenance:order:complete")) {
            workOrder.setWorkOrderStatus("to_finish");
            List<GxtWorkOrder> list = gxtWorkOrderMapper.selectGxtWorkOrderList(workOrder);
            num += list.size();
        }
        if (SecurityUtils.hasPermi("gxt:maintenance:order:approve")) {
            workOrder.setWorkOrderStatus("to_approve");
            List<GxtWorkOrder> list = gxtWorkOrderMapper.selectGxtWorkOrderList(workOrder);
            num += list.size();
        }
        return num;
    }

    public String hasCenter() {
        SysDept dept = deptMapper.selectDeptById(SecurityUtils.getDeptId());
        if (dept!=null && dept.getStatus().equals("0") && dept.getLevel().equals("3")) {
            return "no";
        }
        return "yes";
    }

    public boolean isSelect(GxtOrderData gxtOrderData) {
        if (gxtOrderData==null) {
            return false;
        }
        if ("true".equals(gxtOrderData.getCenter())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getPcs())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getCode())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getBrand())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getModel())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getSystem())) {
            return true;
        }
        if (gxtOrderData.getRepairOrder()) {
            return true;
        }
        if (gxtOrderData.getWorkOrder()) {
            return true;
        }
        if ("true".equals(gxtOrderData.getRepairPerson())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getChargePerson())) {
            return true;
        }
        if (gxtOrderData.getRepairOrderNum()!=null && gxtOrderData.getRepairOrderNum()==1) {
            return true;
        }
        if (gxtOrderData.getWorkOrderNum()!=null && gxtOrderData.getWorkOrderNum()==1) {
            return true;
        }
        if ("true".equals(gxtOrderData.getTjsc())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getXfsc())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getXysc())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getZbsc())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getClsc())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getQjbwsc())) {
            return true;
        }
        if ("true".equals(gxtOrderData.getGqsc())) {
            return true;
        }
        if (gxtOrderData.getScore()!=null && gxtOrderData.getScore().compareTo(BigDecimal.ONE)==0) {
            return true;
        }

        return false;
    }

    /**
     * 查询超时工单列表
     *
     * @param gxtWorkOrder 维保工单查询条件
     * @return 超时工单列表
     */
    @Override
    public List<GxtWorkOrder> selectOverdueWorkOrderList(GxtWorkOrder gxtWorkOrder, String keyword) {
        // 添加业务特定的数据权限过滤
        addBusinessDataScopeFilter(gxtWorkOrder);

        // 查询超时工单：realEndTime为空且当前时间超过planEndTime
        gxtWorkOrder.setParams(new HashMap<>());
        gxtWorkOrder.getParams().put("overdueCondition", "overdue");
        gxtWorkOrder.getParams().put("keyword", keyword);

        return gxtWorkOrderMapper.selectGxtWorkOrderList(gxtWorkOrder);
    }

    /**
     * 查询即将超时工单列表
     *
     * @param gxtWorkOrder 维保工单查询条件
     * @return 即将超时工单列表
     */
    @Override
    public List<GxtWorkOrder> selectAlmostOverdueWorkOrderList(GxtWorkOrder gxtWorkOrder, String keyword) {
        // 添加业务特定的数据权限过滤
        addBusinessDataScopeFilter(gxtWorkOrder);

        // 查询所有未完成的工单（realEndTime为空且planEndTime大于当前时间）
        gxtWorkOrder.setParams(new HashMap<>());
        gxtWorkOrder.getParams().put("overdueCondition", "almostOverdue");
        gxtWorkOrder.getParams().put("keyword", keyword);

        List<GxtWorkOrder> allOrders = gxtWorkOrderMapper.selectGxtWorkOrderList(gxtWorkOrder);

        // 获取超时配置
        String timeoutConfig = configService.selectConfigByKey("gxt.order.timeout");
        int timeoutHours = 24; // 默认24小时
        if (timeoutConfig != null && !timeoutConfig.isEmpty()) {
            try {
                timeoutHours = Integer.parseInt(timeoutConfig);
            } catch (NumberFormatException e) {
                // 如果配置不是有效数字，使用默认值24小时
                logger.warn("Invalid gxt.order.timeout config value: {}, using default 24 hours", timeoutConfig);
            }
        }

        // 过滤即将超时的工单
        List<GxtWorkOrder> almostOverdueOrders = new ArrayList<>();
        Date now = new Date();
        for (GxtWorkOrder order : allOrders) {
            if (order.getPlanEndTime() != null && order.getRealEndTime() == null) {
                long diffInMillies = order.getPlanEndTime().getTime() - now.getTime();
                long diffInHours = TimeUnit.HOURS.convert(diffInMillies, TimeUnit.MILLISECONDS);
                // 如果剩余时间小于等于配置的超时小时数，则认为是即将超时
                if (diffInHours <= timeoutHours && diffInHours >= 0) {
                    almostOverdueOrders.add(order);
                }
            }
        }

        return almostOverdueOrders;
    }

    /**
     * 作废维保工单
     *
     * @param gxtWorkOrder 维保工单
     * @return 结果
     */
    @Override
    @Transactional
    public int invalidateGxtWorkOrder(GxtWorkOrder gxtWorkOrder)
    {
        Long id = gxtWorkOrder.getId();
        GxtWorkOrder order = gxtWorkOrderMapper.selectGxtWorkOrderById(id);
        if (order == null)
        {
            throw new ServiceException("工单不存在");
        }

        String oldStatus = order.getWorkOrderStatus();

        // 更新工单信息
        order.setPauseTime(DateUtils.getNowDate());
        order.setInvalidReason(gxtWorkOrder.getInvalidReason());
        order.setWorkOrderStatus("invalid");
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());

        int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

        if (result > 0)
        {
            // 记录流转
            recordWorkOrderFlow(id, order.getWorkOrderProjectNo(), "invalid", oldStatus, "invalid",
                    "作废原因: " + gxtWorkOrder.getInvalidReason());
        }

        return result;
    }

    @Override
    @Transactional
    public int shutdownOrder(GxtWorkOrder gxtWorkOrder) {
        int result = gxtWorkOrderMapper.updateGxtWorkOrder(gxtWorkOrder);
        if (result > 0)
        {
            // 记录流转
            recordWorkOrderFlow(gxtWorkOrder.getId(), gxtWorkOrder.getWorkOrderProjectNo(), "shutdown", gxtWorkOrder.getWorkOrderStatus(),gxtWorkOrder.getWorkOrderStatus(),
                    null);
        }

        return result;
    }

    @Override
    public List<GxtWorkOrder> selectLatestGxtWorkOrderByDeviceId(Long pcsDeviceId, Integer limit) {
        return gxtWorkOrderMapper.selectLatestGxtWorkOrderByDeviceId(pcsDeviceId, limit);
    }
    
    @Override
    public List<GxtWorkOrder> selectGxtWorkOrderByDeviceIdWithCondition(Long pcsDeviceId, String workOrderStatus, boolean excludeStatus, String orderByField, Integer limit) {
        return gxtWorkOrderMapper.selectGxtWorkOrderByDeviceIdWithCondition(pcsDeviceId, workOrderStatus, excludeStatus, orderByField, limit);
    }
}
