package com.fs.app.websocket.service;


import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fs.ai.service.IBaiduAIService;
import com.fs.ai.vo.BaiduAIMsgResultVO;
import com.fs.app.param.SopLogsEditParam;
import com.fs.app.websocket.bean.MsgBean;
import com.fs.app.websocket.bean.SendMsgVo;
import com.fs.chat.config.WxConfig;
import com.fs.chat.domain.ChatKeyword;
import com.fs.chat.domain.ChatMsg;
import com.fs.chat.domain.ChatRole;
import com.fs.chat.domain.ChatSession;
import com.fs.chat.service.IChatMsgService;
import com.fs.chat.service.IChatRoleService;
import com.fs.chat.service.IChatSessionService;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.spring.SpringUtils;

import com.fs.company.domain.CompanyUser;
import com.fs.company.domain.CompanyWxChat;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.service.ICompanyWxChatService;
import com.fs.course.domain.FsCourseSopLogs;
import com.fs.course.service.IFsCourseSopLogsService;
import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;
import com.fs.wx.kf.dto.WeixinKfImageMsgDTO;
import com.fs.wx.kf.dto.WeixinKfMsgSendDTO;
import com.fs.wx.kf.dto.WeixinKfTextMsgDTO;
import com.fs.wxUser.domain.CompanyWxUser;
import org.apache.commons.lang3.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.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static com.fs.common.constant.FsConstants.REDIS_CHAT_SESSION;

@ServerEndpoint("/app/webSocket/{uid}")
@Component
public class WebSocketServer {

    private final ICompanyWxChatService companyWxChatService = SpringUtils.getBean(ICompanyWxChatService.class);
    private final ICompanyUserService companyUserService = SpringUtils.getBean(ICompanyUserService.class);

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    protected static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();
    RedisCache redisCache=SpringUtils.getBean(RedisCache.class);
    IFsCourseSopLogsService iFsCourseSopLogsService=SpringUtils.getBean(IFsCourseSopLogsService.class);

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                System.out.println("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }
    //给指定用户发送信息
    public void sendInfo(String id, String message){
        Session session = sessionPools.get(id);
        try {
            if(session != null){
                sendMessage(session, message);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "uid") String uid){

        sessionPools.put(uid, session);

        System.out.println(uid + "加入webSocket！当前人数为" + sessionPools.size());

    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "uid") String uid){

        sessionPools.remove(uid);
        System.out.println(uid + "断开webSocket连接！当前人数为" + sessionPools.size());
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message) throws IOException{
        SendMsgVo msg = JSONObject.parseObject(message, SendMsgVo.class);
        Session session;
        System.out.println( "收到数据" + msg.getCmd());
        try {
            switch (msg.getCmd()){
                case "heartbeat":
                    session=sessionPools.get(msg.getUserId());
                    sendMessage(session, JSONObject.toJSONString(msg));
                    break;
                case "sendSop":

                    break;
                case "sendMsg":
                    CompanyWxUser companyWxUser = companyUserService.selectCompanyUserByNickName(msg.getUserId(), msg.getNickName());
                    if(companyWxUser != null){
                        saveWxChat(msg.getMsg(), companyWxUser, 1);
                    }
                    break;

            }
        }
        catch (Exception e){
            System.out.println( "收到数据" + e.getMessage());
        }

    }
    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误"+throwable.getMessage());
        throwable.printStackTrace();
    }


    public SendMsgVo saveWxChat(String msg, CompanyWxUser user, Integer sendType) {
        SendMsgVo build = SendMsgVo.builder().cmd("sendMsg").msg(msg).nickName(user.getNickName()).build();
        CompanyWxChat companyWxChat = new CompanyWxChat();
        companyWxChat.setWxUserId(user.getUserId());
        companyWxChat.setCompanyId(user.getCompanyId());
        companyWxChat.setCompanyUserId(user.getCompanyUserId());
        companyWxChat.setContent(msg);
        companyWxChat.setSendType(sendType);
        companyWxChat.setCreateTime(new Date());
        companyWxChatService.save(companyWxChat);
        return build;
    }


}
