package com.njcn.prepare.harmonic.service.mysql.dim.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.njcn.device.biz.pojo.dto.DeptGetChildrenDTO;
import com.njcn.harmonic.pojo.po.dim.RDimMonitorRateD;
import com.njcn.harmonic.pojo.po.dim.RDimMonitorRateM;
import com.njcn.prepare.harmonic.mapper.mysql.dim.RDimMonitorRateMMapper;
import com.njcn.prepare.harmonic.pojo.bo.CalculatedParam;
import com.njcn.prepare.harmonic.service.mysql.dim.IRDimMonitorRateDService;
import com.njcn.prepare.harmonic.service.mysql.dim.IRDimMonitorRateMService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cdf
 * @since 2023-11-23
 */
@Service
@RequiredArgsConstructor
public class RDimMonitorRateMServiceImpl extends MppServiceImpl<RDimMonitorRateMMapper, RDimMonitorRateM> implements IRDimMonitorRateMService {

    private final IRDimMonitorRateDService irDimMonitorRateDService;

    @Override
    public void monitorRateMonth(CalculatedParam<DeptGetChildrenDTO> calculatedParam) {
        List<RDimMonitorRateM> poList = new ArrayList<>();
        DateTime start = DateUtil.beginOfMonth(DateUtil.parse(calculatedParam.getDataDate()));
        QueryWrapper<RDimMonitorRateD> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().between(RDimMonitorRateD::getStatisDate,start,DateUtil.endOfMonth(DateUtil.parse(calculatedParam.getDataDate(),DatePattern.NORM_DATE_FORMAT)));
        queryWrapper.select("Org_Id as orgId,avg(Bus_Monitor_Rate) as busMonitorRate,avg(Station_Monitor_Rate) as stationMonitorRate").groupBy("Org_Id");
        List<RDimMonitorRateD> rDimMonitorRateDList = irDimMonitorRateDService.list(queryWrapper);

        if(CollUtil.isNotEmpty(rDimMonitorRateDList)){
            for(RDimMonitorRateD rDimMonitorRateD : rDimMonitorRateDList){
                RDimMonitorRateM rDimMonitorRateM = new RDimMonitorRateM();
                rDimMonitorRateM.setBusMonitorRate(rDimMonitorRateD.getBusMonitorRate());
                rDimMonitorRateM.setStationMonitorRate(rDimMonitorRateD.getStationMonitorRate());
                rDimMonitorRateM.setOrgId(rDimMonitorRateD.getOrgId());
                rDimMonitorRateM.setStatisDate(LocalDate.parse(DateUtil.format(start,DatePattern.NORM_DATE_PATTERN)));
                poList.add(rDimMonitorRateM);
            }
            this.saveOrUpdateBatchByMultiId(poList,100);
        }

    }
}
