package com.tofly.scada.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.scada.entity.*;
import com.tofly.scada.mapper.*;
import com.tofly.scada.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

/**
 * @author HaiQiu
 * @date 2022/4/25
 */

@Slf4j
@Service("scadaHistorySynService")
public class ScadaHistorySynServiceImpl extends ServiceImpl<ScadaHistorySynMapper, ScadaHistorySyn> implements ScadaHistorySynService {
    @Autowired
    @Lazy
    private ScadaServiceImpl scadaService;

    @Override
    @Async
    public void synScadaHistoryData() {
        Page page=new Page();
        page.setCurrent(1);
        page.setSize(300); //每次取1000条数据进行同步

        Page<ScadaHistorySyn> listPage=super.page(page, Wrappers.<ScadaHistorySyn>lambdaQuery()
                .eq(ScadaHistorySyn::getStatus,"0").orderByAsc(ScadaHistorySyn::getScadaTime));
        if(listPage.getTotal()>0){
            listPage.getRecords().forEach(a->{

                int count=scadaService.count(Wrappers.<Scada>lambdaQuery()
                        .eq(Scada::getCode,a.getCode())
                        .eq(Scada::getScadaTime,a.getScadaTime())
                );
                boolean flag=true;
                if(count==0){ //不存在，则新增
                    Scada scada=new Scada();
                    scada.setScadaTime(a.getScadaTime());
                    scada.setCode(a.getCode());
                    scada.setValue(a.getValue());
                    flag=scadaService.save(scada);
                }
                a.setStatus(flag?1:2);
                this.updateById(a);
            });

        }

    }
    @Override
    public  void  delScadaHistoryData(){
        //删除数据，只保留过去30天的数据
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, - 30);
        Date d = calendar.getTime();

        this.remove(Wrappers.<ScadaHistorySyn>lambdaQuery()
                .eq(ScadaHistorySyn::getStatus,1)
                .le(ScadaHistorySyn::getScadaTime,d));
    }
}
