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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
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.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.DeptGetChildrenMoreDTO;
import com.njcn.device.biz.pojo.dto.DeptGetSubStationDTO;
import com.njcn.device.biz.pojo.param.DeptGetLineParam;
import com.njcn.device.pms.api.StatationStatClient;
import com.njcn.device.pms.pojo.param.PmsStatationStatInfoParam;
import com.njcn.device.pms.pojo.po.StatationStat;
import com.njcn.harmonic.pojo.po.upload.RUploadPointStatisticalDataD;
import com.njcn.harmonic.pojo.po.upload.RUploadSubstationStatisticalDataD;
import com.njcn.prepare.harmonic.enums.UploadEnum;
import com.njcn.prepare.harmonic.mapper.mysql.upload.RUploadSubstationStatisticalDataDMapper;
import com.njcn.prepare.harmonic.pojo.bo.CalculatedParam;
import com.njcn.prepare.harmonic.service.mysql.upload.IRUploadSubstationStatisticalDataDService;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 主配网变电站监测统计数据-日表 服务实现类
 * </p>
 *
 * @author xuyang
 * @since 2023-12-08
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class RUploadSubstationStatisticalDataDServiceImpl extends MppServiceImpl<RUploadSubstationStatisticalDataDMapper, RUploadSubstationStatisticalDataD> implements IRUploadSubstationStatisticalDataDService {

    private final DeptFeignClient deptFeignClient;
    private final StatationStatClient statationStatClient;
    @Override
    public void insertSubStatisticalDataDay(CalculatedParam<String> calculatedParam) {
        List<RUploadSubstationStatisticalDataD> result = new ArrayList<>();
        //获取省级单位id
        Dept data = deptFeignClient.getRootDept().getData();
        String provinceId = deptFeignClient.getDepSonIdByDeptId(data.getId()).getData().get(0);
        Dept dept = deptFeignClient.getDeptById(provinceId).getData();
        //变电站id
        List<String> subList = calculatedParam.getIdList();
        //获取变电站信息
        List<StatationStat> subInfo = getSubstationInfo(subList);
        Map<String,List<StatationStat>> subMap = subInfo.stream().collect(Collectors.groupingBy(StatationStat::getOrgId));
        //获取所有部门单位信息
        List<Dept> deptList = deptFeignClient.getAllDept().getData();
        Map<String,List<Dept>> deptMap = deptList.stream().collect(Collectors.groupingBy(Dept::getCode));
        deptMap.forEach((k,v)->{
            List<String> list = Arrays.stream(v.get(0).getPids().split(",")).map(String::trim).collect(Collectors.toList());
            if (list.size() > 1){
                RUploadSubstationStatisticalDataD rUploadSubstationStatisticalDataD = new RUploadSubstationStatisticalDataD();
                rUploadSubstationStatisticalDataD.setId(IdUtil.simpleUUID());
                rUploadSubstationStatisticalDataD.setStatisticalDate(calculatedParam.getDataDate());
                rUploadSubstationStatisticalDataD.setStatisticalType(UploadEnum.STATISTICAL_TYPE_02.getCode());
                rUploadSubstationStatisticalDataD.setProvinceId(dept.getCode());
                rUploadSubstationStatisticalDataD.setProvinceName(dept.getName());
                rUploadSubstationStatisticalDataD.setUploadStatus(Integer.parseInt(UploadEnum.UPLOAD_STATUS_0.getCode()));
                //处理层级关系 && 处理基础数据
                getDeptLevel(list,rUploadSubstationStatisticalDataD,deptList,deptMap,k,subMap);
                result.add(rUploadSubstationStatisticalDataD);
            }
        });
        if (CollectionUtil.isNotEmpty(result)){
            //查询数据如果有数据,将data_id置为null,这样就保留之前的唯一id
            LambdaQueryWrapper<RUploadSubstationStatisticalDataD> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(RUploadSubstationStatisticalDataD::getStatisticalDate,calculatedParam.getDataDate());
            List<RUploadSubstationStatisticalDataD> oldData = this.list(lambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(oldData)){
                result.forEach(item->{
                    item.setId(null);
                });
            }
            //存储数据
            this.saveOrUpdateBatchByMultiId(result);
        }
    }

    /**
     * 获取变电站信息
     * @param list
     * @return
     */
    public List<StatationStat> getSubstationInfo(List<String> list) {
        PmsStatationStatInfoParam param = new PmsStatationStatInfoParam();
        param.setPowerIds(list);
        return statationStatClient.getPowerInfo(param).getData();
    }

    /**
     * 判断当前部门的层级
     * @return
     */
    public void getDeptLevel(List<String> list, RUploadSubstationStatisticalDataD rUploadSubstationStatisticalDataD, List<Dept> deptList, Map<String,List<Dept>> map, String code, Map<String,List<StatationStat>> subMap) {
        switch (list.size()) {
            //省级
            case 2:
                rUploadSubstationStatisticalDataD.setCityId("");
                rUploadSubstationStatisticalDataD.setCountyId("");
                int ct = 0;
                //处理基础数据
                String i = deptList.stream().filter(o->Objects.equals(o.getCode(),code)).findAny().orElse(null).getId();
                List<String> cList = deptList.stream().filter(o->Objects.equals(o.getPid(),i)).map(Dept::getCode).collect(Collectors.toList());
                List<String> idList = deptList.stream().filter(o->Objects.equals(o.getPid(),i)).map(Dept::getId).collect(Collectors.toList());
                List<String> cList2 = deptList.stream().filter(o->idList.contains(o.getPid())).map(Dept::getCode).collect(Collectors.toList());
                List<String> cList3 = Stream.concat(cList.stream(), cList2.stream()).collect(Collectors.toList());
                for (String item : cList3) {
                    List<StatationStat> l = subMap.get(item);
                    if (CollectionUtil.isNotEmpty(l)){
                        ct = ct + l.size();
                    }

                }
                rUploadSubstationStatisticalDataD.setSubstationCount(ct == 0 ? null:ct);
                break;
            //市级
            case 3:
                int count = 0;
                //处理层级
                rUploadSubstationStatisticalDataD.setCityId(code);
                rUploadSubstationStatisticalDataD.setCityName(map.get(code).get(0).getName());
                rUploadSubstationStatisticalDataD.setCountyId("");
                //处理基础数据
                String id = deptList.stream().filter(o->Objects.equals(o.getCode(),code)).findAny().orElse(null).getId();
                List<String> codeList = deptList.stream().filter(o->Objects.equals(o.getPid(),id)).map(Dept::getCode).collect(Collectors.toList());
                for (String item : codeList) {
                    List<StatationStat> l = subMap.get(item);
                    if (CollectionUtil.isNotEmpty(l)){
                        count = count + l.size();
                    }
                }
                rUploadSubstationStatisticalDataD.setSubstationCount(count == 0 ? null:count);
                break;
            //县级
            case 4:
                //处理层级
                String parentCode = deptList.stream().filter(o->Objects.equals(o.getId(),list.get(3))).findFirst().orElse(null).getCode();
                rUploadSubstationStatisticalDataD.setCityId(parentCode);
                rUploadSubstationStatisticalDataD.setCityName(map.get(parentCode).get(0).getName());
                rUploadSubstationStatisticalDataD.setCountyId(code);
                rUploadSubstationStatisticalDataD.setCountyName(map.get(code).get(0).getName());
                //处理基础数据
                List<StatationStat> l = subMap.get(code);
                if (CollectionUtil.isNotEmpty(l)){
                    rUploadSubstationStatisticalDataD.setSubstationCount(l.size());
                }
                break;
            default:
                break;
        }
    }
}
