package com.usky.iot.service.job;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.util.Arith;
import com.usky.common.core.util.DateUtils;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.iot.domain.DmpDataOverview;
import com.usky.iot.mapper.DmpDeviceStatusMapper;
import com.usky.iot.service.DmpDataOverviewService;
import com.usky.iot.service.vo.DmpDataOverviewVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DmpDataOverviewJob {


    @Autowired
    private DmpDeviceStatusMapper dmpDeviceStatusMapper;

    @Autowired
    private DmpDataOverviewService dmpDataOverviewService;

    public void execute(){
        log.info("定时生成数据概览数据 start");
        deviceCount();
        log.info("定时生成数据概览数据 end");
    }

    /**
     * 设备量分析
     */
    public void deviceCount(){
        Date date = new Date();
        Date dayStartTime = DateUtils.getDayStartTime(date);
        Date dayEndTime = DateUtils.getDayEndTime(date);
        Date firstDayOfMonth = DateUtils.getFirstDayOfMonth(date);
        Date lastDayOfMonth = DateUtils.getLastDayOfMonth(date);

        Date date1 = DateUtils.setHours(date, 0);
        Date date2 = DateUtils.setMinutes(date1, 0);
        Date date3 = DateUtils.setSeconds(date2, 0);
        Date date4 = DateUtils.setDays(date3, 1);
        //产品日
        List<DmpDataOverview> dmpDataOverviews = new ArrayList<>();
        List<DmpDataOverviewVO> list = getListMap(dayStartTime, dayEndTime);
        //计算产品活跃占比
        checkRadio(list);
        for (DmpDataOverviewVO dvo : list) {
            DmpDataOverview dmpDataOverview = new DmpDataOverview();
            dmpDataOverview.setCreatedTime(date3);
            dmpDataOverview.setTenantId(dvo.getTenantId());
            dmpDataOverview.setDeviceNumber(JSON.toJSONString(dvo));
            dmpDataOverviews.add(dmpDataOverview);
        }
        dmpDataOverviewService.saveBatch(dmpDataOverviews);
        //产品月
        List<DmpDataOverviewVO> monthList = getListMap(firstDayOfMonth, lastDayOfMonth);
        //活跃产品月
        List<DmpDataOverviewVO> hyList = getHyListMap(firstDayOfMonth, lastDayOfMonth);
        for (DmpDataOverviewVO dmpDataOverviewVO : monthList) {
            hyList.stream().filter(hy -> Objects.equals(hy.getTenantId(), dmpDataOverviewVO.getTenantId()))
                    .findFirst()
                    .ifPresent(hy -> dmpDataOverviewVO.setHyCount(hy.getHyCount()));
        }
        //统计全部时间数据
        List<DmpDataOverviewVO> allList = getListMap(null, null);
        //计算占比
        checkRadio(monthList);
        //查看对应月份数据是否存在
        List<DmpDataOverview> listByTimeAndIds = getListByTimeAndIds(monthList, firstDayOfMonth,lastDayOfMonth);
        for (DmpDataOverviewVO dmpDataOverviewVO : monthList) {
            DmpDataOverview dd = listByTimeAndIds.stream()
                    .filter(dm -> dmpDataOverviewVO.getTenantId().equals(dm.getTenantId()) && DateUtils.isSameDay(dm.getCreatedTime(),date4))
                    .findAny()
                    .map(dm -> {
                        dm.setDeviceNumber(JSON.toJSONString(dmpDataOverviewVO));
                        return dm;
                    })
                    .orElseGet(() -> {
                        DmpDataOverview dmpDataOverview = new DmpDataOverview();
                        dmpDataOverview.setDeviceNumber(JSON.toJSONString(dmpDataOverviewVO));
                        dmpDataOverview.setTenantId(dmpDataOverviewVO.getTenantId());
                        dmpDataOverview.setCreatedTime(date4);
                        dmpDataOverview.setCycleType(2);
                        listByTimeAndIds.add(dmpDataOverview);
                        return dmpDataOverview;
                    });
            allList.stream()
                    .filter(dvo -> dvo.getTenantId().equals(dd.getTenantId()))
                    .findAny()
                    .ifPresent(dvo -> dd.setMiddleStatistic(JSON.toJSONString(dvo)));
        }
        dmpDataOverviewService.saveOrUpdateBatch(listByTimeAndIds);
    }

    /**
     * 统计月信息
     * @param tenantIds
     * @param startTime
     * @param endTime
     * @return
     */
    public List<DmpDataOverview> getListByTimeAndIds(List<DmpDataOverviewVO> tenantIds,Date startTime,Date endTime){
        if (CollectionUtils.isNotEmpty(tenantIds)){
            List<Integer> tenantId = tenantIds.stream()
                    .map(DmpDataOverviewVO::getTenantId)
                    .collect(Collectors.toList());
            LambdaQueryWrapper<DmpDataOverview> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(DmpDataOverview::getTenantId,tenantId)
                    .between(DmpDataOverview::getCreatedTime,startTime,endTime)
                    .eq(DmpDataOverview::getCycleType,2);
            return dmpDataOverviewService.list(queryWrapper);
        }else {
            return new ArrayList<>();
        }
    }

    public List<DmpDataOverviewVO> getHyListMap(Date startTime,Date endTime){
        List<DmpDataOverviewVO> list = dmpDeviceStatusMapper.getMonthHyCollect(startTime, endTime);
        DmpDataOverviewVO map = dmpDeviceStatusMapper.getAllMonthHyCollect(startTime, endTime);
        joinList(list,map);
        return list;
    }

    public List<DmpDataOverviewVO> getListMap(Date startTime,Date endTime){
        List<DmpDataOverviewVO> list = dmpDeviceStatusMapper.getDeviceStatusCollect(startTime, endTime);
        //全部产品日
        DmpDataOverviewVO map = dmpDeviceStatusMapper.getAllCollect(startTime, endTime);
        joinList(list,map);
        return list;
    }

    public void joinList(List<DmpDataOverviewVO> list,DmpDataOverviewVO map){
        Optional.ofNullable(map).ifPresent(map1 -> map.setTenantId(0));
        list.add(map);
    }


    public void checkRadio(List<DmpDataOverviewVO> list){
        list.forEach(dmpDataOverviewVO -> {
            dmpDataOverviewVO.setJhRadioCount((null == dmpDataOverviewVO.getDeviceCount() || 0 == dmpDataOverviewVO.getDeviceCount())?0.00: Arith.div(dmpDataOverviewVO.getJhCount(),dmpDataOverviewVO.getDeviceCount()));
            dmpDataOverviewVO.setHyRadioCount((null == dmpDataOverviewVO.getDeviceCount() || 0 == dmpDataOverviewVO.getDeviceCount())?0.00:Arith.div(dmpDataOverviewVO.getHyCount(),dmpDataOverviewVO.getDeviceCount()));
        });
    }


}
