package com.zcxk.charge.web.service;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxk.charge.api.dto.*;
import com.zcxk.charge.api.vo.*;
import com.zcxk.charge.core.dao.MonthReportMapper;
import com.zcxk.charge.core.entity.MonitorDataEntity;
import com.zcxk.charge.core.entity.MonthReportEntity;
import com.zcxk.charge.web.util.MongoDbUtil;
import com.zcxk.core.common.util.BeanCopyUtils;
import com.zcxk.core.oauth2.pojo.LoginUser;
import com.zcxk.core.oauth2.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 日报Service接口
 *
 * @author: WYY
 * @date 2020-12-03 16:20
 */
@Service
public class MonthReportService extends AbstractReportService<MonthReportMapper, MonthReportEntity> {

    @Resource
    private MonthReportMapper monthReportMapper;

    @Autowired
    private MongoDbUtil mongoDbUtil;

    /**
     * 查列表
     */
    public List<MonthReportEntity> findList(MonthReportEntity monthReportEntity) {
        return monthReportMapper.findList(monthReportEntity);
    }


    public Page<ReportVo> findPage(IPage<ReportDto> page, Long[] ids, Integer year, Integer month, Integer day) {
        LoginUser currentUser     = UserUtil.getCurrentUser();
        Page<ReportVo> reportPage = new Page<>();
        // 查询场景下的所有设备信息
        List<DeviceVo> devices = findDevices(ids);
        if (CollectionUtils.isEmpty(devices)) {
            return reportPage;
        }
        MonthReportEntity monthReportEntity = new MonthReportEntity();
        monthReportEntity.setYear(year);
        monthReportEntity.setMonth(month);
        monthReportEntity.setTenantId(currentUser.getTenantId());
        monthReportEntity.setParentSceneIds(ids);
        monthReportEntity.setDeviceIds(devices);
        // 查询到分页的行数
        reportPage = monthReportMapper.findPage(page, monthReportEntity);
        // 查询标题
        ReportDto reportDto = new ReportDto();
        reportDto.setYear(year);
        reportDto.setMonth(month);
        reportDto.setDeviceIds(devices);
        reportDto.setParentSceneIds(ids);
        formatReport(reportDto, reportPage, devices);
        return reportPage;
    }


    public List<MonthReportEntity> findAmountBySceneIds(MonthReportEntity monthReportEntity) {
        return monthReportMapper.findAmountBySceneIds(monthReportEntity);
    }

    /**
     * 查询历史数据压力及流量统计
     * @param page
     * @param queryDto
     * @return
     */
    public Page<ReportVo> findHistoryDataDevicePressPageReport(IPage<ReportDto> page, ReportQueryDto queryDto) {
        return pageReport(queryDto, page, true);
    }

    /**
     * 查询历史数据
     * @param page
     * @param queryDto
     * @return
     */
    public Page<ReportVo> findHistoryDataPageReport(IPage<ReportDto> page, ReportQueryDto queryDto) {
        return pageReport(queryDto, page, false);
    }

    public Page<ReportVo> findPageReport(IPage<ReportDto> page, ReportQueryDto queryDto) {
        return findPageReport(page, queryDto, false);
    }

    public Page<ReportVo> findDevicePressPageReport(IPage<ReportDto> page, ReportQueryDto queryDto) {
        return findPageReport(page, queryDto, true);
    }

    @Override
    public void calcUsage(ReportDto item, List<ReportVo> reportDtos) {
        if (item == null || reportDtos.size() == 0) {
            return;
        }
        // 固定参数项
        int index = -1;
        for (int i = 0; i < reportDtos.size(); i++) {
            if (reportDtos.get(i).getDay().equals(item.getDay())) {
                index = i;
            }
        }
        if (index == -1) {
            return;
        }
        calcReportUsage(index, reportDtos, item);
    }

    @Override
    public List<ReportVo> findReport(ReportDto reportDto) {
        return monthReportMapper.findReport(reportDto);
    }


    @Override
    public List<ReportAttributeVo> findAttributeList(ReportDto item) {
        return monthReportMapper.findAttributeList(item);
    }

    @Override
    public String formatCollectDate(ReportVo item){
        return item.getYear() + "-" + String.format("%02d", item.getMonth()) + "-" + String.format("%02d", item.getDay());
    }

    @Override
    public Page<ReportVo> findPageReport(IPage<ReportDto> page, ReportPageQueryDto reportPageQueryDto) {
        return monthReportMapper.findPageReprot(page, reportPageQueryDto);
    }

    private Page<ReportVo> pageReport(ReportQueryDto queryDto, IPage<ReportDto> page, boolean isPipe){
        Page<ReportVo> reportPage = new Page<>();
        List<DeviceVo> devices = findDevicesForReport(queryDto.getIds());
        if (devices.size() == 0) {
            return reportPage;
        }
        List<Long> deviceIds = devices.stream().map(DeviceVo::getId).collect(Collectors.toList());
        Query query = new Query();
        Sort sort = new Sort(Sort.Direction.ASC, "deviceId").and(new Sort(Sort.Direction.ASC, "collectDate"));
        query.addCriteria(Criteria.where("deviceId").in(deviceIds));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            query.addCriteria(Criteria.where("collectDate").gte(format.parse(queryDto.getStartTime())).lt(format.parse(queryDto.getEndTime())));
        } catch (ParseException e) {
            System.out.println("异常");
        }
        query.with(sort);
        Page<MonitorDataEntity> info = mongoDbUtil.pagination(MonitorDataEntity.class, page.getSize(), page.getCurrent(), query);
        reportHistoryDataHandle(queryDto, devices, reportPage, info,isPipe);
        return reportPage;
    }
}
