package com.bcrjl.miwifi.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.param.DeviceDayTrafficParam;
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 IPage<DeviceDayTraffic> pageList(IPage<DeviceDayTraffic> page, DeviceDayTrafficParam param) {
        return this.baseMapper.pageList(page, param);
    }


    /**
     * 定时任务写入每日数据
     */
    public void writeEverydayDeviceTraffic() {
        Date date = DateUtil.date();
        Date firstYesterday = DateUtil.offsetDay(date, -2);
        Date yesterday = DateUtil.offsetDay(date, -1);
        String dateStr = DateUtil.format(firstYesterday, "yyyy-MM-dd");
        String yesterdayDateStr = DateUtil.format(yesterday, "yyyy-MM-dd");
        List<DeviceDayTraffic> list = this.list(new LambdaQueryWrapper<DeviceDayTraffic>().eq(DeviceDayTraffic::getDate, dateStr));
        if (CollUtil.isEmpty(list)) {
            dayTraffic();
        } else {
            StatusResult status = miWifiUtil.getStatus();
            List<StatusResult.Dev> devList = status.getDev();
            List<DeviceDayTraffic> dbList = new ArrayList<>();
            for (DeviceDayTraffic dayTraffic : list) {
                StatusResult.Dev device = devList.stream().filter(t -> t.getMac().equals(dayTraffic.getMac())).findFirst().orElse(null);
                DeviceDayTraffic deviceDayTraffic = new DeviceDayTraffic();
                deviceDayTraffic.setDate(yesterdayDateStr);
                if (Objects.isNull(device)) {
                    deviceDayTraffic.setMac(dayTraffic.getMac());
                    deviceDayTraffic.setDeviceName(dayTraffic.getDeviceName());
                    deviceDayTraffic.setUpload("0");
                    deviceDayTraffic.setDownload("0");
                    deviceDayTraffic.setTotal("0");
                    dbList.add(deviceDayTraffic);
                } else {
                    // 如果不是null 则今日流量减去昨日流量 等于今日流量
                    deviceDayTraffic.setMac(device.getMac());
                    deviceDayTraffic.setDeviceName(device.getDevName());
                    long download = Long.parseLong(device.getDownload());
                    long upload = Long.parseLong(device.getUpload());
                    long total = download + upload;
                    long yesterdayTotal = Long.parseLong(dayTraffic.getTotal());
                    if (total - yesterdayTotal <= 0) {
                        // 今日流量就是当日流量
                        upload = Long.parseLong(device.getUpload());
                        download = Long.parseLong(device.getDownload());
                        total = download + upload;
                        deviceDayTraffic.setDownload(device.getDownload());
                        deviceDayTraffic.setUpload(device.getUpload());
                        deviceDayTraffic.setTotal(String.valueOf(total));
                        dbList.add(deviceDayTraffic);
                    } else {
                        // 减去的数据就是今日流量
                        deviceDayTraffic.setTotal(String.valueOf(total - yesterdayTotal));
                        upload = Long.parseLong(device.getUpload()) - Long.parseLong(dayTraffic.getUpload());
                        deviceDayTraffic.setUpload(String.valueOf(upload));
                        download = Long.parseLong(device.getDownload()) - Long.parseLong(dayTraffic.getDownload());
                        deviceDayTraffic.setDownload(String.valueOf(download));
                        dbList.add(deviceDayTraffic);
                    }
                }
            }
            this.saveBatch(dbList);
        }
    }

    /**
     * 系统启动初始化数据
     */
    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();
            Date yesterday = DateUtil.offsetDay(date, -1);
            String dateStr = DateUtil.format(yesterday, "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);
        }
    }
}
