package com.imdroid.beidou_fwd.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.imdroid.beidou_fwd.service.TCPClient;
import com.imdroid.secapi.dto.ResendRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Configuration
@EnableScheduling
public class GXJSForwarder extends GXXfzForwarder{
    private final String FORWARDER_NAME = "广西新发展";
    @Value("${xfz.server.host}")
    private String host;

    @Value("${xfz.server.port}")
    private int port;
    private boolean enabled=true;

    @PostConstruct
    void registerMe(){
        init(FORWARDER_NAME, "TCP "+host+":"+port,1,FWD_DEVICE_ID,30);
        xfzTcpClient = new TCPClient();
        xfzTcpClient.init(host, port,listener);
        if(!enabled) return;

        xfzTcpClient.start();
    }

    /**
     * 每半小时转发GNSS解算结果
     */
    @Scheduled(cron = "0 0/30 * * * ?") // 每30分钟执行一次
    private void forwardGnss() {
        if(!enabled) return;
        logger.debug("gxjs forwardGnss");
        forwardCurrentGnss();
    }

    @Override
    void forwardHistoryGnss(){
        // 1.从转发记录表里检索待补传记录时间表，含设备Id，时间段
        QueryWrapper<ResendRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fwd_group_id",fwdGroupId);
        queryWrapper.eq("state",ResendRecord.STATE_BREAK_POINT);
        queryWrapper.ge("createtime", LocalDateTime.now().minusDays(30));
        List<ResendRecord> resendRecordsList = resendRecordMapper.selectList(queryWrapper);

        if(resendRecordsList!=null && resendRecordsList.size()>0){
            //修改状态
            UpdateWrapper<ResendRecord> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("fwd_group_id",fwdGroupId);
            updateWrapper.eq("state",ResendRecord.STATE_BREAK_POINT);
            updateWrapper.ge("createtime", LocalDateTime.now().minusDays(30));
            updateWrapper.set("state",ResendRecord.STATE_FWDING);
            int updateNum = resendRecordMapper.update(null, updateWrapper);
            logger.debug("{} forward history records: {}, update {}",fwdGroupId, resendRecordsList.size(),updateNum);
            // 2.检索这个这个时间段的解算结果，如果有数据则单个终端转发，标志记录为已补传
            for(ResendRecord record:resendRecordsList){
                if(record.getProjectid()!=null)
                    logger.debug("{} forward history {}",fwdGroupId, record.getProjectid());
                forwardBatchGnssRecords(record);
            }
        }
    }
}
