package com.ag.web.websocket;

import cn.hutool.core.collection.CollUtil;
import com.ag.log.RemqMsgCustom;
import com.ag.log.service.impl.RemqMsgCustomServiceImpl;
import com.ag.web.websocket.service.AgSktService;
import com.ag.web.websocket.service.topic.RedisTopicService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wb.util.SysUtil;
import com.wb.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;

@Controller
@RequestMapping("/sktmq")
public class AgWebSocketControl {
    private static final Logger logger = LoggerFactory.getLogger(AgWebSocketControl.class);
    @Autowired
    private AgSktService sktService;
    @Autowired
    private RemqMsgCustomServiceImpl remqMsgCustomService;

    private ExecutorService threads;

    /**
     *  向前台推送消息发送消息
     */
    @ResponseBody
    @RequestMapping(value = "/sendMq", method = {RequestMethod.POST})
    public void shakeHandler(@RequestBody JSONObject jsonObject) {
        logger.info("开始推送"+jsonObject.toJSONString());

        RemqMsgCustom msg= JSON.parseObject(jsonObject.getString("msg"), RemqMsgCustom.class);
        List<String> userList= JSONArray.parseArray(jsonObject.getString("userList"),String.class);
        if (!CollUtil.isEmpty(userList)){
            threads=newFixedThreadPool(5);
            threads.execute(()->{
                for (String userId:userList) {
                    msg.setSrFlag("R");
                    msg.setParentId(msg.getId());
                    msg.setId(SysUtil.getId());
                    msg.setReUserId(userId);
                    sktService.sendMsgToUser(userId,msg);
                }
            });
            threads.shutdown();
        }else {
            logger.info("无人订阅");
        }
    }

    public static void main(String[] args) {
        ExecutorService threads=newFixedThreadPool(5);
        for (int i = 0; i < 1001; i++) {
           // threads.execute(()->{logger.info("第"+i+"个")});
            int finalI = i;
            threads.execute(() -> {
               logger.info("第"+finalI+"个");
            });
        }
        threads.shutdown();
    }

    /**
     * 查询未读消息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryCountNoRd", method = {RequestMethod.POST}, produces = "text/html;charset=UTF-8;")
    public void queryCountNoRd(HttpServletRequest request, HttpServletResponse response) {
        String user=String.valueOf(request.getSession().getAttribute("sys.user"));
        int counRdt= remqMsgCustomService.queryNoRead(user);
        try {
            WebUtil.send(response, counRdt);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 标记已读消息
     *
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/markMsg", method = {RequestMethod.POST}, produces = "text/html;charset=UTF-8;")
    public String markMsg(HttpServletRequest request,HttpServletResponse response) {
        try {
            List<String> idList = RedisTopicService.idList(request.getParameter("dataArray"));

            if (CollUtil.isNotEmpty(idList)){
                remqMsgCustomService.markMsg(idList);
            }
            return "成功";
        }catch (Exception e){
            return e.getLocalizedMessage();
        }

    }
}