package com.zksy.base.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zksy.base.alarm.domain.AlarmData;
import com.zksy.base.domain.CaseInfo;
import com.zksy.base.domain.EquipmentBase;
import com.zksy.base.domain.WorkOrder;
import com.zksy.base.domain.WorkOrderLog;
import com.zksy.base.mapper.CaseInfoMapper;
import com.zksy.base.mapper.EquipmentBaseMapper;
import com.zksy.base.mapper.WorkOrderLogMapper;
import com.zksy.base.mapper.WorkOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Slf4j
@Service
public class DrillAlarmSyncService {

    @Autowired
    private EquipmentBaseMapper equipmentBaseMapper;
    @Autowired
    private CaseInfoMapper caseInfoMapper;
    @Autowired
    private WorkOrderMapper workOrderMapper;
    @Autowired
    private WorkOrderLogMapper workOrderLogMapper;

    private static final List<String> CASE_REQUIRED_TYPE_IDS = Arrays.asList("5", "9", "10");

    public void syncCreateCaseAndWorkOrder(AlarmData alarmData) {
        EquipmentBase equipmentBase = equipmentBaseMapper.selectOne(
                new LambdaQueryWrapper<EquipmentBase>()
                        .eq(EquipmentBase::getEquipmentCode, alarmData.getDeviceCode())
                        .last("LIMIT 1"));
        if (equipmentBase == null) {
            log.warn("未找到设备编码对应的设备信息，deviceCode={}", alarmData.getDeviceCode());
            return;
        }
        String typeId = equipmentBase.getEquipmentTypeId();
        boolean needCreateCase = CASE_REQUIRED_TYPE_IDS.contains(typeId);
        int caseLevel = alarmData.getAlarmLevel() != null ? alarmData.getAlarmLevel() : 4;
        int orderLevel = caseLevel <= 2 ? 1 : (caseLevel == 3 ? 2 : 3);
        String desc = alarmData.getWarningType() != null ? alarmData.getWarningType() : "设备告警";
        if (alarmData.getRemark() != null) {
            desc += "-" + alarmData.getRemark();
        }
        CaseInfo caseInfo = null;
        if (needCreateCase) {
            caseInfo = new CaseInfo();
            caseInfo.setCaseNo(generateCaseNo());
            caseInfo.setAlarmId(alarmData.getId());
            caseInfo.setDeviceId(equipmentBase.getEquipmentId());
            caseInfo.setDeviceCode(alarmData.getDeviceCode());
            caseInfo.setCaseLevel(caseLevel);
            caseInfo.setCaseDesc(desc);
            caseInfo.setCaseSource(1);
            caseInfo.setCaseStatus(1);
            caseInfoMapper.insert(caseInfo);
            log.info("同步新增案件信息成功，caseNo={}", caseInfo.getCaseNo());
        }
        WorkOrder workOrder = new WorkOrder();
        workOrder.setOrderNo(generateOrderNo());
        workOrder.setAlarmId(alarmData.getId());
        workOrder.setDeviceId(equipmentBase.getEquipmentId());
        workOrder.setDeviceCode(alarmData.getDeviceCode());
        workOrder.setOrderType(1);
        workOrder.setOrderLevel(orderLevel);
        workOrder.setOrderDesc(desc);
        workOrder.setCreateTime(DateUtil.date());
        workOrder.setOrderStatus(1);
        if (caseInfo != null) {
            workOrder.setCaseId(caseInfo.getCaseId());
            workOrder.setCaseNo(caseInfo.getCaseNo());
        }
        workOrderMapper.insert(workOrder);
        log.info("同步新增工单成功，orderNo={}", workOrder.getOrderNo());
        WorkOrderLog workOrderLog = new WorkOrderLog();
        workOrderLog.setOrderId(workOrder.getOrderId());
        workOrderLog.setOperType(1);
        workOrderLog.setOperDesc(desc + ",系统告警自动创建工单");
        workOrderLog.setOperUserName("系统");
        workOrderLog.setOperUserId(-1L);
        workOrderLog.setOperTime(DateUtil.date());
        workOrderLogMapper.insert(workOrderLog);
        log.info("同步新增工单操作日志成功，orderId={}", workOrder.getOrderId());
    }

    private static String generateCaseNo() {
        String dt = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        return "CS" + dt + String.format("%04d", new Random().nextInt(10000));
    }

    private static String generateOrderNo() {
        String dt = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        return "WO" + dt + String.format("%04d", new Random().nextInt(10000));
    }
}
