package com.usky.cdi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.usky.cdi.service.config.mqtt.MqttOutConfig;
import com.usky.cdi.service.util.SnowflakeIdGenerator;
import com.usky.cdi.service.vo.alarm.AlarmMessage1VO;
import com.usky.cdi.service.vo.alarm.AlarmMessage2VO;
import com.usky.cdi.service.vo.alarm.AlarmMessage3VO;
import com.usky.cdi.service.vo.alarm.AlarmMessageVO;
import com.usky.cdi.service.vo.base.EngineeringBaseVO;
import com.usky.cdi.service.vo.base.FloorPlaneVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * 告警类数据传输服务
 * 负责向市适配平台发送告警类数据
 *
 * @author han
 * @date 2025/12/08
 */
@Slf4j
@Service
@ConditionalOnProperty(prefix = "mqtt", value = {"enabled"}, havingValue = "true")
public class AlarmDataTransferService {

    @Resource
    private MqttOutConfig.MqttGateway mqttGateway;

    private final SnowflakeIdGenerator idGenerator;
    private final SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    public AlarmDataTransferService() {
        // 使用默认的workerId和datacenterId，实际项目中可以从配置读取
        this.idGenerator = new SnowflakeIdGenerator(1L, 1L);
    }

    /**
     * 获取当前时间字符串
     */
    private String getCurrentTime() {
        return timeFormat.format(new Date());
    }

    /**
     * 生成数据包ID
     */
    private Long generateDataPacketID() {
        return idGenerator.nextPacketId();
    }

    /**
     * 发送告警信息
     * Topic: base/floorPlane
     *
     * @param vo 楼层平面图信息
     * @return 是否发送成功
     */
    public boolean sendAlarmMessage(AlarmMessageVO vo) {
        try {
            if (vo.getDataPacketID() == null) {
                vo.setDataPacketID(generateDataPacketID());
            }
            if (vo.getPublishTime() == null) {
                vo.setPublishTime(getCurrentTime());
            }

            HashMap<String, Object> map = new HashMap<>();
//            map.put("dataPacketID", vo.getDataPacketID());
//            map.put("engineeringID", vo.getEngineeringID());
//            map.put("floor", vo.getFloor());
//            map.put("floorFileID", vo.getFloorFileID());
//            map.put("floorFileName", vo.getFloorFileName());
//            map.put("floorFileSuffix", vo.getFloorFileSuffix());
//            map.put("filePixWidth", vo.getFilePixWidth());
//            map.put("filePixHeight", vo.getFilePixHeight());
//            map.put("floorFile", imageBytes);
//            map.put("publishTime", vo.getPublishTime());
            Gson gson = new Gson();
            JSONObject jsonObject = (JSONObject) JSON.toJSON(vo);
            String json = jsonObject.toJSONString();
            System.out.println(json);
            String topic = "alarm/message";
            mqttGateway.sendToMqtt(topic, json);

            return true;
        } catch (Exception e) {
            log.error("发送告警信息失败，AlarmID: {}", vo.getAlarmID(), e);
            return false;
        }
    }

    /**
     * 发送告警信息
     * Topic: base/floorPlane
     *
     * @param vo 楼层平面图信息
     * @return 是否发送成功
     */
    public boolean sendAlarmMessage1(AlarmMessage1VO vo) {
        try {
            if (vo.getDataPacketID() == null) {
                vo.setDataPacketID(generateDataPacketID());
            }
            if (vo.getPublishTime() == null) {
                vo.setPublishTime(getCurrentTime());
            }

            HashMap<String, Object> map = new HashMap<>();
//            map.put("dataPacketID", vo.getDataPacketID());
//            map.put("engineeringID", vo.getEngineeringID());
//            map.put("floor", vo.getFloor());
//            map.put("floorFileID", vo.getFloorFileID());
//            map.put("floorFileName", vo.getFloorFileName());
//            map.put("floorFileSuffix", vo.getFloorFileSuffix());
//            map.put("filePixWidth", vo.getFilePixWidth());
//            map.put("filePixHeight", vo.getFilePixHeight());
//            map.put("floorFile", imageBytes);
//            map.put("publishTime", vo.getPublishTime());
            Gson gson = new Gson();
            JSONObject jsonObject = (JSONObject) JSON.toJSON(vo);
            String json = jsonObject.toJSONString();
            System.out.println(json);
            String topic = "alarm/message";
            mqttGateway.sendToMqtt(topic, json);

            return true;
        } catch (Exception e) {
            log.error("发送告警信息失败，AlarmID: {}", vo.getAlarmID(), e);
            return false;
        }
    }

    public boolean sendAlarmMessage2(AlarmMessage2VO vo) {
        try {
            if (vo.getDataPacketID() == null) {
                vo.setDataPacketID(generateDataPacketID());
            }
            if (vo.getPublishTime() == null) {
                vo.setPublishTime(getCurrentTime());
            }

            JSONObject jsonObject = (JSONObject) JSON.toJSON(vo);
            String json = jsonObject.toJSONString();
            System.out.println(json);
            String topic = "alarm/message";
            mqttGateway.sendToMqtt(topic, json);

            return true;
        } catch (Exception e) {
            log.error("发送告警信息失败，AlarmID: {}", vo.getAlarmID(), e);
            return false;
        }
    }

    public boolean sendEngineeringBase(AlarmMessage3VO vo) {
        try {
            if (vo.getDataPacketID() == null) {
                vo.setDataPacketID(generateDataPacketID());
            }
            if (vo.getPublishTime() == null) {
                vo.setPublishTime(getCurrentTime());
            }

            JSONObject jsonObject = (JSONObject) JSON.toJSON(vo);
            String json = jsonObject.toJSONString();
            String topic = "alarm/message";
            System.out.println("推送的数据: " + json);
            mqttGateway.sendToMqtt(topic, json);

            return true;
        } catch (Exception e) {
            log.error("发送电流告警信息失败，EngineeringID: {}", vo.getEngineeringID(), e);
            return false;
        }
    }
}
