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


import cn.hutool.core.collection.CollectionUtil;
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.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.device.biz.pojo.dto.DeptGetBase;
import com.njcn.harmonic.pojo.po.dim.RDimStationBaseD;
import com.njcn.harmonic.pojo.po.dim.RDimStationTargetM;
import com.njcn.harmonic.pojo.po.dim.RDimStationTargetY;
import com.njcn.prepare.harmonic.mapper.mysql.dim.RDimStationTargetYMapper;
import com.njcn.prepare.harmonic.pojo.bo.CalculatedParam;
import com.njcn.prepare.harmonic.service.mysql.dim.IRDimStationBaseDService;
import com.njcn.prepare.harmonic.service.mysql.dim.IRDimStationTargetYService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cdf
 * @since 2023-11-21
 */
@Service
@RequiredArgsConstructor
public class RDimStationTargetYServiceImpl extends MppServiceImpl<RDimStationTargetYMapper, RDimStationTargetY> implements IRDimStationTargetYService {

    private final IRDimStationBaseDService irDimStationBaseDService;

    @Override
    public void calDimStationTargetYear(CalculatedParam<DeptGetBase> calculatedParam) {
        List<RDimStationTargetY> poList = new ArrayList<>();
        DateTime start = DateUtil.beginOfYear(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN));
        DateTime end = DateUtil.endOfYear(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN));

        List<DeptGetBase> deptList = calculatedParam.getIdList();

        for(DeptGetBase deptGetBase : deptList){
            List<String> deptCodes = deptGetBase.getUnitChildrenList();

            LambdaQueryWrapper<RDimStationBaseD> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(RDimStationBaseD::getOrgId,deptCodes)
                    .between(RDimStationBaseD::getStatisDate,start,end).eq(RDimStationBaseD::getLevel,0);

            List<RDimStationBaseD> rDimStationBaseDList = irDimStationBaseDService.list(lambdaQueryWrapper);
            if(CollectionUtil.isEmpty(rDimStationBaseDList)){
                continue;
            }


            Map<String,List<RDimStationBaseD>> voltageMap = rDimStationBaseDList.stream().collect(Collectors.groupingBy(RDimStationBaseD::getVoltageLevel));
            voltageMap.forEach((voltageKey,voltageVal)->{
                int stationNum = (int) voltageVal.stream().map(RDimStationBaseD::getStationId).distinct().count();
                int stationAllNum = (int) voltageVal.stream().map(RDimStationBaseD::getStationId).count();

                Map<String,List<RDimStationBaseD>> targetMap = voltageVal.stream().collect(Collectors.groupingBy(RDimStationBaseD::getTargetType));
                targetMap.forEach((targetKey,targetVal)->{
                    RDimStationTargetY rDimStationTargetY = new RDimStationTargetY();
                    rDimStationTargetY.setOrgId(deptGetBase.getUnitId());
                    rDimStationTargetY.setStatisDate(LocalDate.parse(calculatedParam.getDataDate()));
                    rDimStationTargetY.setVoltageLevel(voltageKey);
                    rDimStationTargetY.setTargetType(targetKey);

                    List<String> limitList = targetVal.stream().filter(targetItem->targetItem.getLimitCount()>0).map(RDimStationBaseD::getStationId).distinct().collect(Collectors.toList());
                    rDimStationTargetY.setLimitRate((double) (limitList.size() / stationNum));

                    long limitAllList = targetVal.stream().filter(targetItem->targetItem.getLimitCount()>0).map(RDimStationBaseD::getStationId).count();
                    rDimStationTargetY.setLimitAvgRate((double) (limitAllList / stationAllNum));

                    //**kV变电站**指标合格率（%）
                    int limit = targetVal.stream().mapToInt(RDimStationBaseD::getLimitCount).sum();
                    int all = targetVal.stream().mapToInt(RDimStationBaseD::getStatisCount).sum();
                    rDimStationTargetY.setPassRate((double)(all-limit)/all);
                    rDimStationTargetY.setPassAvgRate((double)(all-limit)/all);
                    rDimStationTargetY.setState(DataStateEnum.ENABLE.getCode());
                    poList.add(rDimStationTargetY);
                });
            });
            this.saveOrUpdateBatchByMultiId(poList,100);
        }
    }
}
