package com.imdroid.beidou.test_device.task;

import com.imdroid.beidou.test_device.service.OnlineChannels;
import com.imdroid.common.util.ByteUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Configuration
@EnableScheduling
public class BeidouTCPDevice {
    FileReader fr=null;
    BufferedReader br=null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    int cycleCount = 0;

    @Scheduled(cron = "0 6,16,26,36,46,56 * * * ?") // 每10分钟执行一次
    public void execute() throws IOException {
        if(br == null) {
            try{
                String dataFileName = "C:\\Users\\wd\\Desktop\\log\\2307046_0562_6xx.log";
                fr = new FileReader(dataFileName);
                br = new BufferedReader(fr);
            }
            catch (Exception e){
                return;
            }
        }

        try {
            String line = "";
            String[] arrs = null;

            long lastTime = 0;
            int d331Count = 0;

            while ((line = br.readLine()) != null) {
                arrs = line.split(" ");
                if(arrs.length != 3) continue;
                Date time = sdf.parse(arrs[0] + " " + arrs[1]);

                if (lastTime!=0 && Math.abs(time.getTime() - lastTime) > 60 * 1000) {//超过1分钟为一个周期
                    System.out.println(time+" cycle "+cycleCount+", b562 num "+d331Count);
                    cycleCount++;
                    break;
                }

                if(arrs[2].startsWith("d331")) {
                    OnlineChannels.INSTANCE.writeAndFlush(ByteUtil.hexStringTobyte(arrs[2]));
                    d331Count++;
                    Thread.sleep(980);
                }
                lastTime = time.getTime();

            }
            if(line == null) {
                br.close();
                fr.close();
                br = null;
                fr = null;
                System.out.println("finish!");
            }
        }
        catch (Exception e){
            e.printStackTrace();
            if(br!=null) br.close();
            if(fr!=null) fr.close();
        }
    }

}
