package com.cim.idm.utils;

import com.cim.idm.framework.IDMFrameServiceProxy;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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 java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/***
 * 监听websocket地址  /myWs
 */
@ServerEndpoint("/socket/{userId}")
@Component
@Slf4j
@EnableScheduling
public class WsServerEndpoint {

	static Map<String,Session> map = new ConcurrentHashMap<String,Session>();
	/***
	 * 连接建立时执行的操作
	 * @param session
	 */
	@OnOpen
	public void onOpen(@PathParam("userId") String userId, Session session)
	{
//		map.put(session.getId(),session);
		map.put(userId,session);

		log.info("websocket is open session=" + session);
		log.info("websocket is open userId=" + userId);

	}

	/***
	 * 收到客户端消息执行的操作
	 * @param
	 */
//	@OnMessage
//	public void onMessage(byte[] message) throws IOException{
////		byte[] data = Arrays.copyOfRange(message, 50, message.length);
////		String msg = new String(data, "utf-8");
//		log.info("webSocket后台收到消息：" + msg);
//	}
	@OnMessage
	public void onMessage(String message, Session session) throws IOException {
		System.out.println("收到客户端消息：" + message);
		session.getBasicRemote().sendText("服务器收到消息：" + message);
	}

	/***
	 * 连接关闭时执行的操作
	 * @param session
	 */
	@OnClose
	public void OnClose(Session session)
	{
		map.remove(session.getId());
		log.info("连接关闭时执行的操作");
	}

	/***
	 * 向客户端发送信息
	 */
	@Scheduled(fixedRate = 300000)
	public void sendMsg() throws IOException {
//		log.info("map," + map);
		String sql = "SELECT\n" +
				"'1' RECEIVEREQUESTDETAILNAME,\n" +
				"SUM(m.REQUESTQUANTITY) REQUESTQUANTITY,\n" +
				"SUM(m.ASSIGNEDQUANTITY) RECEIVEDQUANTITY,\n" +
				"SUM(m.REQUESTQUANTITY - m.ASSIGNEDQUANTITY) AS MINUSQTY,\n" +
				"m3.DESC_CN ,\n" +
				"m.UNIT ,\n" +
				"m.SDK_ID ,\n" +
				"ss.SPECNAME ,\n" +
				"m.PHASE ,\n" +
				"m.MATERIALSPECNAME,\n" +
				"m.SITENAME,\n" +
				"m.SHIPREQUESTNAME RECEIVEREQUESTNAME,\n" +
				"be.LOCATION_USER,\n" +
				"be.ERPLOCATIONNAME,\n" +
				"m2.ERPLOCATION,\n" +
				"TO_CHAR(SYSDATE,'YYYY-MM-DD') RECEIVETIME,\n" +
				"TO_CHAR(SYSDATE,'YYYY-MM-DD') MAKEDATE\n" +
				"FROM\n" +
				"MATERIALSHIPREQUESTDETAIL m\n" +
				"LEFT JOIN MATERIALSHIPREQUEST m2 ON\n" +
				"m.SHIPREQUESTNAME = m2.SHIPREQUESTNAME\n" +
				"LEFT JOIN MATERIALSPEC m3 ON\n" +
				"m.MATERIALSPECNAME = m3.MATERIALSPECNAME\n" +
				"LEFT JOIN SDK_SPEC ss ON\n" +
				"m.SDK_ID = ss.SDK_ID\n" +
				"--\\t\\t\\t\\tLEFT JOIN SUPPLIER S ON\n" +
				"--\\t\\t\\t\\tm2.SUPPLIERNO = S.SUPPLIERNO\n" +
				"LEFT JOIN MATERIALUNIT MM ON\n" +
				"MM.FNUMBER = m.UNIT\n" +
				"LEFT JOIN BS_ERPLOCATION be ON\n" +
				"m2.ERPLOCATION = be.ERPLOCATIONNAME\n" +
				"--\\t\\t\\t\\tLEFT JOIN ORG o ON\n" +
				"--\\t\\t\\t\\to.ORGNO = m2.STOCKORGNO\n" +
				"LEFT JOIN STORAGESPEC sss ON\n" +
				"m.LOCATIONNAME = sss.STORAGENAME\n" +
				"WHERE \n" +
				"ORDERDATE >= SYSDATE - INTERVAL '5' MINUTE\n" +
				"AND m2.ERPLOCATION IS NOT NULL\n" +
				"AND be.LOCATION_USER = :LOCATION_USER\n" +
				"GROUP BY\n" +
				"m3.DESC_CN ,\n" +
				"m.UNIT ,\n" +
				"m.SDK_ID ,\n" +
				"ss.SPECNAME ,\n" +
				"m.PHASE ,\n" +
				"m.MATERIALSPECNAME,\n" +
				"m.SITENAME,\n" +
				"m.SHIPREQUESTNAME,\n" +
				"be.LOCATION_USER,\n" +
				"be.ERPLOCATIONNAME,\n" +
				"m2.ERPLOCATION";
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("LOCATION_USER", map.keySet().iterator().next());
		List<Map<String, Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", list);
		jsonObject.put("total", list.size());
		for (String key : map.keySet())
			{
				if(!list.isEmpty()) {
					map.get(key).getAsyncRemote().sendText(String.valueOf(jsonObject));
				}else {
					map.get(key).getAsyncRemote().sendText("");
				}
			}
	}
}