package com.junmp.jyzb.websocket;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.junmp.iot.server.ws.WebSocketServerListener;
import com.junmp.iot.server.ws.impl.DefaultWebSocketServerProtocol;
import com.junmp.junmpProcess.redis.FlowRedisCache;
import com.junmp.jyzb.api.util.WsCabinetReq;
import com.junmp.jyzb.api.util.WsWarehouseReq;
import com.junmp.jyzb.cache.DeviceRedisCache;
import com.junmp.jyzb.cache.OnlineRedisCache;
import com.junmp.jyzb.entity.Cabinet;
import com.junmp.jyzb.entity.CabinetBox;
import com.junmp.jyzb.entity.Temp.OnlineState;
import com.junmp.jyzb.service.CabinetService;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.v2.ws.api.enums.ClientMsgType;
import com.junmp.v2.ws.api.enums.ServerMsgType;
import com.junmp.v2.ws.api.enums.SysMsgTypeEnum;
import com.junmp.v2.ws.api.message.WsCallbackApi;
import com.junmp.v2.ws.api.session.bean.WsSession;
import com.junmp.v2.ws.bean.WsMsgDto;
import com.junmp.v2.ws.channel.WsSessionContainer;
import com.junmp.v2.ws.message.WsMessageHandle;
import com.junmp.v2.ws.session.WsSessionHandle;
import io.jsonwebtoken.JwtException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;


@Component
@Slf4j
public class WarehouseWebSocketServer implements WebSocketServerListener {
//    private static final Logger log = LoggerFactory.getLogger(com.junmp.v2.ws.server.ScreenWebSocketServer.class);
    @Resource
    public CabinetService cabinetService;
    @Resource
    private DeviceRedisCache redisCache;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RabbitAdmin rabbitAdmin;

    @Override
    public String uri() {
        return "/device/ws";
    }

    @SneakyThrows
    @Override
    public void onText(DefaultWebSocketServerProtocol protocol) {
        try {


            String text = protocol.readText();
            ObjectMapper objectMapper = new ObjectMapper();
            WsWarehouseReq deviceData = objectMapper.readValue(text, WsWarehouseReq.class);
            String orgId = deviceData.getOrgId();
            String redisExist= redisCache.get(orgId);

            if(redisExist!=null)//已有存在数据
            {

                String jsonData = objectMapper.writeValueAsString(deviceData);
                redisCache.put(orgId, jsonData);
            }
            else
            {
                String channel =  protocol.requestMessage().getChannelId();
                String jsonData = objectMapper.writeValueAsString(deviceData);
                redisCache.put(orgId, jsonData);
                redisCache.put(channel, orgId);
            }
            //推送消息到对应组织机构
            TopicExchange exchange = new TopicExchange("DevMonitorMsg");
            rabbitAdmin.declareExchange(exchange);
            String exchangeName="DevMonitorMsg";
            rabbitTemplate.convertAndSend(exchangeName, orgId, "设备上线");
            protocol.response("true");
        }
        catch (Exception e)
        {
            protocol.response("false");
        }
    }
    @Override
    public void onClose(DefaultWebSocketServerProtocol protocol) {

        String channel= protocol.requestMessage().getChannelId();
        String orgId= redisCache.get(channel);
        redisCache.remove(channel);
        redisCache.remove(orgId);
        //将消息推到对应组织机构
        TopicExchange exchange = new TopicExchange("DevMonitorMsg");
        String exchangeName="DevMonitorMsg";
        rabbitAdmin.declareExchange(exchange);
        rabbitTemplate.convertAndSend(exchangeName, orgId, "设备下线");
        WebSocketServerListener.super.onClose(protocol);
    }

    @Override
    public void onBinary(DefaultWebSocketServerProtocol protocol) {
        WebSocketServerListener.super.onBinary(protocol);
    }



}