package com.inspect.mqtt.services;

import com.inspect.base.redis.service.RedisService;
import com.inspect.mqtt.IMQTTUtil;
import com.inspect.partrolresult.mapper.PatrolResultMapper;
import com.inspect.task.service.IPatrolTaskService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Service;

@Service
public class SendHeartServerImpl implements ISendHeartServer {
    private final IMQTTUtil mqttUtil;
    private final PatrolResultMapper patrolResultMapper;
    private final IPatrolTaskService patrolTaskService;
    private final RedisService redisService;

    public SendHeartServerImpl(IMQTTUtil mqttUtil, PatrolResultMapper patrolResultMapper, IPatrolTaskService patrolTaskService, RedisService redisService) {
        this.mqttUtil = mqttUtil;
        this.patrolResultMapper = patrolResultMapper;
        this.patrolTaskService = patrolTaskService;
        this.redisService = redisService;
    }

    public void sendHeart() {
        String stationIp = this.patrolTaskService.selectConfigByKey("MAJOR_URL");
        String node_id = "";
        Map<String, String> stringMap = this.patrolResultMapper.selectBasedataStation();
        if (stringMap != null) {
            if (stringMap.get("node_id") != null) {
                node_id = stringMap.get("node_id");
            }

            String volt_level = "";
            if (stringMap.get("volt_level") != null) {
                volt_level = stringMap.get("volt_level");
            } else {
                volt_level = "500";
            }

            String province_name = stringMap.get("province_name");
            String city_name = stringMap.get("city_name");
            String station_name = stringMap.get("station_name");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = sdf.format(new Date());
            if (!redisService.hasKey("PATROL_TASK_MQTT_HEARTBEAT")) {
                System.out.println("<===HEARTBEAT===>\n{\n   \"province_name\":\"" + province_name + ",\"\n   \"city_name\":\"" + city_name + "\",\n   \"volt_level\":" + volt_level + ",\n   \"station_name\":\"" + station_name + "\",\n   \"station_ip\":\"" + stationIp + "\",\n   \"node_id\":\"" + node_id + "\",\n   \"msg_type\":\"heart\",\n   \"time\":\"" + date + "\"\n}\n");
                redisService.setCacheObject("PATROL_TASK_MQTT_HEARTBEAT", 1, 30L, TimeUnit.MINUTES);
            }

            mqttUtil.publish2(1, "nodes/java/user/heartbeat/1", "{\n   \"province_name\":\"" + province_name + ",\"\n   \"city_name\":\"" + city_name + "\",\n   \"volt_level\":" + volt_level + ",\n   \"station_name\":\"" + station_name + "\",\n   \"station_ip\":\"" + stationIp + "\",\n   \"node_id\":\"" + node_id + "\",\n   \"msg_type\":\"heart\",\n   \"time\":\"" + date + "\"\n}\n");
        }
    }
}
