package com.zksy.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.api.domain.*;
import com.zksy.api.mapper.*;
import com.zksy.api.service.AlarmDataService;
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 AlarmDataServiceImpl extends ServiceImpl<AlarmDataMapper, AlarmData>
    implements AlarmDataService {

    @Autowired
    private EquipmentBaseApiMapper equipmentBaseApiMapper;

    @Autowired
    private CaseInfoApiMapper caseInfoApiMapper;

    @Autowired
    private WorkOrderApiMapper workOrderApiMapper;

    @Autowired
    private WorkOrderLogApiMapper workOrderLogApiMapper;

    /**
     * 需要同步新增案件的设备类别ID
     */
    private static final List<String> CASE_REQUIRED_TYPE_IDS = Arrays.asList("5", "9", "10");

    @Override
    public boolean saveAlarmData(AlarmData alarmData) {
        if (alarmData.getAlarmTime() == null) {
            alarmData.setAlarmTime(LocalDateTime.now());
        }
        if (alarmData.getCreateTime() == null) {
            alarmData.setCreateTime(LocalDateTime.now());
        }
        if (alarmData.getAlarmStatus() == null) {
            alarmData.setAlarmStatus(0);
        }
        boolean saved = this.save(alarmData);
        if (saved) {
            try {
                syncCreateCaseAndWorkOrder(alarmData);
            } catch (Exception e) {
                log.error("保存告警后同步创建案件/工单失败，alarmId={}", alarmData.getId(), e);
            }
        }
        return saved;
    }

    /**
     * 根据设备类别ID同步创建案件和工单
     * 1、设备类别ID为5、9、10时：同步新增案件信息 + 新增工单
     * 2、设备类别ID不为5、9、10时：仅新增工单
     */
    private void syncCreateCaseAndWorkOrder(AlarmData alarmData) {
        log.info("保存设备告警后同步创建案件和工单-入参:{}", alarmData);
        // 根据设备编码查询设备基础信息
        EquipmentBase equipmentBase = equipmentBaseApiMapper.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);

        // 告警等级映射为案件等级/工单优先级：1级->1-紧急, 2级->1-紧急, 3级->2-一般, 4级->3-低
        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); // 1-系统自动报警
            caseInfo.setCaseStatus(1); // 1-待核查
            caseInfoApiMapper.insert(caseInfo);
            log.info("同步新增案件信息成功，caseNo={}, alarmId={}", caseInfo.getCaseNo(), alarmData.getId());
        }

        // 同步新增工单
        WorkOrder workOrder = new WorkOrder();
        workOrder.setOrderNo(generateOrderNo());
        workOrder.setAlarmId(alarmData.getId());
        workOrder.setDeviceId(equipmentBase.getEquipmentId());
        workOrder.setDeviceCode(alarmData.getDeviceCode());
        workOrder.setOrderType(1); // 1-故障维修
        workOrder.setOrderLevel(orderLevel);
        workOrder.setOrderDesc(desc);
        workOrder.setOrderStatus(1); // 1-待派单
        if (caseInfo != null) {
            workOrder.setCaseId(caseInfo.getCaseId());
            workOrder.setCaseNo(caseInfo.getCaseNo());
        }
        workOrderApiMapper.insert(workOrder);
        log.info("同步新增工单成功，orderNo={}, alarmId={}", workOrder.getOrderNo(), alarmData.getId());

        // 新增工单操作日志
        WorkOrderLog workOrderLog = new WorkOrderLog();
        workOrderLog.setOrderId(workOrder.getOrderId());
        workOrderLog.setOperType(1); // 1-创建工单
        workOrderLog.setOperDesc(desc + ",系统告警自动创建工单");
        workOrderLog.setOperUserName("系统");
        workOrderLogApiMapper.insert(workOrderLog);
        log.info("同步新增工单操作日志成功，orderId={}, alarmId={}", workOrder.getOrderId(), alarmData.getId());
    }

    /**
     * 生成案件编号：CS + 年月日时分秒 + 4位随机数
     */
    public static String generateCaseNo() {
        // 1. 获取当前时间，格式化为14位年月日时分秒
        String currentDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        // 2. 生成4位随机数，不足补0
        String randomNum = String.format("%04d", new Random().nextInt(10000));
        // 3. 拼接完整编号
        return "CS" + currentDateTime + randomNum;
    }

    /**
     * 生成工单编号：WO + 年月日时分秒 + 4位随机数
     */
    public static String generateOrderNo() {
        // 1. 获取当前时间，格式化为14位年月日时分秒
        String currentDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        // 2. 生成4位随机数，不足补0
        String randomNum = String.format("%04d", new Random().nextInt(10000));
        // 3. 拼接完整编号
        return "WO" + currentDateTime + randomNum;
    }
}
