package com.inspect.metadata.montdatamqhandle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inspect.base.core.constant.Color;
import com.inspect.metadata.eqpbook.domain.BasedataEqpBook;
import com.inspect.metadata.eqpbook.domain.BasedataEqpBookChannel;
import com.inspect.metadata.eqpbook.domain.vo.BasedataEqpBookChannelQueryVo;
import com.inspect.metadata.eqpbook.mapper.BasedataEqpBookChannelMapper;
import com.inspect.metadata.eqpbook.service.IBasedataEqpBookService;
import com.inspect.metadata.montdata.domain.BasedataMontPatDevOnline;
import com.inspect.metadata.montdata.service.IBasedataMontPatDevOnlineService;
import com.inspect.metadata.montdatamqhandle.service.IBasedataMontDataHandleService;
import com.inspect.base.websocket.configure.WsPool;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.HttpClientUtils;
import com.inspect.base.core.utils.ip.IpUtils;
import com.inspect.base.redis.service.RedisService;

import java.util.Date;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component("basedataMont-heartbeat")
public class BasedataMontHeartBeatConsumerHandle implements IBasedataMontDataHandleService {
    @Resource
    private IBasedataEqpBookService basedataEqpBookService;
    @Resource
    private RedisService redisService;
    @Resource
    IBasedataMontPatDevOnlineService basedataMontPatDevOnlineService;
    @Resource
    BasedataEqpBookChannelMapper basedataEqpbookChannelMapper;
    @Value("${liveSIPB.url}")
    private String liveSIPB_URL;

    public void handleMontData(JSONObject jsonObject) {
        log.info("handleMontData-heartbeat: {}", jsonObject.toString());
        String Type = jsonObject.getString("Type");
        String uuid = jsonObject.getString("uuid");
        log.info("[METADATA] handMontData 会话: {}, 类型: {}, 消息体: {}", uuid, Type, jsonObject.toJSONString());

        String SendCode = jsonObject.getString("SendCode");
        if (null != SendCode && !SendCode.isEmpty()) {
            if ("nvrGwbMedia".equals(SendCode)) {
                this.ipcNvrOnlineStatusHandle(jsonObject);
            } else {
                this.robotVavOnlineStatusHandle(SendCode, jsonObject);
            }

        }
    }

    public void robotVavOnlineStatusHandle(String SendCode, JSONObject jsonObject) {
        BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
        basedataEqpbook.setMainSystemCode(SendCode);

        String Type = jsonObject.getString("Type");
        String uuid = jsonObject.getString("uuid");
        log.info("[METADATA] handMontData 会话: {}, 类型: {}, 消息体: {}, 台账: {}", uuid, Type, jsonObject.toJSONString(), basedataEqpbook);

        List<BasedataEqpBook> eqpBooks = this.basedataEqpBookService.selectBasedataEqpBookList(basedataEqpbook);
        if (null != eqpBooks && !eqpBooks.isEmpty()) {
            for (BasedataEqpBook book : eqpBooks) {
                String patrolDeviceCode = book.getPatrolDeviceCode();
                Long eqpBookId = book.getEqpBookId();
                int heartFromTcpServer = jsonObject.getInteger("HeartBeatInterval");
                int heartBeatInterval = (int) Math.floor((double) heartFromTcpServer * 120D);
                Date nowTime = DateUtils.getNowDate();
                this.patrolDeviceOnlineHandle(patrolDeviceCode, eqpBookId, heartFromTcpServer, heartBeatInterval, nowTime);
            }
        } else {
            basedataEqpBookService.insertBasedataEqpBook(basedataEqpbook);
        }
    }

    public void ipcNvrOnlineStatusHandle(JSONObject jsonObject) {
        String patrolDeviceCode = jsonObject.getString("patroldevice_code");
        int heart_beat_interval = jsonObject.getInteger("heartBeatInterval") == null ? 60 : jsonObject.getInteger("heart_beat_interval").intValue();
        Date nowTime = DateUtils.getNowDate();
        int heartBeatInterval = (int) Math.floor((double) heart_beat_interval * 1.5D);
        this.patrolDeviceOnlineHandle(patrolDeviceCode, null, heart_beat_interval, heartBeatInterval, nowTime);
        if (this.redisService.hasKey("basedata_eqpbook_info:" + patrolDeviceCode)) {
            JSONObject jObject = this.redisService.getCacheObject("basedata_eqpbook_info:" + patrolDeviceCode);
            if (null != jObject) {
                String type = jObject.getString("type");
                String patroldeviceCode = null;
                if ("11".equals(type)) {
                    patroldeviceCode = jObject.getString("patroldeviceCode");
                }

                if (null != patroldeviceCode && !patroldeviceCode.isEmpty()) {
                    this.queryPatrolEqpChannelFromGwbMedia(patroldeviceCode, heart_beat_interval, heartBeatInterval, nowTime);
                }
            }
        }

    }

    public void patrolDeviceOnlineHandle(String patrolDeviceCode, Long eqpBookId, int heart_beat_interval, int heartBeatInterval, Date nowTime) {
        Boolean hasKey = this.redisService.hasKey("mont_patrol_device_online_status:" + patrolDeviceCode);
        if (!hasKey) {
            String dateTimeNowFormat = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, nowTime);
            JSONObject returnJsonObject = new JSONObject();
            returnJsonObject.put("patroldeviceCode", patrolDeviceCode);
            returnJsonObject.put("heartBeatInterval", heart_beat_interval);
            returnJsonObject.put("patroldeviceOnlineStatus", "1");
            returnJsonObject.put("heart_beat_time", dateTimeNowFormat);
            returnJsonObject.put("receiveTime", dateTimeNowFormat);
            returnJsonObject.put("event", "mont/montHeartBeatData");
            String jsonString = JSON.toJSONString(returnJsonObject);
            this.addBasedataMontPatDevOnline(patrolDeviceCode, eqpBookId, nowTime);
            this.redisService.setCacheObject("mont_patrol_device_online_status:" + patrolDeviceCode, returnJsonObject);
            this.redisService.expire("mont_patrol_device_online_status:" + patrolDeviceCode, (long) heartBeatInterval);
            this.parseMessage(jsonString);
        } else {
            this.redisService.expire("mont_patrol_device_online_status:" + patrolDeviceCode, (long) heartBeatInterval);
        }

    }

    public void parseMessage(String order) {
        WsPool.sendMessageToAll(order);
    }

    private void addBasedataMontPatDevOnline(String patrolDeviceCode, Long eqpBookId, Date nowTime) {
        BasedataMontPatDevOnline patDevOnline = new BasedataMontPatDevOnline();
        BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
        basedataEqpbook.setPatrolDeviceCode(patrolDeviceCode);
        if (null == eqpBookId) {
            List<BasedataEqpBook> eqpBooks = this.basedataEqpBookService.selectBasedataEqpBookList(basedataEqpbook);
            if (null != eqpBooks && !eqpBooks.isEmpty()) {
                patDevOnline.setEqpBookId(eqpBooks.get(0).getEqpBookId());
            }
        } else {
            patDevOnline.setEqpBookId(eqpBookId);
        }

        patDevOnline.setPatrolDeviceCode(patrolDeviceCode);
        patDevOnline.setStatus("1");
        patDevOnline.setActionTime(nowTime);
        patDevOnline.setOnlineTime(nowTime);
        patDevOnline.setCreateTime(nowTime);
        patDevOnline.setCreateBy("sys");
        patDevOnline.setUpdateBy(IpUtils.getHostIp());
        this.basedataMontPatDevOnlineService.insertBasedataMontPatDevOnline(patDevOnline);
    }

    public void queryPatrolEqpChannelFromGwbMedia(String patrolDeviceCode, int heart_beat_interval, int heartBeatInterval, Date nowTime) {
        String url = this.liveSIPB_URL + "/api/v1/device/channellist";

        try {
            String result = HttpClientUtils.get(url, "serial=" + patrolDeviceCode);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (null == jsonObject) {
                return;
            }

            JSONArray jsonArray = jsonObject.getJSONArray("ChannelList");
            if (null == jsonArray) {
                return;
            }

            for (int i = 0; i < jsonArray.size(); ++i) {
                JSONObject item = jsonArray.getJSONObject(i);
                String channelCode = item.getString("ID");
                String channelName = item.getString("Name");
                String DeviceID = item.getString("DeviceID");
                Boolean isOnline = item.getBoolean("DeviceOnline");
                if (null != channelName && !channelName.isEmpty() && isOnline) {
                    BasedataEqpBookChannelQueryVo channelQueryVo = new BasedataEqpBookChannelQueryVo();
                    channelQueryVo.setChannelCode(channelCode);
                    channelQueryVo.setVideoNvrCode(patrolDeviceCode);
                    List<BasedataEqpBookChannel> eqpbookList = this.basedataEqpbookChannelMapper.getChannelByEqpBookByVideoNvrCode(channelQueryVo);
                    if (null != eqpbookList && !eqpbookList.isEmpty()) {
                        BasedataEqpBookChannel basedataEqpbookChannel = eqpbookList.get(0);
                        String eqpBookPatrolDeviceCode = basedataEqpbookChannel.getPatrolDeviceCode();
                        Long eqpBookId = basedataEqpbookChannel.getEqpBookId();
                        this.patrolDeviceOnlineHandle(eqpBookPatrolDeviceCode, eqpBookId, heart_beat_interval, heartBeatInterval, nowTime);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
