package com.mosty.wzzx.udp;

import com.mosty.base.model.entity.wzzx.TbWzSbsswz;
import com.mosty.wzzx.service.TbWzSblswzService;
import com.mosty.wzzx.service.TbWzSbsswzService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.Filter;
import org.springframework.integration.annotation.Router;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.ip.dsl.Udp;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * esacpe
 * 泸州udp
 * 2023-01-10
 */
@Component
public class UdpServerForLz {


    private static final Logger logger = LoggerFactory.getLogger(UdpServerForLz.class);

    @Value("${custom.udp.LzUdpPort}")
    private Integer bureauPort;
    @Resource
    private TbWzSbsswzService tbWzSbsswzService;
    @Resource
    private TbWzSblswzService tbWzSblswzService;

    // UDP服务
    @Bean(name = "integrationLzUdp")
    public IntegrationFlow integrationFlow() {
        logger.info("UDP-UDP-启动成功，端口号为: {}", bureauPort);
        return IntegrationFlows.from(Udp.inboundAdapter(bureauPort)).channel("udpChannelLz").get();
    }


    // 数据转换器
    @Transformer(inputChannel = "udpChannelLz", outputChannel = "udpFilterLz")
    public UdpLzEntity transformer(@Payload byte[] payload) {
//        logger.info("UDP-定位接收服务-开始转换数据");
        UdpLzEntity lzEntity = new UdpLzEntity();
        try {
            String s = UdpLzEntity.byteArrayToString(payload);
//            logger.info("UDP推送信息---》", s);
            if (lzEntity.parseLz(payload)) {

                if (ObjectUtils.isNotEmpty(lzEntity)) {
//                    long time = new Date().getTime();
//                    long i = time - lzEntity.getTime().getTime();
//                    if (i > 300000) {
//                        logger.info("UDP-定位接收服务-返回位置信息异常 : {}", s);
//                    }
                    lzEntity.setPgisId(lzEntity.getPgisId().replace("000", ""));
                }
                return lzEntity;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new UdpLzEntity();
    }


    // 过滤器
    @Filter(inputChannel = "udpFilterLz", outputChannel = "udpRouterLz")
    public boolean filter(@Headers Map<String, Object> headers) {
        String id = headers.get("id").toString();
        String ip = headers.get("ip_address").toString();
        String port = headers.get("ip_port").toString();
//        System.err.println("filter-id : " + id + "，filter-ip : " + ip + ",filter-port : " + port);
        return true;
    }


    // 路由分发处理器 - 可根据消息或者headers数据进行分发处理
    @Router(inputChannel = "udpRouterLz")
    public String router(UdpLzEntity lzEntity) {
        if (null == lzEntity.getLat() || lzEntity.getLat() == 0
                || null == lzEntity.getLng() || lzEntity.getLng() == 0) {
            return "locationExceptionHandleLz";
        }
        return "locationHandleLz";
    }


    // 位置信息处理方法
    @ServiceActivator(inputChannel = "locationHandleLz")
    public void locationHandleLz(UdpLzEntity lzEntity) {
//        logger.info("UDP-定位接收服务-获取到正常位置信息 : {}", lzEntity.toString());
        TbWzSbsswz sswz = this.tbWzSbsswzService.saveSbsswz(lzEntity);
        this.tbWzSblswzService.saveSblswz(sswz);
    }


    // 位置信息解析异常处理方法
    @ServiceActivator(inputChannel = "locationExceptionHandleLz")
    public void locationExceptionHandleLz(UdpLzEntity lzEntity) {
        logger.error("UDP-定位接收服务-获取到解析异常位置信息 : {} ", lzEntity.toString());
    }
}
