package com.xzzn.framework.aspectj;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xzzn.common.utils.StringUtils;
import com.xzzn.ems.domain.EmsDeviceChangeLog;
import com.xzzn.ems.domain.MqttSyncLog;
import com.xzzn.ems.mapper.EmsMqttTopicConfigMapper;
import com.xzzn.ems.mapper.MqttSyncLogMapper;
import com.xzzn.framework.web.service.MqttPublisher;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

/**
 * 设备运行状态变更日志同步
 * 本地 - 云端
 */
@Aspect
@Component
public class DeviceChangeLogAspect {

    private static final Log logger = LogFactory.getLog(DeviceChangeLogAspect.class);
    @Autowired
    private MqttPublisher mqttPublisher;

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final String MQTT_TOPIC = "DEVICE_CHANGE_LOG_UP";
    private static final String TABLE_NAME = "ems_device_change_log";
    @Autowired
    private MqttSyncLogMapper mqttSyncLogMapper;
    @Autowired
    private EmsMqttTopicConfigMapper emsMqttTopicConfigMapper;

    // 定义切点：拦截策略相关表的Mapper方法
    @Pointcut("(execution(* com.xzzn.ems.mapper.EmsDeviceChangeLogMapper.insertEmsDeviceChangeLog(..)) &&  args(insertEntity)) ")
    public void insertPointCut(EmsDeviceChangeLog insertEntity) {
        logger.info("【新增设备运行状态变更日志】DeviceChangeLogAspect 实例化");
    }

    // 方法执行成功后发布同步消息
    @AfterReturning(pointcut = "insertPointCut(insertEntity)", returning = "result")
    public void afterInsert(JoinPoint joinPoint, EmsDeviceChangeLog insertEntity, Integer result) {
        logger.info("【新增设备运行状态变更日志下发数据切面进入成功】");
        if (result == 0 || insertEntity == null) {
            return;
        }

        // 校验是否配置监听topic-监听则不发布
        String topic = emsMqttTopicConfigMapper.checkTopicIsExist(MQTT_TOPIC);
        if (!StringUtils.isEmpty(topic)) {
            return;
        }

        // 解析方法名，获取操作类型（INSERT/UPDATE/DELETE）和表名
        String operateType = "INSERT";
        String siteId = insertEntity.getSiteId();

        // 构建日志同步消息
        MqttSyncLog message = createMessageObject(operateType,siteId);

        try {
            // 数据转换
            String content = objectMapper.writeValueAsString(insertEntity);
            message.setContent(content);

            // mqtt同步到云端
            mqttPublisher.publish(MQTT_TOPIC, objectMapper.writeValueAsString(message), 1);
        } catch (Exception e) {
            message.setStatus("FAIL");
            message.setErrorMsg(e.getMessage());
        }
        // 存储同步信息
        mqttSyncLogMapper.insertMqttSyncLog(message);
    }

    // 构建同步信息
    private MqttSyncLog createMessageObject(String operateType, String siteId) {
        MqttSyncLog message = new MqttSyncLog();
        message.setSyncId(UUID.randomUUID().toString());
        message.setOperateType(operateType);
        message.setTableName(TABLE_NAME);
        message.setCreateTime(new Date());
        message.setTopic(MQTT_TOPIC);
        message.setStatus("SUCCESS");
        message.setSyncObject(siteId);
        message.setTarget("CLOUD");
        return message;
    }
}