package com.ygtx.gxt.task;

import com.ygtx.common.core.domain.entity.SysDept;
import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.gxt.domain.*;
import com.ygtx.gxt.mapper.*;
import com.ygtx.gxt.mapper.source.GxtMisInfoMapper;
import com.ygtx.gxt.service.IGxtFaultCodesService;
import com.ygtx.gxt.service.IGxtRepairOrderService;
import com.ygtx.system.mapper.SysUserMapper;
import com.ygtx.system.service.ISysDeptService;
import com.ygtx.system.service.impl.SysDeptServiceImpl;
import com.ygtx.system.strategy.AutoCodeUtil;
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.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 工单自动生成
 * @author lingma
 */
@EnableScheduling
@Component("autoCreateTask")
public class OrderAutoCreateTask {

    private static final Logger log = LoggerFactory.getLogger(OrderAutoCreateTask.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;

    @Autowired
    private IGxtRepairOrderService gxtRepairOrderService;

    @Autowired
    private IGxtFaultCodesService gxtFaultCodesService;

    @Autowired
    private com.ygtx.gxt.mapper.source.GxtShutdownRecordMapper gxtShutdownRecordMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private GxtEquipmentMapper gxtEquipmentMapper;

    @Autowired
    private AutoCodeUtil autoCodeUtil;


    /**
     * 每小时执行定时任务
     * 查找状态为assigned或to_finish且接单时间、停机时间、恢复运行时间不为空的工单
     */
    public void autoCreateOrders() {
        log.info("开始执行工单自动创建");
        
        // 构建查询条件
        GxtShutdownRecord queryParam = new GxtShutdownRecord();
        // 设置监控状态筛选条件，支持多个状态，逗号分隔
         queryParam.setMonitorStatusName("其他停机,风机故障,网侧故障,异常状态");
        
        // 查询前一天的停机记录数据
        List<GxtShutdownRecord> repairShutdownRecords = gxtShutdownRecordMapper.selectShutdownRecordsByDate(queryParam);
        
        if (repairShutdownRecords != null && !repairShutdownRecords.isEmpty()) {
            log.info("查询到前一天的维修停机记录数据，共 {} 条", repairShutdownRecords.size());
            
            // 遍历停机记录，进行后续处理
            for (GxtShutdownRecord record : repairShutdownRecords) {
                String stationName = record.getStationName();
                // 根据站名查询场站信息
                SysDept dept = sysDeptService.selectDeptByDeptName(stationName);
                GxtRepairOrder gxtRepairOrder = new GxtRepairOrder();
                if (dept != null) {
                    gxtRepairOrder.setPcsStationId(dept.getDeptId());
                    gxtRepairOrder.setPcsStationName(stationName);
                    if ("4".equals(dept.getLevel())) {
                        SysDept pDept = sysDeptService.selectDeptById(dept.getParentId());
                        gxtRepairOrder.setGxtCenterId(pDept.getParentId());
                        gxtRepairOrder.setGxtCenter(pDept.getParentName());
                        gxtRepairOrder.setPcsStationPid(pDept.getDeptId());
                    } else if ("3".equals(dept.getLevel())) {
                        gxtRepairOrder.setGxtCenterId(dept.getParentId());
                        gxtRepairOrder.setGxtCenter(dept.getParentName());
                        gxtRepairOrder.setPcsStationPid(dept.getDeptId());
                    }
                }

                // 根据风机编号查设备信息
                GxtEquipment equipmentParam = new GxtEquipment();
                equipmentParam.setEquipmentCode(record.getTurbineName());
                equipmentParam.setStation(stationName);
                List<GxtEquipment> equipments = gxtEquipmentMapper.selectGxtEquipmentList(equipmentParam);
                if (equipments != null && !equipments.isEmpty()) {
                    gxtRepairOrder.setPcsDeviceId(equipments.get(0).getEquipmentId());
                    gxtRepairOrder.setPcsDeviceName(equipments.get(0).getEquipmentCode());
                    gxtRepairOrder.setModel(equipments.get(0).getModel());
                    gxtRepairOrder.setBrand(equipments.get(0).getBrand());
                }

                // 故障信息解析
                ParseResult result1 = parse(record.getDowntimeDesc());
                gxtRepairOrder.setFaultBarcode(result1.getDesc());
                gxtRepairOrder.setFaultCode(result1.getCode());

                gxtRepairOrder.setOrderType(1L);
                gxtRepairOrder.setWorkOrderStatus("to_issue");
                gxtRepairOrder.setCreateBy("admin");
                gxtRepairOrder.setCreateTime(DateUtils.getNowDate());
                gxtRepairOrder.setUpdateTime(DateUtils.getNowDate());
                gxtRepairOrder.setOcccurTime(record.getStartTime());
                // 生成工单编码
                String workOrderNo = autoCodeUtil.genSerialCode("REPAIR_ORDER_CODE", "", gxtRepairOrder);
                gxtRepairOrder.setWorkOrderProjectNo(workOrderNo);
                int result = gxtRepairOrderMapper.insertGxtRepairOrder(gxtRepairOrder);
                if (result > 0) {
                    GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
                    flow.setOrderId(gxtRepairOrder.getId());
                    flow.setOrderCode(gxtRepairOrder.getWorkOrderProjectNo());
                    flow.setActionType("create");
                    flow.setToStatus("to_issue");
                    flow.setOperatorId(1L);
                    flow.setOperatorName("系统");
                    flow.setActionTime(DateUtils.getNowDate());
                    flow.setCreateBy("admin");
                    flow.setCreateTime(DateUtils.getNowDate());
                    gxtRepairOrderFlowMapper.insertGxtRepairOrderFlow(flow);
                }
            }
        } else {
            log.info("未查询到前一天的维修停机记录数据");
        }

        // 设置监控状态筛选条件，支持多个状态，逗号分隔
        queryParam.setMonitorStatusName("维护停机");

        // 查询前一天的停机记录数据
        List<GxtShutdownRecord> workShutdownRecords = gxtShutdownRecordMapper.selectShutdownRecordsByDate(queryParam);
        if (workShutdownRecords != null && !workShutdownRecords.isEmpty()) {
            log.info("查询到前一天的维保停机记录数据，共 {} 条", workShutdownRecords.size());
            // 遍历停机记录，进行后续处理
            for (GxtShutdownRecord record : workShutdownRecords) {
                String stationName = record.getStationName();
                // 根据站名查询场站信息
                SysDept dept = sysDeptService.selectDeptByDeptName(stationName);
                GxtWorkOrder gxtWorkOrder = new GxtWorkOrder();
                if (dept != null) {
                    gxtWorkOrder.setPcsStationId(dept.getDeptId());
                    gxtWorkOrder.setPcsStationName(stationName);
                    if ("4".equals(dept.getLevel())) {
                        SysDept pDept = sysDeptService.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());
                    }
                }

                // 根据风机编号查设备信息
                GxtEquipment equipmentParam = new GxtEquipment();
                equipmentParam.setEquipmentCode(record.getTurbineName());
                equipmentParam.setStation(stationName);
//                equipmentParam.setMaintenanceCenter(dept.getParentName());
                List<GxtEquipment> equipments = gxtEquipmentMapper.selectGxtEquipmentList(equipmentParam);
                if (equipments != null && !equipments.isEmpty()) {
                    gxtWorkOrder.setPcsDeviceId(equipments.get(0).getEquipmentId());
                    gxtWorkOrder.setPcsDeviceName(equipments.get(0).getEquipmentCode());
                    gxtWorkOrder.setModel(equipments.get(0).getModel());
                    gxtWorkOrder.setBrand(equipments.get(0).getBrand());
                }

                gxtWorkOrder.setOrderType(2L);
                gxtWorkOrder.setWorkOrderStatus("to_issue");
                gxtWorkOrder.setCreateBy("admin");
                gxtWorkOrder.setCreateTime(DateUtils.getNowDate());
                gxtWorkOrder.setUpdateTime(DateUtils.getNowDate());
                // 生成工单编码
                String workOrderNo = autoCodeUtil.genSerialCode("WORK_ORDER_CODE", "", gxtWorkOrder);
                gxtWorkOrder.setWorkOrderProjectNo(workOrderNo);
                gxtWorkOrderMapper.insertGxtWorkOrder(gxtWorkOrder);
                GxtWorkOrderFlow flow = new GxtWorkOrderFlow();
                flow.setOrderId(gxtWorkOrder.getId());
                flow.setOrderCode(gxtWorkOrder.getWorkOrderProjectNo());
                flow.setActionType("create");
                flow.setToStatus("to_issue");
                flow.setOperatorId(1L);
                flow.setOperatorName("系统");
                flow.setActionTime(DateUtils.getNowDate());
                flow.setCreateBy("admin");
                flow.setCreateTime(DateUtils.getNowDate());
                gxtWorkOrderFlowMapper.insertGxtWorkOrderFlow(flow);
            }
        } else {
            log.info("未查询到前一天的维保停机记录数据");
        }
    }
    
    /**

     */
    private static ParseResult parse(String text) {
        System.out.println("===== 解析：" + text);

        // 正则兼容：有数字 / 无数字
        Pattern pattern = Pattern.compile("\\((故障|告警)\\)(\\d+)?\\s*(.+)");
        Matcher m = pattern.matcher(text);

        if (m.find()) {
            String type = m.group(1);       // 故障 / 告警
            String code = m.group(2);       // 可能为 null
            String desc = m.group(3).trim(); // 描述
            return new ParseResult(code, desc);
        }
        // 解析失败返回空
        return new ParseResult(null, text);
    }

    // 解析结果对象：返回 code 和 desc
    public static class ParseResult {
        private String code;  // 故障代码（可能为null/无）
        private String desc;  // 故障描述

        // 构造、getter
        public ParseResult(String code, String desc) {
            this.code = code;
            this.desc = desc;
        }

        public String getCode() {
            return code;
        }

        public String getDesc() {
            return desc;
        }
    }
}
