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 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.harmonic.pojo.po.dim.RDimObjRateD;
import com.njcn.harmonic.pojo.po.dim.RDimObjRateM;
import com.njcn.prepare.harmonic.mapper.mysql.dim.RDimObjRateMMapper;
import com.njcn.prepare.harmonic.pojo.bo.CalculatedParam;
import com.njcn.prepare.harmonic.service.mysql.dim.IRDimObjRateDService;
import com.njcn.prepare.harmonic.service.mysql.dim.IRDimObjRateMService;
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 RDimObjRateMServiceImpl extends MppServiceImpl<RDimObjRateMMapper, RDimObjRateM> implements IRDimObjRateMService {

    private final IRDimObjRateDService irDimObjRateService;

    @Override
    public void objMonitorRateMonth(CalculatedParam<DeptGetChildrenDTO> calculatedParam) {
        List<RDimObjRateM> poList = new ArrayList<>();
        DateTime start = DateUtil.beginOfMonth(DateUtil.parse(calculatedParam.getDataDate()));
        QueryWrapper<RDimObjRateD> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().between(RDimObjRateD::getStatisDate,start,DateUtil.endOfMonth(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_FORMAT)));
        queryWrapper.select("Org_Id as orgId,Obj_type as objType,avg(Obj_Monitor_Rate) as objMonitorRate").groupBy("Org_Id","Obj_type");
        List<RDimObjRateD> rDimObjRateDList = irDimObjRateService.list(queryWrapper);

        if(CollUtil.isNotEmpty(rDimObjRateDList)){
            for(RDimObjRateD rDimObjRateD : rDimObjRateDList){
                RDimObjRateM rDimMonitorRateM = new RDimObjRateM();
                rDimMonitorRateM.setObjType(rDimObjRateD.getObjType());
                rDimMonitorRateM.setObjMonitorRate(rDimObjRateD.getObjMonitorRate());
                rDimMonitorRateM.setOrgId(rDimObjRateD.getOrgId());
                rDimMonitorRateM.setStatisDate(LocalDate.parse(DateUtil.format(start,DatePattern.NORM_DATE_PATTERN)));
                poList.add(rDimMonitorRateM);
            }
            this.saveOrUpdateBatchByMultiId(poList,100);
        }
    }
}
