package vip.xiaonuo.Timer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.common.timer.CommonTimerTaskRunner;
import vip.xiaonuo.modular.env.envDeviceOnline.entity.EnvDeviceOnline;
import vip.xiaonuo.modular.env.envDeviceOnline.service.EnvDeviceOnlineService;
import vip.xiaonuo.modular.env.envdevice.entity.EnvDevice;
import vip.xiaonuo.modular.env.envdevice.service.EnvDeviceService;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.sys.modular.org.mapper.SysOrgMapper;
import vip.xiaonuo.sys.modular.org.service.SysOrgService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class DeviceOnlineTimer implements CommonTimerTaskRunner {

    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private EnvDeviceService envDeviceService;
    @Autowired
    private EnvDeviceOnlineService envDeviceOnlineService;
    @Override
    public void action() {
        List<SysOrg> list = sysOrgService.list();
        for (SysOrg sysOrg : list) {
            double rate = 0.0;
            Integer deviceOff = Math.toIntExact(envDeviceService.count(new QueryWrapper<EnvDevice>().lambda().eq(EnvDevice::getOrgId, sysOrg.getId()).eq(EnvDevice::getStatus, 0)));
            Integer deviceOn = Math.toIntExact(envDeviceService.count(new QueryWrapper<EnvDevice>().lambda().eq(EnvDevice::getOrgId, sysOrg.getId()).eq(EnvDevice::getStatus, 1)));
            Integer total = deviceOff+deviceOn;
            LocalDateTime now = LocalDateTime.now();
            try {
                rate = (deviceOn/total)*100;
            }catch (ArithmeticException e){
                System.out.println(e);
            }
            EnvDeviceOnline envDeviceOnline = new EnvDeviceOnline();
            envDeviceOnline.setDeviceOn(deviceOn);
            envDeviceOnline.setDeviceOff(deviceOff);
            envDeviceOnline.setOnlineRate(new BigDecimal(rate).setScale(2, RoundingMode.UP));
            envDeviceOnline.setOrgId(sysOrg.getId());
            envDeviceOnline.setCreatTime(now);
            envDeviceOnlineService.save(envDeviceOnline);
        }
    }
}
