package cn.com.taiji.track.listener;

import cn.com.taiji.track.constants.WarningCodeConstants;
import cn.com.taiji.track.dto.AnchorTrackQueryDTO;
import cn.com.taiji.track.dto.HistoryTrackQueryDTO;
import cn.com.taiji.track.entity.BeidouTrackEntity;
import cn.com.taiji.track.entity.WarningRecordEntity;
import cn.com.taiji.track.event.AnchorTrackChannelAddEvent;
import cn.com.taiji.track.event.HistoryTrackChannelAddEvent;
import cn.com.taiji.track.handler.AnchorTrackHandler;
import cn.com.taiji.track.handler.HistoryTrackHandler;
import cn.com.taiji.track.service.IBeidouTrackService;
import cn.com.taiji.track.service.IWarningRecordService;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author chenfangchao
 * @title: BeidouChannelListener
 * @projectName ax-geomesa-redis
 * @description: TODO
 * @date 2022/9/22 6:00 PM
 */
@Component
@Slf4j
public class AnchorTrackChannelListener {
    @Autowired
    private AnchorTrackHandler historyTrackHandler;
    @Autowired
    private IWarningRecordService warningRecordService;

    private static final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("thread-pool-channel-anchor-track").build();

    ThreadPoolExecutor threadPoolExecutor  = new ThreadPoolExecutor(2,2,5,
            TimeUnit.MINUTES,new ArrayBlockingQueue<>(10),threadFactory,new ThreadPoolExecutor.AbortPolicy());
    /**
     * 监听新增用户信道
     *
     * @param event
     */
    @EventListener
    public void listenerNettyAddChannel(AnchorTrackChannelAddEvent event) {
        log.info("当前需要创建的线程名称为 {}", event.getChannelId());
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                queryAnchorTrack(event);
            }
        });
    }
    /**
     * 查询
     */
    private void queryAnchorTrack(AnchorTrackChannelAddEvent event)  {
        List<BeidouTrackEntity> results = new ArrayList<>();
        List<WarningRecordEntity> warningRecords = new ArrayList<>();
        AttributeKey<String> key = AttributeKey.valueOf("anchor-track");
        String dtoStr = event.getCtx().attr(key).get();
        AnchorTrackQueryDTO dto = JSONObject.parseObject(dtoStr, AnchorTrackQueryDTO.class);
        if (null != dto) {
            QueryWrapper<WarningRecordEntity> wrapper = new QueryWrapper();
            wrapper.eq("model_code", WarningCodeConstants.ANCHOR_WARNING);
            wrapper.eq("start", "true");
            if(StringUtils.hasText(dto.getDeviceId())){
                wrapper.eq("device_id",dto.getDeviceId());
            }
            if(StringUtils.hasText(dto.getStartTime())&&StringUtils.hasText(dto.getEndTime())){
                wrapper.between("warning_time",dto.getStartTime(),dto.getEndTime());
            }
            wrapper.orderByDesc("warning_time");
            warningRecords = warningRecordService.list(wrapper);
            if (warningRecords.size() > 0) {
                for (WarningRecordEntity e : warningRecords)  {
                    BeidouTrackEntity result = JSONObject.parseObject(e.getDynamicShip(),BeidouTrackEntity.class);
                    results.add(result);
                }
            }
        }
        historyTrackHandler.sendMsgToSpecifyChannel(event.getChannelId(), JSONUtil.toJsonStr(results));
    }

}
