package com.xhpc.wxma.socket;

import com.alibaba.fastjson.JSONObject;
import com.xhpc.common.core.web.controller.BaseController;
import com.xhpc.wxma.domain.WebSocketClient;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yuyang
 * @date 2021/8/11 17:15
 */
@Component
@ServerEndpoint(value = "/websocket/{userId}")
public class OrderNotificationWebSocket extends BaseController {

    static final ConcurrentHashMap<String, List<WebSocketClient>> webSocketClientMap= new ConcurrentHashMap<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    //连接用户id
    private String userId;
    /**
     * 连接建立成功时触发，绑定参数
     * @param session 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId){
        this.userId =userId;
        this.session = session;
        WebSocketClient client = new WebSocketClient();
        client.setSession(session);
        client.setUri(session.getRequestURI().toString());

        List<WebSocketClient> webSocketClientList = webSocketClientMap.get(userId);
        if(webSocketClientList == null){
            webSocketClientList = new ArrayList<>();
        }
        webSocketClientList.add(client);
        webSocketClientMap.put(userId, webSocketClientList);
    }

    /**
     * 连接关闭时触发，注意不能向客户端发送消息了
     * @param userId
     */
    @OnClose
    public void onClose(@PathParam("userId") String userId){
        webSocketClientMap.remove(userId);
    }

    /**
     * 通信发生错误时触发
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 向客户端发送消息
     * @param userId
     * @param message
     */
    public static void sendMessage(String userId,String message){
        try {
            List<WebSocketClient> webSocketClientList = webSocketClientMap.get(userId);
            if(webSocketClientList!=null){
                for(WebSocketClient webSocketServer:webSocketClientList){
                    webSocketServer.getSession().getBasicRemote().sendText(message);
                    System.out.println("----------------------");
                    System.out.println("---------userId-------------"+userId);
                    System.out.println("---------message-------------"+message);
                    System.out.println("----------------------");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        Map<String,Object> map =new HashMap<>();
        map.put("code", 200);
        map.put("message", "实时数据");
        map.put("userId", this.userId);
        Map<String, Object> data = new HashMap<>();
        BigDecimal decimal = new BigDecimal(0);
        data.put("amountCharged",decimal);
        data.put("gunNumber","0");
        data.put("chargingOrderId",0L);
        data.put("chargingTimeNumber",0);
        data.put("soc",0);
        data.put("chargingTime","0");
        data.put("electricCurrent",decimal);
        data.put("voltage", decimal);
        data.put("power", "0");
        data.put("chargingDegree", decimal);
        data.put("remainingTime","0");
        data.put("serialNumber","0");
        data.put("parkingInstructions","充电完成请尽快离场,超时车位占用费10元/小时");
        data.put("type", "-1");
        map.put("data", data);
        JSONObject json = new JSONObject(map);
        sendMessage(this.userId,json.toString());
    }

}
