package com.iotechn.unimall.admin.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.iotechn.unimall.core.Const;
import com.iotechn.unimall.data.domain.AdminDO;
import com.iotechn.unimall.data.domain.MessageDO;
import com.iotechn.unimall.data.domain.RoleDO;
import com.iotechn.unimall.data.mapper.AdminMapper;
import com.iotechn.unimall.data.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Component
@ServerEndpoint("/websocket/{adminId}")
@Service
//此注解相当于设置访问URL
public class WebSocket {

    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    private static RoleMapper  roleMapper;
    private static AdminMapper  adminMapper;

    @Autowired
    public void setRoleService(RoleMapper  roleMapper) {
        WebSocket.roleMapper= roleMapper;
    }

    @Autowired
    public void setAdminService(AdminMapper  adminMapper) {
        WebSocket.adminMapper= adminMapper;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam(value="adminId")String adminId) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(adminId, session);
        System.out.println("adminId = "+adminId+"【websocket消息】有新的连接，总数为:"+webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开，总数为:"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
    }

    // 此为广播消息
    public void sendAllMessage(MessageDO messageDO) {
        for(WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:"+messageDO.getCustomer()+messageDO.getOperation()+messageDO.getResult()+"$"+messageDO.getPath());
            try {
                webSocket.session.getAsyncRemote().sendText(messageDO.getCustomer()+messageDO.getOperation()+messageDO.getResult()+"$"+messageDO.getPath());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(MessageDO messageDO) {
//        sendAllMessage(messageDO);
        System.out.println("【websocket消息 : "+messageDO.getAdminId()+"】单点消息:"+messageDO.getCustomer()+messageDO.getOperation()+messageDO.getResult()+"$"+messageDO.getPath());
        Session session = sessionPool.get(messageDO.getAdminId()+"");
        if (session != null) {
            try {
//                session.getAsyncRemote().sendObject(messageDO);
//                session.getBasicRemote().sendObject(messageDO);
                session.getAsyncRemote().sendText(messageDO.getCustomer()+messageDO.getOperation()+messageDO.getResult()+"$"+messageDO.getPath());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else{
            System.out.println("【websocket消息 session is null ");
        }
    }

    // 根据角色发送消息
    public  void sendMessageByRole(MessageDO messageDO ,String role ,Long companyId){
        // 根据role 获取roleId
        List<RoleDO> roleDOs = roleMapper.selectList(new EntityWrapper<RoleDO>().like("name","%"+role+"%").eq("company_id",companyId));
        if(!CollectionUtils.isEmpty(roleDOs)){
            RoleDO roleDO = roleDOs.get(0);
            // 根据roleID  查询adminid
            List<AdminDO> adminDOList = adminMapper.selectList(new EntityWrapper<AdminDO>().eq("company_id",companyId).like("role_ids","%"+roleDO.getId()+"%"));
            if(!CollectionUtils.isEmpty(adminDOList)){
                adminDOList.forEach(adminDO -> {
                    System.out.println("【websocket消息 : "+adminDO.getId()+"】单点消息:"+messageDO.getCustomer()+messageDO.getOperation()+messageDO.getResult()+"$"+messageDO.getPath());
                    Session session = sessionPool.get(adminDO.getId()+"");
                    if (session != null) {
                        try {
                            session.getAsyncRemote().sendText(messageDO.getCustomer()+messageDO.getOperation()+messageDO.getResult()+"$"+messageDO.getPath());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    else{
                        System.out.println("【websocket消息 session is null ");
                    }
                });


            }
        }
    }

}