package org.jeecg.modules.nettyServer.controller;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.AllArgsConstructor;
import jtznyj.common.api.vo.AFocusWarn;
import org.jeecg.modules.dataVue.service.IAFocusWarnService;
import org.jeecg.modules.nettyServer.domain.SocketBody;
import org.jeecg.modules.nettyServer.service.PushMessageService;
import org.jeecg.modules.nettyServer.store.ChannelStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 首页
 *
 * @author cn2008tv
 */
@RestController
@RequestMapping("wsTest")
@AllArgsConstructor
public class WSTestController {

    private PushMessageService pushMessageService;
    @Autowired
    IAFocusWarnService iaFocusWarnService;
    /**
     * 活跃用户
     *
     * @return
     */
    @GetMapping("/onLineChannel")
    public Object onLineChannel(String msg) {

        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>(16);

        Iterator<Map.Entry<String, ChannelId>> it = ChannelStore.getAllChannels();

        while (it.hasNext()) {

            Map.Entry<String, ChannelId> key = it.next();

            Channel obj = ChannelStore.getChannel(key.getValue().asShortText());

            System.out.println("channel id is: " + key);

            System.out.println("channel: " + obj.isActive());
            obj.writeAndFlush(new TextWebSocketFrame("hello, it is Server test header ping！" + msg));

        }

        return "ok";
    }

    /**
     * 活跃用户
     *
     * @return
     */
    @GetMapping("/onNoticeWell")
    public Object onNoticeWell(String wellId,String msg) {


        AFocusWarn warn = new AFocusWarn();
        warn.setSource("工程预警");
//        Map<String, Object> res =  iaFocusWarnService.newListWarning(warn,1,10,1,getDayAgoOrAfterString(-2),getDayAgoOrAfterString(0));
        //todo 多井列表有页数问题 考虑是否还要推



        SocketBody body = new SocketBody(SocketBody.type_oneWellData,"aaa");

        pushMessageService.pushMsgToOneWell(wellId,body.toJson(),SocketBody.type_oneWellData);

        return "ok-onNoticeWell";
    }

    /**
     *
     * @param num ﹣3 三天前 +3 三天后
     * @return
     */
    public static String getDayAgoOrAfterString(int num){
        Calendar calendar1 = Calendar.getInstance();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        calendar1.add(Calendar.DATE, num);
        return sdf1.format(calendar1.getTime());
    }
}
