package com.ygtx.gxt.task;

import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.gxt.domain.*;
import com.ygtx.gxt.mapper.*;
import com.ygtx.gxt.mapper.source.GxtMisInfoMapper;
import com.ygtx.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 工单自动结单任务
 * @author lingma
 */
@EnableScheduling
@Component("autoFinalizeTask")
public class OrderAutoFinalizeTask {

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

    @Autowired
    private GxtRepairOrderMapper gxtRepairOrderMapper;

    @Autowired
    private GxtWorkOrderMapper gxtWorkOrderMapper;

    @Autowired
    private GxtWorkOrderFlowMapper gxtWorkOrderFlowMapper;

    @Autowired
    private GxtRepairOrderFlowMapper gxtRepairOrderFlowMapper;

    @Autowired
    private GxtMisInfoMapper misInfoMapper;

    @Autowired
    private GxtOrderPersonMapper orderPersonMapper;

    @Autowired
    private GxtRepairOrderPersonMapper repairOrderPersonMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private GxtWorkOrderPersonMapper workOrderPersonMapper;

    /**
     * 每小时执行定时任务
     * 查找状态为assigned或to_finish且接单时间、停机时间、恢复运行时间不为空的工单
     */
    public void finalizeOrders() {
        log.info("开始执行工单自动结单任务");
        
        // 查询维修工单 - 状态为assigned或to_finish，且接单时间、停机时间、恢复运行时间不为空
        GxtRepairOrder gxtRepairOrder = new GxtRepairOrder();
        gxtRepairOrder.setWorkOrderStatus("assigned,to_finish");
        gxtRepairOrder.setOrderEntryType("1");
        List<GxtRepairOrder> repairOrderList = gxtRepairOrderMapper.selectGxtRepairOrderListForAutoFinalize(gxtRepairOrder);
        
        // 更新维修工单状态为完成
        GxtRepairOrder updateRepairOrder = new GxtRepairOrder();
        updateRepairOrder.setWorkOrderStatus("completed");
        updateRepairOrder.setUpdateTime(DateUtils.getNowDate());
        updateRepairOrder.setUpdateBy("admin");

        for (GxtRepairOrder repairOrder : repairOrderList) {
            // 关联查询MIS工单信息
            GxtMisInfo misInfo = new GxtMisInfo();
            misInfo.setPcsStationName(repairOrder.getPcsStationName());
            misInfo.setPcsDeviceName(repairOrder.getPcsDeviceName());
            misInfo.setPauseTime(repairOrder.getOccurTime());
            misInfo.setRestartTime(repairOrder.getRestartTime());
            misInfo.setWorkOrderStatus("结束");
            List<GxtMisInfo> misInfoList = misInfoMapper.selectAutoGxtMisInfoList(misInfo);
            
            GxtMisInfo validMisInfo = null;
            List<GxtWorkOrderPerson> personList = null;
            // 如果查询出的misInfoList大于1，则不执行后续操作
            if (misInfoList != null && misInfoList.size() == 1) {
                GxtMisInfo mis = misInfoList.get(0);
                if (mis.getWorkPermitNum() != null && !mis.getWorkPermitNum().isEmpty()) {
                    // 检查该MIS工单是否已在维修工单或维保工单中存在
                    boolean misExistsInOrders = checkMisExistsInOrders(mis.getMisNo());
                    
                    if (!misExistsInOrders) {
                        // 查询工作负责人和工作组成员信息
                        GxtWorkOrderPerson workOrderPerson = new GxtWorkOrderPerson();
                        workOrderPerson.setMisNo(mis.getMisNo());
                        personList = misInfoMapper.selectGxtWorkOrderPersonList(workOrderPerson);
                        
                        if (personList != null && !personList.isEmpty()) {
                            boolean hasLeader = false;
                            boolean hasMembers = false;
                            
                            for (GxtWorkOrderPerson person : personList) {
                                if (person.getIsLeader() != null && 1 == person.getIsLeader()) {
                                    hasLeader = true;
                                } else {
                                    hasMembers = true;
                                }
                            }
                            
                            if (hasLeader) {
                                validMisInfo = mis;
                            }
                        }
                    }
                }
            }
            
            // 如果存在有效MIS工单信息，则更新工单状态为已完成
            if (validMisInfo != null && personList != null && !personList.isEmpty()) {
                // 检查是否同时存在工作负责人和工作组成员
                boolean hasLeaderCheck = false;
                boolean hasMembersCheck = false;
                for (GxtWorkOrderPerson person : personList) {
                    if (person.getIsLeader() != null && 1 == person.getIsLeader()) {
                        hasLeaderCheck = true;
                    } else {
                        hasMembersCheck = true;
                    }
                }
                
                if (hasLeaderCheck) {
                    updateRepairOrder.setId(repairOrder.getId());
                    updateRepairOrder.setWorkPermitNum(validMisInfo.getWorkPermitNum());
                    
                    StringBuilder members = new StringBuilder();
                    String leader = null;
                    Long leaderUserId = null;
                    
                    for (GxtWorkOrderPerson person : personList) {
                        if (person.getIsLeader() != null && 1 == person.getIsLeader()) {
                            leader = person.getNickName();
                            // 查询工作负责人的ID
                            SysUser queryUser = new SysUser();
                            queryUser.setUserName(person.getUserName());
                            queryUser.setNickName(person.getNickName());
                            List<SysUser> users = sysUserMapper.selectUserList(queryUser);
                            if (users != null && !users.isEmpty()) {
                                leaderUserId = users.get(0).getUserId();
                            }
                            continue;
                        }
                        if (members.length() > 0) {
                            members.append(",");
                        }
                        members.append(person.getNickName());
                    }

                    updateRepairOrder.setMisOrderNo(validMisInfo.getMisNo());
                    updateRepairOrder.setTeamLeaderName(leader);
                    updateRepairOrder.setTeamLeaderId(leaderUserId); // 设置工作负责人ID
                    updateRepairOrder.setWorkGroupMemberName(members.toString());
                    updateRepairOrder.setRealStartTime(validMisInfo.getRealStartTime());
                    updateRepairOrder.setRealEndTime(validMisInfo.getRealEndTime());
                    updateRepairOrder.setInfoEntry("1");
                    updateRepairOrder.setFinalizeMethod("1");
                    updateRepairOrder.setScoringStatus("to_self");
                    updateRepairOrder.setRepairMethod("1");

                    gxtRepairOrderMapper.updateGxtRepairOrder(updateRepairOrder);
                    
                    // 将工作负责人和工作组成员存入GxtWorkOrderPersonMapper
                    // 先删除该工单原有的工作组员信息
                    repairOrderPersonMapper.deleteGxtRepairOrderPersonByOrderId(repairOrder.getId());
                    
                    for (GxtWorkOrderPerson person : personList) {
                        // 查询系统中对应的人员ID，同时使用用户名和昵称查询
                        SysUser queryUser = new SysUser();
                        queryUser.setUserName(person.getUserName());
                        queryUser.setNickName(person.getNickName());
                        List<SysUser> users = sysUserMapper.selectUserList(queryUser);
                        SysUser sysUser = null;
                        if (users != null && !users.isEmpty()) {
                            sysUser = users.get(0); // 使用第一个匹配的用户
                        }
                        
                        GxtRepairOrderPerson newPerson = new GxtRepairOrderPerson();
                        newPerson.setOrderId(repairOrder.getId());
                        newPerson.setOrderCode(repairOrder.getWorkOrderProjectNo());
                        newPerson.setNickName(person.getNickName());
                        newPerson.setUserName(person.getUserName());
                        newPerson.setIsLeader(person.getIsLeader());
                        // 设置用户ID，如果找不到则设为null
                        newPerson.setUserId(sysUser != null ? sysUser.getUserId() : null);
                        newPerson.setCreateBy("admin");
                        newPerson.setCreateTime(DateUtils.getNowDate());
                        newPerson.setUpdateBy("admin");
                        newPerson.setUpdateTime(DateUtils.getNowDate());
                        newPerson.setStatus(1);
                        repairOrderPersonMapper.insertGxtRepairOrderPerson(newPerson);
                    }

                    GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
                    flow.setOrderId(repairOrder.getId());
                    flow.setOrderCode(repairOrder.getWorkOrderProjectNo());
                    flow.setActionType("auto_finalize");
                    flow.setFromStatus(repairOrder.getWorkOrderStatus());
                    flow.setToStatus(updateRepairOrder.getWorkOrderStatus());
                    flow.setOperatorId(1L);
                    flow.setOperatorName("系统");
                    flow.setActionTime(DateUtils.getNowDate());
                    flow.setCreateBy("admin");
                    flow.setCreateTime(DateUtils.getNowDate());
                    gxtRepairOrderFlowMapper.insertGxtRepairOrderFlow(flow);
                }
            }
        }

        // 查询维保工单 - 状态为assigned或to_finish，且接单时间、停机时间、恢复运行时间不为空
        GxtWorkOrder gxtWorkOrder = new GxtWorkOrder();
        gxtWorkOrder.setWorkOrderStatus("assigned,to_finish");
        gxtWorkOrder.setOrderEntryType("1");
        List<GxtWorkOrder> workOrderList = gxtWorkOrderMapper.selectGxtWorkOrderListForAutoFinalize(gxtWorkOrder);
        
        // 更新维保工单状态为完成
        GxtWorkOrder updateWorkOrder = new GxtWorkOrder();
        updateWorkOrder.setWorkOrderStatus("completed");
        updateWorkOrder.setUpdateTime(DateUtils.getNowDate());
        updateWorkOrder.setUpdateBy("admin");

        for (GxtWorkOrder workOrder : workOrderList) {
            // 关联查询MIS工单信息
            GxtMisInfo misInfo = new GxtMisInfo();
            misInfo.setPcsStationName(workOrder.getPcsStationName());
            misInfo.setPcsDeviceName(workOrder.getPcsDeviceName());
            misInfo.setPauseTime(workOrder.getPauseTime());
            misInfo.setRestartTime(workOrder.getRestartTime());
            misInfo.setWorkOrderStatus("结束");
            List<GxtMisInfo> misInfoList = misInfoMapper.selectAutoGxtMisInfoList(misInfo);
            
            GxtMisInfo validMisInfo = null;
            List<GxtWorkOrderPerson> personList = null;
            // 如果查询出的misInfoList大于1，则不执行后续操作
            if (misInfoList != null && misInfoList.size() == 1) {
                GxtMisInfo mis = misInfoList.get(0);
                if (mis.getWorkPermitNum() != null && !mis.getWorkPermitNum().isEmpty()) {
                    // 检查该MIS工单是否已在维修工单或维保工单中存在
                    boolean misExistsInOrders = checkMisExistsInOrders(mis.getMisNo());
                    
                    if (!misExistsInOrders) {
                        // 查询工作负责人和工作组成员信息
                        GxtWorkOrderPerson workOrderPerson = new GxtWorkOrderPerson();
                        workOrderPerson.setMisNo(mis.getMisNo());
                        personList = misInfoMapper.selectGxtWorkOrderPersonList(workOrderPerson);
                        
                        if (personList != null && !personList.isEmpty()) {
                            boolean hasLeader = false;
                            boolean hasMembers = false;
                            
                            for (GxtWorkOrderPerson person : personList) {
                                if (person.getIsLeader() != null && 1 == person.getIsLeader()) {
                                    hasLeader = true;
                                } else {
                                    hasMembers = true;
                                }
                            }
                            
                            if (hasLeader) {
                                validMisInfo = mis;
                            }
                        }
                    }
                }
            }
            
            // 如果存在有效MIS工单信息，则更新工单状态为已完成
            if (validMisInfo != null && personList != null && !personList.isEmpty()) {
                // 检查是否同时存在工作负责人和工作组成员
                boolean hasLeaderCheck = false;
                boolean hasMembersCheck = false;
                for (GxtWorkOrderPerson person : personList) {
                    if (person.getIsLeader() != null && 1 == person.getIsLeader()) {
                        hasLeaderCheck = true;
                    } else {
                        hasMembersCheck = true;
                    }
                }
                
                if (hasLeaderCheck) {
                    updateWorkOrder.setId(workOrder.getId());
                    updateWorkOrder.setWorkPermitNum(validMisInfo.getWorkPermitNum());
                    
                    StringBuilder members = new StringBuilder();
                    String leader = null;
                    Long leaderUserId = null;
                    
                    for (GxtWorkOrderPerson person : personList) {
                        if (person.getIsLeader() != null && 1 == person.getIsLeader()) {
                            leader = person.getNickName();
                            // 查询工作负责人的ID
                            SysUser queryUser = new SysUser();
                            queryUser.setUserName(person.getUserName());
                            queryUser.setNickName(person.getNickName());
                            List<SysUser> users = sysUserMapper.selectUserList(queryUser);
                            if (users != null && !users.isEmpty()) {
                                leaderUserId = users.get(0).getUserId();
                            }
                            continue;
                        }
                        if (members.length() > 0) {
                            members.append(",");
                        }
                        members.append(person.getNickName());
                    }

                    updateWorkOrder.setMisNo(validMisInfo.getMisNo());
                    updateWorkOrder.setTeamLeaderName(leader);
                    updateWorkOrder.setTeamLeaderId(leaderUserId); // 设置工作负责人ID
                    updateWorkOrder.setWorkGroupMemberName(members.toString());
                    updateWorkOrder.setRealStartTime(validMisInfo.getRealStartTime());
                    updateWorkOrder.setRealEndTime(validMisInfo.getRealEndTime());
                    updateWorkOrder.setInfoEntry("1");
                    updateWorkOrder.setFinalizeMethod("1");
                    updateWorkOrder.setScoringStatus("to_self");
                    updateWorkOrder.setCompleteTime(DateUtils.getNowDate());
                    
                    gxtWorkOrderMapper.updateGxtWorkOrder(updateWorkOrder);
                    
                    // 将工作负责人和工作组成员存入GxtWorkOrderPersonMapper
                    // 先删除该工单原有的工作组员信息
                    workOrderPersonMapper.deleteGxtWorkOrderPersonByOrderId(workOrder.getId());
                    
                    for (GxtWorkOrderPerson person : personList) {
                        // 查询系统中对应的人员ID，同时使用用户名和昵称查询
                        SysUser queryUser = new SysUser();
                        queryUser.setUserName(person.getUserName());
                        queryUser.setNickName(person.getNickName());
                        List<SysUser> users = sysUserMapper.selectUserList(queryUser);
                        SysUser sysUser = null;
                        if (users != null && !users.isEmpty()) {
                            sysUser = users.get(0); // 使用第一个匹配的用户
                        }
                        
                        GxtWorkOrderPerson newPerson = new GxtWorkOrderPerson();
                        newPerson.setOrderId(workOrder.getId());
                        newPerson.setOrderCode(workOrder.getWorkOrderProjectNo());
                        newPerson.setMisNo(person.getMisNo());
                        newPerson.setNickName(person.getNickName());
                        newPerson.setUserName(person.getUserName());
                        newPerson.setIsLeader(person.getIsLeader());
                        // 设置用户ID，如果找不到则设为null
                        newPerson.setUserId(sysUser != null ? sysUser.getUserId() : null);
                        newPerson.setCreateBy("admin");
                        newPerson.setCreateTime(DateUtils.getNowDate());
                        newPerson.setUpdateBy("admin");
                        newPerson.setUpdateTime(DateUtils.getNowDate());
                        newPerson.setStatus(1);
                        workOrderPersonMapper.insertGxtWorkOrderPerson(newPerson);
                    }

                    GxtWorkOrderFlow flow = new GxtWorkOrderFlow();
                    flow.setOrderId(workOrder.getId());
                    flow.setOrderCode(workOrder.getWorkOrderProjectNo());
                    flow.setActionType("auto_finalize");
                    flow.setFromStatus(workOrder.getWorkOrderStatus());
                    flow.setToStatus(updateWorkOrder.getWorkOrderStatus());
                    flow.setOperatorId(1L);
                    flow.setOperatorName("系统");
                    flow.setActionTime(DateUtils.getNowDate());
                    flow.setCreateBy("admin");
                    flow.setCreateTime(DateUtils.getNowDate());
                    gxtWorkOrderFlowMapper.insertGxtWorkOrderFlow(flow);
                }
            }
        }
    }
    
    /**
     * 检查MIS工单是否已在维修工单或维保工单中存在
     * @param misNo MIS工单编号
     * @return 如果MIS工单已存在返回true，否则返回false
     */
    private boolean checkMisExistsInOrders(String misNo) {
        // 检查维修工单中是否已存在该MIS工单号（排除当前工单）
        GxtRepairOrder repairOrderCriteria = new GxtRepairOrder();
        repairOrderCriteria.setMisOrderNo(misNo);
        List<GxtRepairOrder> existingRepairOrders = gxtRepairOrderMapper.selectGxtRepairOrderList(repairOrderCriteria);
        
        // 如果查询到结果，且存在非排除ID的记录，则返回true
        if (existingRepairOrders != null && !existingRepairOrders.isEmpty()) {
            return true;
        }
        
        // 检查维保工单中是否已存在该MIS工单号（排除当前工单）
        GxtWorkOrder workOrderCriteria = new GxtWorkOrder();
        workOrderCriteria.setMisNo(misNo);
        List<GxtWorkOrder> existingWorkOrders = gxtWorkOrderMapper.selectGxtWorkOrderList(workOrderCriteria);
        
        // 如果查询到结果，且存在非排除ID的记录，则返回true
        if (existingWorkOrders != null && !existingWorkOrders.isEmpty()) {
            return true;
        }
        
        // 如果都没有找到符合条件的记录，则返回false
        return false;
    }
}
