package com.sqx.modules.gameChat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sqx.modules.gameChat.entity.ChatContentTcwm;
import com.sqx.modules.gameChat.service.ChatContentTcwmService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * WebSocket聊天实现  游戏聊天
 */
@Component
@ServerEndpoint("/ordersChat/{ordersId}")
@Slf4j
public class OrdersChatSocket {
    /**
     * 在线人数
     */
    public static int onlineNumber = 0;
    /**
     * userId作为key
     */
    private static Map<Long, CopyOnWriteArraySet<OrdersChatSocket>> clients = new HashMap<Long, CopyOnWriteArraySet<OrdersChatSocket>>();
    /**
     * 会话
     */
    private Session session;
    /**
     * 订单id
     */
    private Long ordersId;

    private static ChatContentTcwmService chatContentTcwmService;


    @Autowired
    public void setChatContentTcwmService(ChatContentTcwmService chatContentService) {
        OrdersChatSocket.chatContentTcwmService = chatContentService;
    }


    /**
     * 建立连接
     *
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("ordersId") Long ordersId, Session session) {
        onlineNumber++;
        this.ordersId = ordersId;
        log.info("聊天室id:"+ordersId);

        this.session = session;
        log.info("有新连接加入！ 当前在线人数" + onlineNumber);
        /*try {*/
            CopyOnWriteArraySet<OrdersChatSocket> friends = clients.get(ordersId);
            if (friends == null) {
                synchronized (clients) {
                    if (!clients.containsKey(ordersId)) {
                        friends = new CopyOnWriteArraySet<>();
                        clients.put(ordersId, friends);
                    }
                }
            }
            friends.add(this);

        /*} catch (Exception e) {
            log.info(e.getMessage());
            log.info(userId + "上线的时候通知所有人发生了错误");
        }*/
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.info("服务端发生了错误" + error.getMessage());
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        onlineNumber--;
        CopyOnWriteArraySet<OrdersChatSocket> friends = clients.get(ordersId);
        if (friends != null) {
            friends.remove(this);
        }
        log.info("有连接关闭！ 当前在线人数" + onlineNumber);
    }

    /**
     * 接收客户端的消息，并把消息发送给所有连接的会话
     */
    @OnMessage
    public void onMessage(String message) {
        try {
            //解析聊天内容
            JSONObject jsonObject = JSON.parseObject(message);
            String type = jsonObject.getString("messageType");
            String content = jsonObject.getString("content");
            String userId = jsonObject.getString("userId");
            String shopId = jsonObject.getString("shopId");
            String riderId = jsonObject.getString("riderId");
            String ordersId = jsonObject.getString("ordersId");
            //聊天记录
            ChatContentTcwm chatContentTcwm = new ChatContentTcwm();
            chatContentTcwm.setContent(content);
            chatContentTcwm.setMessageType(Integer.valueOf(type));
            if(StringUtils.isNotEmpty(userId) && !"null".equals(userId)){
                chatContentTcwm.setUserId(Long.valueOf(userId));
                chatContentTcwm.setShopStatus(0);
                chatContentTcwm.setRiderStatus(0);
                chatContentTcwm.setUserStatus(1);
            }
            if(StringUtils.isNotEmpty(shopId) && !"null".equals(shopId)){
                chatContentTcwm.setShopId(Long.valueOf(shopId));
                chatContentTcwm.setShopStatus(1);
                chatContentTcwm.setRiderStatus(0);
                chatContentTcwm.setUserStatus(0);
            }
            if(StringUtils.isNotEmpty(riderId) && !"null".equals(riderId)){
                chatContentTcwm.setRiderId((Long.valueOf(riderId)));
                chatContentTcwm.setShopStatus(0);
                chatContentTcwm.setRiderStatus(1);
                chatContentTcwm.setUserStatus(0);
            }
            chatContentTcwm.setShopStatus(0);
            chatContentTcwm.setRiderStatus(0);
            chatContentTcwm.setUserStatus(0);
            chatContentTcwm.setOrdersId(Long.valueOf(ordersId));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            chatContentTcwm.setCreateTime(sdf.format(new Date())); //创建时间
            chatContentTcwmService.save(chatContentTcwm);
            CopyOnWriteArraySet<OrdersChatSocket> friends = clients.get(Long.valueOf(ordersId));
            if (friends != null) {
                for (OrdersChatSocket item : friends) {
                    item.session.getAsyncRemote().sendText(message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("发生了错误了");
        }
    }



}
