package com.dashitech.callcenter.webSocket.service;

import com.dashitech.businessdata.dao.IDictionaryDAO;
import com.dashitech.businessdata.entity.DictionaryEntity;
import com.dashitech.callcenter.socket.HandlerThread;
import com.dashitech.callcenter.webSocket.core.CacheHandlerAdapter;
import com.dashitech.callcenter.webSocket.core.WebSocketSender;
import com.dashitech.utils.JsonUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.atmosphere.cache.UUIDBroadcasterCache;
import org.atmosphere.client.TrackMessageSizeInterceptor;
import org.atmosphere.config.service.WebSocketHandlerService;
import org.atmosphere.interceptor.HeartbeatInterceptor;
import org.atmosphere.util.SimpleBroadcaster;
import org.atmosphere.websocket.WebSocket;
import org.atmosphere.websocket.WebSocketProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.*;

/**
 * Created by chi on 2020/8/6.
 */

/**
 * 给前端推送消息
 */
@WebServlet(name="phoneWebSocket",urlPatterns="/webSocket")
@Service
@WebSocketHandlerService(path = "/webSocket/message/phone", interceptors = {
        TrackMessageSizeInterceptor.class,  //校验消息大小，验证数据完整性，需要前端参数配合
        HeartbeatInterceptor.class},    //保持心跳，维持链接，需要前端参数配合
        broadcaster = SimpleBroadcaster.class,  //简单广播
        broadcasterCache = UUIDBroadcasterCache.class,//加入缓存，防止消息丢失
        atmosphereConfig = {"org.atmosphere.websocket.WebSocketProtocol=org.atmosphere.websocket.protocol.StreamingHttpProtocol"})
public class PhoneWebSocket extends CacheHandlerAdapter {
    public final static WebSocketSender webSocketSender = new WebSocketSender();
    private static Log log = LogFactory.getLog(PhoneWebSocket.class);
    private static IDictionaryDAO dictionaryDAO;
    @Autowired
    public void setDictionaryDAO(IDictionaryDAO dictionaryDAO) {
        PhoneWebSocket.dictionaryDAO = dictionaryDAO;
    }

    private  static Map<String,String> phoneMap = new HashMap<>();
    private List<String> phoneChannelList = new ArrayList<>();
    private String likeName;

    @Override
    public void onByteMessage(WebSocket webSocket, byte[] data, int offset, int length) throws IOException {
        super.onByteMessage(webSocket, data, offset, length);
    }

    @Override
    public void onOpen(WebSocket webSocket) throws IOException {
        super.onOpen(webSocket);
    }

    @Override
    public void onClose(WebSocket webSocket) {
        //连接关闭同时销毁绑定话机连接
        System.out.println(likeName + "哥们被关闭了！！！");
   /*     for (String phoneChannel : phoneChannelList){
            phoneMap.remove(phoneChannel);
        }*/
        super.onClose(webSocket);
    }

    @Override
    public void onError(WebSocket webSocket, WebSocketProcessor.WebSocketException t) {
        System.out.println(likeName + "哥们报错了！！！");
        super.onError(webSocket, t);
    }

    @Override
    public void onTextMessage(WebSocket webSocket, String data) throws IOException {
        //如果没有缓存，初始化缓存
        synchronized (this) {
            if (!webSocketSender.isReady()) {
                webSocketSender.setCache(this.getCACHE());
            }
        }
    //    log.info("data:" + data);
        if(data.equals("ping")){
            webSocket.resource().getResponse().getWriter().write("pong");
            return;
        }
        JSONObject jsonObject = JsonUtil.toJSONObject(data);
        String identity = jsonObject.optString("userCount");
        String[] nameAndPhone = identity.split("\\|");
        String[] loginPhones = nameAndPhone[1].split("_");
//        System.out.println(loginPhones.length+":33333333333333333333333333");
       // List<DictionaryEntity> list = getPhoneDictionaryList("phone_num_port");
        for (String phone:loginPhones){
//            System.out.println( "777777777777777 "+ nameAndPhone[1] + " " + phone);
            //if(a[1].equals(dictionaryEntity.getName())) {
                //保存通道号，后续根据key销毁Map中的值。
            phoneChannelList.add(phone);
            phoneMap.put(phone, identity);
            //}
        }
        //通过userCount的方式确定缓存的人员
        login(webSocket.resource(),identity);
        likeName = identity;
        Map rMap=new HashMap();
        rMap.put("status",200);
        rMap.put("phone",nameAndPhone[1]);
        ObjectMapper objectMapper=new ObjectMapper();
        String json = objectMapper.writeValueAsString(rMap);
        webSocket.resource().getResponse().getWriter().write(json);
    }

    public static void sendMessage(String phone,String json) throws Exception {
        String identity = getIdentity(phone);
//        System.out.println("888888888888888888888888 " + phone + " " +  identity);
        if (identity!=null&&!identity.equals("")){
            PhoneWebSocket.webSocketSender.identityMessage(identity,json);
        }else {
//            System.out.println("这个电话没有被绑定"+new Date());
        }
    }

    public static String getIdentity(String phone){
        //System.out.println();
        for(String key : phoneMap.keySet()){
//            System.out.println("getIdentity --> phoneMap (" + key + " " + phoneMap.get(key));
        }
        if (phone!=null){
            String identity = phoneMap.get(phone);
            if(identity != null){
                return identity;
            }else{
                //System.out.println(phone);
                return null;
            }
        }
       return null;
    }

    public List<DictionaryEntity> getPhoneDictionaryList(String key){
        List<DictionaryEntity> dictionaryEntityList= dictionaryDAO.selectDictionaryByKey(key);
        return dictionaryEntityList;
    }


}
