package com.bcrjl.miwifi.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bcrjl.miwifi.common.util.MiWifiUtil;
import com.bcrjl.miwifi.mapper.DeviceDayTrafficMapper;
import com.bcrjl.miwifi.model.domain.DeviceDayTraffic;
import com.bcrjl.miwifi.model.result.StatusResult;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 设备每日流量 Service
 *
 * @author yanqs
 */
@Service
@AllArgsConstructor
public class DeviceDayTrafficService extends ServiceImpl<DeviceDayTrafficMapper, DeviceDayTraffic> {

    private final MiWifiUtil miWifiUtil;

    /**
     * 定时任务写入每日数据
     */
    public void writeEverydayDeviceTraffic() {
        dayTraffic();
    }

    /**
     * 系统启动初始化数据
     */
    public void initTraffic() {
        List<DeviceDayTraffic> list = this.list();
        if (CollUtil.isEmpty(list)) {
            dayTraffic();
        }
    }

    /**
     * 每日流量写入
     */
    private void dayTraffic() {
        StatusResult status = miWifiUtil.getStatus();
        if (Objects.nonNull(status) && CollUtil.isNotEmpty(status.getDev())) {
            List<DeviceDayTraffic> dbList = new ArrayList<>();
            Date date = DateUtil.date();
            String dateStr = DateUtil.format(date, "yyyy-MM-dd");
            status.getDev().forEach(dev -> {
                DeviceDayTraffic deviceDayTraffic = new DeviceDayTraffic();
                deviceDayTraffic.setMac(dev.getMac());
                deviceDayTraffic.setDate(dateStr);
                deviceDayTraffic.setDeviceName(dev.getDevName());
                deviceDayTraffic.setUpload(dev.getUpload());
                deviceDayTraffic.setDownload(dev.getDownload());
                Long total = Long.parseLong(dev.getUpload()) + Long.valueOf(dev.getDownload());
                deviceDayTraffic.setTotal(String.valueOf(total));
                dbList.add(deviceDayTraffic);
            });
            this.saveBatch(dbList);
        }
    }
}
