package com.xzzn.ems.service.impl;

import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.xzzn.common.utils.DateUtils;
import com.xzzn.common.utils.StringUtils;
import com.xzzn.ems.domain.EmsSiteSetting;
import com.xzzn.ems.mapper.EmsSiteSettingMapper;
import com.xzzn.ems.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xzzn.ems.mapper.MqttSyncLogMapper;
import com.xzzn.ems.domain.MqttSyncLog;

/**
 * MQTT云上本地同步日志Service业务层处理
 *
 * @author xzzn
 * @date 2025-11-12
 */
@Service
public class MqttSyncLogServiceImpl implements IMqttSyncLogService
{
    @Autowired
    private MqttSyncLogMapper mqttSyncLogMapper;
    @Autowired
    private IEmsFaultProtectionPlanService emsFaultProtectionPlanService;
    @Autowired
    private IEmsStrategyService emsStrategyService;
    @Autowired
    private IEmsAlarmRecordsService emsAlarmRecordsService;
    @Autowired
    private EmsSiteSettingMapper emsSiteSettingMapper;
    @Autowired
    private IEmsFaultIssueLogService emsFaultIssueLogService;
    @Autowired
    private IEmsDeviceChangeLogService emsDeviceChangeLogService;
    @Autowired
    private IEmsStrategyTempService emsStrategyTempService;
    @Autowired
    private IEmsStrategyTimeConfigService emsStrategyTimeConfigService;

    /**
     * 查询MQTT云上本地同步日志
     *
     * @param id MQTT云上本地同步日志主键
     * @return MQTT云上本地同步日志
     */
    @Override
    public MqttSyncLog selectMqttSyncLogById(Long id)
    {
        return mqttSyncLogMapper.selectMqttSyncLogById(id);
    }

    /**
     * 查询MQTT云上本地同步日志列表
     *
     * @param mqttSyncLog MQTT云上本地同步日志
     * @return MQTT云上本地同步日志
     */
    @Override
    public List<MqttSyncLog> selectMqttSyncLogList(MqttSyncLog mqttSyncLog)
    {
        return mqttSyncLogMapper.selectMqttSyncLogList(mqttSyncLog);
    }

    /**
     * 新增MQTT云上本地同步日志
     *
     * @param mqttSyncLog MQTT云上本地同步日志
     * @return 结果
     */
    @Override
    public int insertMqttSyncLog(MqttSyncLog mqttSyncLog)
    {
        mqttSyncLog.setCreateTime(DateUtils.getNowDate());
        return mqttSyncLogMapper.insertMqttSyncLog(mqttSyncLog);
    }

    /**
     * 修改MQTT云上本地同步日志
     *
     * @param mqttSyncLog MQTT云上本地同步日志
     * @return 结果
     */
    @Override
    public int updateMqttSyncLog(MqttSyncLog mqttSyncLog)
    {
        return mqttSyncLogMapper.updateMqttSyncLog(mqttSyncLog);
    }

    /**
     * 批量删除MQTT云上本地同步日志
     *
     * @param ids 需要删除的MQTT云上本地同步日志主键
     * @return 结果
     */
    @Override
    public int deleteMqttSyncLogByIds(Long[] ids)
    {
        return mqttSyncLogMapper.deleteMqttSyncLogByIds(ids);
    }

    /**
     * 删除MQTT云上本地同步日志信息
     *
     * @param id MQTT云上本地同步日志主键
     * @return 结果
     */
    @Override
    public int deleteMqttSyncLogById(Long id)
    {
        return mqttSyncLogMapper.deleteMqttSyncLogById(id);
    }

    // 校验同步目标是否该站点
    private boolean checkIsSite(String target) {
        if (StringUtils.isEmpty(target)) {
            return false;
        }
        EmsSiteSetting emsSiteSetting = emsSiteSettingMapper.selectEmsSiteSettingBySiteId(target);
        if (emsSiteSetting == null) {
            return false;
        }
        return true;
    }

    /**
     * 处理云上运行策略数据
     * 云上-本地：校验是否该站点
     * @param payload
     */
    @Override
    public void handleMqttStrategyData(String payload) {
        MqttSyncLog syncLog = JSON.parseObject(payload, MqttSyncLog.class);
        if (syncLog != null) {
            // 校验是否该站点数据
            if (!checkIsSite(syncLog.getTarget())) {
                return;
            }
            // 校验是否存在
            String syncId = syncLog.getSyncId();
            MqttSyncLog existLog = mqttSyncLogMapper.selectMqttSyncLogBySyncId(syncId);
            if (existLog == null) {
                try {
                    // 根据不同操作更新
                    String operateType = syncLog.getOperateType();
                    if (!StringUtils.isEmpty(operateType)) {
                        // 不同表操作
                        String tableName = syncLog.getTableName();
                        switch (tableName) {
                            case "ems_strategy_running":
                                emsStrategyService.dealStrategyRunningData(syncLog.getContent(), operateType);
                                break;
                            case "ems_strategy_temp":
                                emsStrategyTempService.dealStrategyTempData(syncLog.getContent(), operateType);
                                break;
                            case "ems_strategy_time_config":
                                emsStrategyTimeConfigService.dealStrategyTimeData(syncLog.getContent(), operateType);
                                break;
                            default:
                                break;
                        }
                    }
                } catch (Exception e) {
                    syncLog.setStatus("FAIL");
                    syncLog.setErrorMsg(e.getMessage());
                }
                // 保存日志
                insertMqttSyncLog(syncLog);
            }
        }
    }

    /**
     * 处理云上同步的告警保护信息
     * 云上-本地：校验是否该站点
     * @param payload
     */
    @Override
    public void handleMqttPlanData(String payload) {
        MqttSyncLog planLog = JSON.parseObject(payload, MqttSyncLog.class);
        if (planLog != null) {
            // 校验是否该站点数据
            if (!checkIsSite(planLog.getTarget())) {
                return;
            }

            // 校验是否存在
            String syncId = planLog.getSyncId();
            MqttSyncLog existLog = mqttSyncLogMapper.selectMqttSyncLogBySyncId(syncId);
            if (existLog == null) {
                // 处理数据
                String operateType = planLog.getOperateType();
                if (!StringUtils.isEmpty(operateType)) {
                    emsFaultProtectionPlanService.dealSyncData(planLog.getContent(), operateType);
                }

                // 保存日志
                insertMqttSyncLog(planLog);
            }
        }

    }

    /**
     * 处理设备保护策略触发的告警信息
     * 本地-云上
     * @param payload
     */
    @Override
    public void handleFaultAlarmData(String payload) {
        MqttSyncLog syncLog = JSON.parseObject(payload, MqttSyncLog.class);
        if (syncLog != null) {
            // 校验是否存在
            String syncId = syncLog.getSyncId();
            MqttSyncLog existLog = mqttSyncLogMapper.selectMqttSyncLogBySyncId(syncId);
            if (existLog == null) {
                // 根据不同操作更新
                String operateType = syncLog.getOperateType();
                if (!StringUtils.isEmpty(operateType)) {
                    emsAlarmRecordsService.dealSyncData(syncLog.getContent(),operateType);
                }

                // 保存日志
                insertMqttSyncLog(syncLog);
            }
        }
    }

    /**
     * 处理保护策略告警信息
     * 本地-云上
     * @param payload
     */
    @Override
    public void handleFaultPlanIssueData(String payload) {
        MqttSyncLog syncLog = JSON.parseObject(payload, MqttSyncLog.class);
        if (syncLog != null) {
            // 校验是否存在
            String syncId = syncLog.getSyncId();
            MqttSyncLog existLog = mqttSyncLogMapper.selectMqttSyncLogBySyncId(syncId);
            if (existLog == null) {
                // 根据不同操作更新
                String operateType = syncLog.getOperateType();
                if (!StringUtils.isEmpty(operateType)) {
                    emsFaultIssueLogService.dealSyncData(syncLog.getContent(),operateType);
                }

                // 保存日志
                insertMqttSyncLog(syncLog);
            }
        }
    }
    /**
     * 处理设备运行状态变更日志
     * 本地-云上
     * @param payload
     */
    @Override
    public void handleDeviceChangeLogData(String payload) {
        MqttSyncLog syncLog = JSON.parseObject(payload, MqttSyncLog.class);
        if (syncLog == null) {
            // 校验是否存在
            String syncId = syncLog.getSyncId();
            MqttSyncLog existLog = mqttSyncLogMapper.selectMqttSyncLogBySyncId(syncId);
            if (existLog == null) {
                // 根据不同操作更新
                String operateType = syncLog.getOperateType();
                if (!StringUtils.isEmpty(operateType)) {
                    emsDeviceChangeLogService.dealSyncData(syncLog.getContent(),operateType);
                }

                // 保存日志
                insertMqttSyncLog(syncLog);
            }
        }
    }
}
