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


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.DeptGetChildrenMoreDTO;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.device.biz.pojo.param.DeptGetLineParam;
import com.njcn.device.pms.pojo.po.GeneratrixWire;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.device.pms.pojo.po.PmsMidLedger;
import com.njcn.device.pms.pojo.po.StatationStat;
import com.njcn.device.pq.pojo.po.RStatIntegrityD;
import com.njcn.prepare.harmonic.mapper.mysql.area.PmsMonitorPOMapper;
import com.njcn.prepare.harmonic.mapper.mysql.day.RStatIntegrityDMapper;
import com.njcn.prepare.harmonic.mapper.mysql.dim.GeneratrixWireMapper;
import com.njcn.prepare.harmonic.mapper.mysql.dim.PmsMidLedgerMapper;
import com.njcn.prepare.harmonic.mapper.mysql.upload.PmsRunStatisticDMapper;
import com.njcn.prepare.harmonic.mapper.mysql.upload.PmsStatationStatMapper;
import com.njcn.harmonic.pojo.po.upload.PmsRunStatisticD;
import com.njcn.prepare.harmonic.service.mysql.upload.IPmsRunStatisticService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.DictTreeFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.enums.DicTreeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.SysDicTreePO;
import com.njcn.system.pojo.vo.DictTreeVO;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cdf
 * @since 2024-04-17
 */
@Service
@RequiredArgsConstructor
public class PmsRunStatisticServiceImpl extends MppServiceImpl<PmsRunStatisticDMapper, PmsRunStatisticD> implements IPmsRunStatisticService {



    private final DeptFeignClient deptFeignClient;

    private final RStatIntegrityDMapper rStatIntegrityDMapper;

    private final PmsMidLedgerMapper pmsMidLedgerMapper;

    private final DicDataFeignClient dicDataFeignClient;


    private final DictTreeFeignClient dictTreeFeignClient;

    private final CommTerminalGeneralClient commTerminalGeneralClient;

    private final PmsMonitorPOMapper pmsMonitorPOMapper;

    private final PmsStatationStatMapper pmsStatationStatMapper;

    private final GeneratrixWireMapper generatrixWireMapper;






    @Override
    public void statisticLedgerRunDay(String date) {
        Dept dept = deptFeignClient.getRootDept().getData();
        LocalDate localDate = LocalDate.parse(date);
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(dept.getId());
        deptGetLineParam.setIsUpToGrid(1);

        List<DeptGetChildrenMoreDTO> deptGetChildrenMoreDTOList = commTerminalGeneralClient.deptGetLine(deptGetLineParam).getData();
        List<PmsRunStatisticD> poList = new ArrayList<>();

        //获取在运母线，在运电站数量
        List<PmsMidLedger> midLedgerStationList = this.getBusBarAndStationInfo(0);
        List<PmsMidLedger> midLedgerBusBarList = this.getBusBarAndStationInfo(1);

        //获取在运,符合上送国网的测点,用于过滤监测母线，监测电站
        DictData dictData = dicDataFeignClient.getDicDataByCodeAndType(DicDataEnum.RUN.getCode(),DicDataTypeEnum.LINE_STATE.getCode()).getData();
        List<Monitor> monitorList = pmsMonitorPOMapper.selectList(new LambdaQueryWrapper<Monitor>().eq(Monitor::getMonitorState,dictData.getId()).eq(Monitor::getIsUpToGrid,DataStateEnum.ENABLE.getCode()));

        List<String> generatrixWireIds = monitorList.stream().map(Monitor::getLineId).distinct().collect(Collectors.toList());
        List<GeneratrixWire> generatrixWireList = generatrixWireMapper.selectList(new LambdaQueryWrapper<GeneratrixWire>().in(GeneratrixWire::getId,generatrixWireIds));

        List<StatationStat> statationStatList = pmsStatationStatMapper.selectList(new LambdaQueryWrapper<StatationStat>().isNotNull(StatationStat::getMidStationId));


        //数据完整性
        List<String> rStatIntegrityIds = rStatIntegrityDMapper.selectList(new LambdaQueryWrapper<RStatIntegrityD>().eq(RStatIntegrityD::getTimeId,localDate).gt(RStatIntegrityD::getRealTime,0)).stream().map(RStatIntegrityD::getLineIndex).distinct().collect(Collectors.toList());

        //对象类型
        List<SysDicTreePO> sysdictreepo = dictTreeFeignClient.queryAll().getData();
        DictTreeVO dictTreeVO = dictTreeFeignClient.queryByCode(DicTreeEnum.Imp_Users.getCode()).getData();
        List<DictTreeVO> dictTreeVOList = dictTreeFeignClient.query(dictTreeVO.getId()).getData();
        List<String> importUser = dictTreeVOList.stream().map(DictTreeVO::getCode).distinct().collect(Collectors.toList());
        importUser.add(dictTreeVO.getCode());

        List<String> import_dict = sysdictreepo.stream().filter(temp -> importUser.contains(temp.getCode())).map(SysDicTreePO::getId).collect(Collectors.toList());

        //遍历每个部门
        for(DeptGetChildrenMoreDTO dto : deptGetChildrenMoreDTOList){
            List<String> childrenDept = dto.getUnitChildrenList();


            List<String> temPointIds = dto.getLineBaseList().stream().map(LineDevGetDTO::getPointId).distinct().collect(Collectors.toList());

            List<String> onlinePointIds = temPointIds.stream().filter(rStatIntegrityIds::contains).collect(Collectors.toList());

            PmsRunStatisticD pmsRunStatisticD = new PmsRunStatisticD();
            pmsRunStatisticD.setStatisticDate(localDate);
            pmsRunStatisticD.setDeptId(dto.getUnitId());
            pmsRunStatisticD.setRunMonitorIds(String.join(StrUtil.COMMA, temPointIds));
            pmsRunStatisticD.setOnlineMonitorIds(String.join(StrUtil.COMMA, onlinePointIds));

            pmsRunStatisticD.setRunDevIds(dto.getLineBaseList().stream().map(LineDevGetDTO::getDevId).distinct().collect(Collectors.joining(StrUtil.COMMA)));


            long stationCount = midLedgerStationList.stream().filter(it->childrenDept.contains(it.getSectionId())).map(PmsMidLedger::getId).distinct().count();
            pmsRunStatisticD.setRunStationNum((int) stationCount);
            long busBarCount = midLedgerBusBarList.stream().filter(it->childrenDept.contains(it.getSectionId())).map(PmsMidLedger::getId).distinct().count();
            pmsRunStatisticD.setRunBusNum((int) busBarCount);

            String temRunBusIds = midLedgerBusBarList.stream().filter(it->childrenDept.contains(it.getSectionId())).map(PmsMidLedger::getId).distinct().collect(Collectors.joining(StrUtil.COMMA));
            pmsRunStatisticD.setRunBusIds(temRunBusIds);

            List<String> onlineBusIds = monitorList.stream().filter(it->childrenDept.contains(it.getOrgId())).map(Monitor::getLineId).distinct().collect(Collectors.toList());
            pmsRunStatisticD.setOnlineBusIds(String.join(StrUtil.COMMA, onlineBusIds));
            List<String> onlineBusMidIds = generatrixWireList.stream().filter(it->onlineBusIds.contains(it.getId())).map(GeneratrixWire::getMidBusId).distinct().collect(Collectors.toList());
            pmsRunStatisticD.setOnlineBusMidIds(String.join(StrUtil.COMMA, onlineBusMidIds));


            List<String> runStationIds = statationStatList.stream().filter(it->childrenDept.contains(it.getOrgId())).map(StatationStat::getPowerId).distinct().collect(Collectors.toList());
            pmsRunStatisticD.setOnlineStationIds(String.join(StrUtil.COMMA, runStationIds));

            //典型统计
            List<String> typicalOnlineIds = dto.getLineBaseList().stream().filter(it->!import_dict.contains(it.getObjType())).map(LineDevGetDTO::getPointId).collect(Collectors.toList());
            pmsRunStatisticD.setTypicalOnlineIds(String.join(StrUtil.COMMA, typicalOnlineIds));
            poList.add(pmsRunStatisticD);
        }
        this.saveOrUpdateBatchByMultiId(poList);
    }




    /**
     * 获取中台母线电站信息
     */
    public List<PmsMidLedger> getBusBarAndStationInfo(Integer type) {
        List<DictData> dicDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        DictData RunStatus = dicDataFeignClient.getDicDataByCodeAndType(DicDataEnum.RUN.getCode(),DicDataTypeEnum.LINE_STATE.getCode()).getData();
        List<String> list = dicDataList.stream().map(DictData::getId).collect(Collectors.toList());
        LambdaQueryWrapper<PmsMidLedger> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PmsMidLedger::getLevel,type)
                .eq(PmsMidLedger::getState, DataStateEnum.ENABLE.getCode())
                .eq(PmsMidLedger::getRunStatus,RunStatus.getId())
                .in(PmsMidLedger::getVoltageLevel, list);
        return pmsMidLedgerMapper.selectList(lambdaQueryWrapper);
    }
}
