package com.ho.business.service.impl;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ho.business.common.BusiTool;
import com.ho.business.entity.*;
import com.ho.business.feignclient.FileCenterFeignClient;
import com.ho.business.feignclient.FlowFeignClient;
import com.ho.business.feignclient.UserFeignClient;
import com.ho.business.mapper.TranslateNameMapper;
import com.ho.business.mapper.TranslateProvinceMapper;
import com.ho.business.mapper.StationMapper;
import com.ho.business.service.*;
import com.ho.business.vo.req.*;
import com.ho.business.vo.resp.ProvinceStation;
import com.ho.business.vo.resp.StationInfoResp;
import com.ho.business.vo.resp.StationRespVO;
import com.ho.business.vo.resp.cockpit.*;
import com.ho.business.vo.resp.station.NationStation;
import com.ho.business.vo.resp.station.StationResp;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.entity.MyAddress;
import com.ho.common.tools.entity.SimpleUser;
import com.ho.common.tools.entity.WeatherRespVo;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
import com.ho.common.tools.util.*;
import com.ho.common.tools.vo.req.CardInfoReqVo;
import com.ho.user.api.entity.SysDept;
import com.ho.user.api.vo.req.QueryDeptReqVO;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author yule
 * @description 针对表【station】的数据库操作Service实现
 * @createDate 2022-08-25 16:03:40
 */
@Service
@Slf4j
public class StationServiceImpl implements StationService {

    @Autowired
    private StationSnService stationSnService;

    @Autowired
    private PictureService pictureService;

    @Autowired
    private StationMapper stationMapper;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private DeviceTypeService deviceTypeService;

    @Autowired
    private TypeContrastService typeContrastService;

    @Autowired
    DeviceService deviceService;

    @Autowired
    private RedisService redisService;

    @Autowired
    BusiTool busiTool;

    @Autowired
    ReallyCockpitService cockpitService;
    //假的
    @Autowired
    CockpitService notRealCockpitService;

    @Autowired
    BigDecimalUtil bigDecimalUtil;

    @Autowired
    FlowFeignClient flowFeignClient;

    @Autowired
    FileCenterFeignClient fileCenterFeignClient;

    @Autowired
    TranslateProvinceMapper translateProvinceMapper;

    @Autowired
    DynamicConfigService dynamicConfigService;

    @Value("${station.timeDifference}")
    Integer minute;

    @Value("${spring.profiles.active}")
    private String env;

    @Override
    public Station selectById(Integer id) {
        //先从缓存取数据
        String key = RedisKeyConstant.STATION + id;
        if (redisService.hasKey(key)) {
            return (Station) redisService.get(key);
        } else {
            Station station = stationMapper.selectByPrimaryKey(id);
            redisService.set(key, station, 2, TimeUnit.HOURS);
            return station;
        }
    }

    @Override
    public List<Station> selectByDeptIds(List<Integer> depts) {
        List<Station> list = new ArrayList<>();
        list = stationMapper.selectByCondition(new StationPageReqVO(), depts);
        if (list == null || list.isEmpty() || CommonConstant.ZERO.equals(list.size())) {
            return list;
        }
        return list;
    }

    @Override
    public PageResult<StationRespVO> selectPage(StationPageReqVO vo, SimpleUser user) {
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        if (vo.getStartTime() != null && vo.getEndTime() != null) {
            vo.setEndTime(DateUtil.endOfDay(vo.getEndTime()));
            vo.setStartTime(DateUtil.beginOfDay(vo.getStartTime()));
        }
        vo.setGroupId(user.getGroupId());
        List<Station> stations = stationMapper.selectByGroupIdNotExclude(vo);
        if (stations == null) {
            stations = new ArrayList<>();
        }
        PageResult pageResult1 = new PageResult();
        if (!stations.isEmpty() && stations != null) {
            PageResult pageResult = PageUtils.getPageResult(new PageInfo<>(stations));
            List<StationRespVO> stationRespVOS = getStationRespVOS(stations);
            if (stationRespVOS != null) {
                for (StationRespVO stationRespVO : stationRespVOS) {
                    if (stationRespVO.getIccId() != null) {
                        //根据电站id和卡号id进行查询套餐以及运营商
                        CardInfoReqVo cardInfo = new CardInfoReqVo();
                        cardInfo.setStationId(stationRespVO.getId());
                        cardInfo.setCard(stationRespVO.getIccId());
                        DataResult<List<CardInfoReqVo>> list = fileCenterFeignClient.selectByCondition(cardInfo);
                        List<CardInfoReqVo> data = list.getData();
                        for (CardInfoReqVo info : data) {
                            stationRespVO.setPackageType(info.getPackageType());
                            stationRespVO.setFlowMonitorId(info.getFlowMonitorId());
                        }
                    }
                }
            }
            PageInfo<StationRespVO> stationRespVOPageInfo = new PageInfo<>(stationRespVOS);
            stationRespVOPageInfo.setTotal(pageResult.getTotalRows());
            stationRespVOPageInfo.setPages(pageResult.getTotalPages());
            pageResult1 = PageUtils.getPageResult(stationRespVOPageInfo);
        } else {
            pageResult1.setList(new ArrayList());
        }
        return pageResult1;
    }

    @Override
    public List<Station> selectAll() {
        List<Station> stations = stationMapper.selectAll();
        return stations;
    }

    @Override
    public List<Station> selectByInverterFlag(Integer inverterFlag) {
        List<Station> stations = stationMapper.selectByInverterFlag(inverterFlag);
        return stations;
    }

    //根据dept_id查询电站信息
    @Override
    public List<Station> selectByDeptId(QueryDeptReqVO queryDeptReqVO) {
        Integer deptId = queryDeptReqVO.getDeptId();
        List<Station> stations = stationMapper.selectByDeptId(deptId);
        return stations;
    }

    @Override
    public List<DeviceType> selectType() {
        List<TypeContrast> typeContrasts = typeContrastService.selectStation();
        List<Integer> deviceTypeIds = new ArrayList<>();
        for (TypeContrast typeContrast : typeContrasts) {
            deviceTypeIds.add(typeContrast.getDeviceTypeId());
        }
        List<DeviceType> deviceTypeList = deviceTypeService.selectByIds(deviceTypeIds);
        Set<Integer> pIds = new HashSet<>();
        for (DeviceType deviceType : deviceTypeList) {
            pIds.add(deviceType.getPid());
        }
        List<DeviceType> deviceTypes = deviceTypeService.selectByPids(pIds);
        deviceTypeList.addAll(deviceTypes);
        return deviceTypeList;
    }

    @Override
    public List<StationRespVO> selectByIds(List<Integer> ids,String lang) {
        List<Station> stations = stationMapper.selectByIds(ids,lang);
        List<StationRespVO> stationRespVOS = getStationRespVOS(stations);
        if (stationRespVOS != null) {
            for (StationRespVO stationRespVO : stationRespVOS) {
                if (stationRespVO.getIccId() != null) {
                    //查询套餐以及运营商
                    CardInfoReqVo cardInfo = new CardInfoReqVo();
                    cardInfo.setStationId(stationRespVO.getId());
                    cardInfo.setCard(stationRespVO.getIccId());
                    DataResult<List<CardInfoReqVo>> list = fileCenterFeignClient.selectByCondition(cardInfo);
                    List<CardInfoReqVo> data = list.getData();
                    for (CardInfoReqVo info : data) {
                        stationRespVO.setPackageType(info.getPackageType());
                        stationRespVO.setFlowMonitorId(info.getFlowMonitorId());
                    }
                }
            }
        }
        return stationRespVOS;
    }

    @Override
    public List<Station> selectStationsByIds(List<Integer> ids,String lang) {
        List<Station> stations = stationMapper.selectByIds(ids,lang);
        return stations;
    }

    @Override
    @Transactional
    public Station insertStation(StationReqVO vo) {
        Station station = new Station();
        BeanUtils.copyProperties(vo, station);
        station.setCreateTime(new Date());
        station.setUpdateTime(new Date());
        //新增是默认展示
        station.setIsEnable(CommonConstant.ONE);
        //新增电站是默认不接入光伏
        station.setInverterFlag(CommonConstant.ZERO);
        updateStationInfo(station);
        //电站名称多语言处理
        if(StringUtil.isNotBlank(station.getName())){
            TranslateName translate = dynamicConfigService.getNameLanguage(station.getName());
            station.setNameEn(translate.getNameEn());
            station.setNameFra(translate.getNameFra());
            station.setNameSpa(translate.getNameSpa());
            station.setNameDe(translate.getNameDe());
            station.setNamePl(translate.getNamePl());
            station.setNameAra(translate.getNameAra());

        }
        stationMapper.insertSelective(station);
        vo.setId(station.getId());
        //新增图片数据
        pictureService.insertSrcIdAndType(vo);
        //新增logo
        pictureService.insertLogo(vo.getLogoPictureId(), vo.getId());
        //判断传入的sn集合中是否有重复
        List<String> snList = vo.getSnList();
        //新增sn编码数据
        if (snList != null) {
            stationSnService.addSnList(station.getId(), vo.getSnList());
        }
        //新增卡信息关联
        //先判断是否为空
        if (vo.getIccId() != null && !"".equals(vo.getIccId().trim())) {
            //判断是否选择套餐
            if (vo.getFlowMonitorId() == null) {
                throw new BusinessException(BaseResponseCode.PLEASE_SELECT_CORRESPOND_PACKAGE);
            }
            CardInfoReqVo cardInfo = new CardInfoReqVo();
            cardInfo.setStationId(station.getId());
            cardInfo.setCard(vo.getIccId());
            cardInfo.setFlowMonitorId(vo.getFlowMonitorId());
            cardInfo.setPackageType(vo.getPackageType());
            cardInfo.setCard(vo.getIccId());
            cardInfo.setCardStatus(CommonConstant.DELETED_FLAG);
            //判断卡输入的卡号是否存在及唯一
            CardInfoReqVo info = new CardInfoReqVo();
            info.setCard(vo.getIccId());
            DataResult<List<CardInfoReqVo>> list = fileCenterFeignClient.selectByCondition(info);
            if (list.isSuccess()) {
                if (!list.getData().isEmpty()) {
                    //说明卡号已经存在 存在则说明卡是提前录入的，只是未绑定电站关系
                    List<CardInfoReqVo> data = list.getData();
                    for (CardInfoReqVo datum : data) {
                        if (datum.getStationId() == null) {
                            datum.setStationId(station.getId());
                            fileCenterFeignClient.updateValue(datum);
                        } else {
                            throw new BusinessException(BaseResponseCode.INPUT_CARD_BOUND_STATION);
                        }
                    }
                } else {
                    fileCenterFeignClient.insertValue(cardInfo);
                }
            } else {
                //说明卡号不存在，则进行新增
                fileCenterFeignClient.insertValue(cardInfo);
            }
        }
        return station;
    }

    /**
     * 更新电站中的地区信息以及更新气象数据
     * @param station
     */
    private void updateStationInfo(Station station) {
        MyAddress address = AbroadAddressUtils.getAddress(String.valueOf(station.getLatitude()),String.valueOf(station.getLongitude()));
        if (null != address) {
            String adCode = address.getCityCode();
            if(StringUtil.isEmpty(adCode)){
                adCode = String.format("%05d", new Random().nextInt(100000));
            }
            station.setAdCode(adCode);
            station.setDistrict(address.getDistrict());
            station.setCity(address.getCity());
            station.setProvince(address.getProvince());
            TranslateName pro = dynamicConfigService.getNameLanguage(station.getProvince());
            station.setProvinceEn(pro.getNameEn());
            station.setProvinceFra(pro.getNameFra());
            station.setProvinceSpa(pro.getNameSpa());
            station.setProvinceDe(pro.getNameDe());
            station.setProvincePl(pro.getNamePl());
            station.setProvinceAra(pro.getNameAra());
            station.setNation(address.getNation());
            TranslateName na = dynamicConfigService.getNameLanguage(station.getNation());
            station.setNationEn(na.getNameEn());
            station.setNationFra(na.getNameFra());
            station.setNationSpa(na.getNameSpa());
            station.setNationDe(na.getNameDe());
            station.setNationPl(na.getNamePl());
            station.setNationAra(na.getNameAra());
            String key = RedisKeyConstant.WEATHER_PROVINCE_CITY + adCode;
            if (!redisService.hasKey(key)) {
                WeatherRespVo weatherRespVo = AbroadWeatherUtils.getWeatherRespVo(String.valueOf(station.getLatitude()),String.valueOf(station.getLongitude()));
                if (weatherRespVo != null) {
                    weatherRespVo.setUpdateTime(System.currentTimeMillis());
                    redisService.set(key, weatherRespVo);
                }
            }
        }
    }


    @Override
    public Station selectByName(String name) {
        Station station = stationMapper.selectByName(name);
        return station;
    }

    @Override
    public List<Station> getByName(String name) {
        List<Station> stations = stationMapper.getByName(name);
        return stations;
    }

    @Override
    @Transactional
    public void deletedByIds(List<Integer> ids) {
        for (Integer id : ids) {
            Station station = new Station();
            station.setId(id);
            station.setDeleted(CommonConstant.DELETED_FLAG);
            stationMapper.updateByPrimaryKeySelective(station);
            //删除缓存
            String key = RedisKeyConstant.STATION + id;
            if (redisService.hasKey(key)) {
                redisService.delete(key);
            }
        }
        //删除电站相关图片数据
        pictureService.deletedBySrcIdsAndType(ids);

        //删除电站的sn编码
        stationSnService.deleteByStationIds(ids);
    }

    @Override
    public void update(StationPutReqVO vo) {
        Station station = new Station();
        BeanUtils.copyProperties(vo, station);
        station.setUpdateTime(new Date());
        if (vo.getGridTime() != null) {
            station.setGridTime(DateUtil.parse(vo.getGridTime(), CommonConstant.DATE_YMD));
        }
        //经纬度都相同的时候，不需要调用地址逆转换
        Station s = stationMapper.selectByPrimaryKey(vo.getId());
        if (!(vo.getLongitude().compareTo(s.getLongitude()) == 0 && vo.getLatitude().compareTo(s.getLatitude()) == 0)) {
            updateStationInfo(station);
        }
        // 电站名称多语言处理,名称相同是不需要处理
        if(StringUtil.isNotBlank(station.getName())
            && !(vo.getName().equals(s.getName()))){
            TranslateName translate = dynamicConfigService.getNameLanguage(station.getName());
            station.setNameEn(translate.getNameEn());
            station.setNameFra(translate.getNameFra());
            station.setNameSpa(translate.getNameSpa());
            station.setNameDe(translate.getNameDe());
            station.setNamePl(translate.getNamePl());
            station.setNameAra(translate.getNameAra());

        }
        station.setIccId(vo.getIccId());
        stationMapper.updateByPrimaryKeySelective(station);
        //调用device方法 直接进行修改
        int i = deviceService.updateByStationId(station);
        //删除缓存
        String key = RedisKeyConstant.STATION + vo.getId();
        if (redisService.hasKey(key)) {
            redisService.delete(key);
        }
        //更新图片
        pictureService.updatePicture(vo);

        //更新sn编码
        //先删除之前的sn编码数据
        List<Integer> stationIds = new ArrayList<>();
        stationIds.add(vo.getId());
        stationSnService.update(stationIds, vo);
        if (s.getIccId() != null) {
            CardInfoReqVo info = new CardInfoReqVo();
            info.setStationId(s.getId());
            DataResult<List<CardInfoReqVo>> list = fileCenterFeignClient.selectByCondition(info);
            if (list.isSuccess()) {
                if (!list.getData().isEmpty()) {
                    //说明卡号已经存在 存在则说明卡是提前录入的，只是未绑定电站关系
                    List<CardInfoReqVo> data = list.getData();
                    for (CardInfoReqVo datum : data) {
                        if (datum.getStationId() != null) {
                            if (datum.getStationId().equals(s.getId())) {
                                datum.setStationId(null);
                                fileCenterFeignClient.updateValue(datum);
                            }
                        }
                    }
                }
            }
        }
        //更新卡号以及运营商
        if (vo.getIccId() != null && !"".equals(vo.getIccId().trim())) {
            //判断是否选择套餐
            if (vo.getFlowMonitorId() == null) {
                throw new BusinessException(BaseResponseCode.PLEASE_SELECT_CORRESPOND_PACKAGE);
            }
            CardInfoReqVo cardInfo = new CardInfoReqVo();
            cardInfo.setStationId(station.getId());
            cardInfo.setCard(vo.getIccId());
            cardInfo.setFlowMonitorId(vo.getFlowMonitorId());
            cardInfo.setPackageType(vo.getPackageType());
            cardInfo.setCard(vo.getIccId());
            cardInfo.setCardStatus(CommonConstant.DELETED_FLAG);
            //判断卡输入的卡号是否存在及唯一
            CardInfoReqVo info = new CardInfoReqVo();
            info.setCard(vo.getIccId());
            DataResult<List<CardInfoReqVo>> list = fileCenterFeignClient.selectByCondition(info);
            if (list.isSuccess()) {
                if (!list.getData().isEmpty()) {
                    //说明卡号已经存在 存在则说明卡是提前录入的，只是未绑定电站关系
                    List<CardInfoReqVo> data = list.getData();
                    for (CardInfoReqVo datum : data) {
                        if (datum.getStationId() == null) {
                            datum.setStationId(station.getId());
                            fileCenterFeignClient.updateValue(datum);
                        } else {
                            throw new BusinessException(BaseResponseCode.INPUT_CARD_BOUND_STATION);
                        }
                    }
                } else {
                    fileCenterFeignClient.insertValue(cardInfo);
                }
            } else {
                //说明卡号不存在，则进行新增
                fileCenterFeignClient.insertValue(cardInfo);
            }
        } else {
            //当输入卡号为空的时候需要将卡信息所对应的电站信息删除
            //先判断更改前的卡号是否为空
            if (s.getIccId() != null) {
                //根据卡号和电站进行查询然后清空电站信息
                CardInfoReqVo info = new CardInfoReqVo();
                info.setCard(s.getIccId());
                info.setStationId(s.getId());
                DataResult<List<CardInfoReqVo>> list = fileCenterFeignClient.selectByCondition(info);
                if (list.isSuccess()) {
                    if (!list.getData().isEmpty()) {
                        List<CardInfoReqVo> data = list.getData();
                        for (CardInfoReqVo datum : data) {
                            //todo
                            datum.setStationId(null);
                            fileCenterFeignClient.updateValue(datum);
                        }
                    }
                }
            }
        }
    }

    @Override
    public Station selectByNameAndId(String name, Integer id, Integer deptId) {
        Station station = stationMapper.selectByNameAndId(name, id, deptId);
        return station;
    }

    @Override
    @Cacheable(cacheManager = "fiveMinuteCacheManager", value = "stationBySn", key = "#sn", sync = true)
    public Station selectBySn(String sn) {
        StationSn stationSn = stationSnService.selectBySn(sn);
        if (stationSn == null) {
            return null;
        }
        Station station = stationMapper.selectByPrimaryKey(stationSn.getStationId());
        return station;
    }

    @Override
    public List<Station> selectByGroupId(Integer groupId) {
        StationPageReqVO vo = new StationPageReqVO();
        vo.setGroupId(groupId);
        List<Station> stations = stationMapper.selectByGroupIdNotExclude(vo);
        return stations;
    }

    @Override
    public List<ProvinceStation> getProvinceStationList(SimpleUser user) {
        List<Station> stations = new ArrayList<>();
        //open环境只查询机构下面的
//        if (EnvConstant.DEV.equals(env) || EnvConstant.OPEN.equals(env)) {
        //开放OPEN环境查询用户登陆信息中的电站
        List<Integer> stationIds = user.getStationIds();
        if (stationIds != null && !stationIds.isEmpty()) {
            StationPageReqVO vo = new StationPageReqVO();
            vo.setIds(stationIds);
            stations = stationMapper.selectByGroupIdNotExclude(vo);
        }
//        } else {
//            stations = stationMapper.selectByGroupId(user.getGroupId(), new StationPageReqVO());
//        }
        Map<String, List<Station>> provincesMap = stations.stream().filter(i->i.getProvince()!=null).sorted(Comparator.comparing(Station::getName)).collect(Collectors.groupingBy(s -> {
            return s.getProvince().replace(CommonConstant.ChineseProvinces.PROVINCE, "").replace(CommonConstant.ChineseProvinces.CITY, "");
        }));
        //创建返回值集合
        List<ProvinceStation> list = new ArrayList<>();
        provincesMap.forEach((k, v) -> {
            ProvinceStation provinceStation = new ProvinceStation();
            provinceStation.setName(k);
            provinceStation.setList(v);
            list.add(provinceStation);
        });
        return list;
    }

    /**
     * 把station集合转化为StationRespVO集合
     *
     * @param stations
     * @return
     */
    private List<StationRespVO> getStationRespVOS(List<Station> stations) {
        List<StationRespVO> stationRespVOS = new ArrayList<>();
        //遍历集合stations获取到deptIds和typeIds的集合
        List<QueryDeptReqVO> deptIds = new ArrayList<>();
        List<Integer> typeIds = new ArrayList<>();
        stations.stream().forEach(s -> {
            StationRespVO stationRespVO = new StationRespVO();
            BeanUtils.copyProperties(s, stationRespVO);
            QueryDeptReqVO queryDeptReqVO = new QueryDeptReqVO();
            queryDeptReqVO.setDeptId(s.getDeptId());
            deptIds.add(queryDeptReqVO);
            typeIds.add(s.getType());
            stationRespVOS.add(stationRespVO);
        });
        //通过deptIds查询的结果,获取sysDept map的集合(key = id,value = Name)
        DataResult<List<SysDept>> result = userFeignClient.queryDept(deptIds);
        List<SysDept> deptList = result.getData();
        Map<Integer, String> depts = new HashMap<>();
        if (!deptList.isEmpty()) {
            depts = deptList.stream().collect(Collectors.toMap(SysDept::getId, SysDept::getName));
        }
        //type使用字典表
        //通过typeIds查询的结果,获取deviceType map的集合(key = id,value = Name)
        /*List<DeviceType> deviceTypeList = deviceTypeService.selectByIds(typeIds);
        Map<Integer, String> deviceTypes = new HashMap<>();
        if (!deviceTypeList.isEmpty()) {
            deviceTypes = deviceTypeList.stream().collect(Collectors.toMap(DeviceType::getId, DeviceType::getName));
        }*/

        for (StationRespVO stationRespVO : stationRespVOS) {
            stationRespVO.setDeptName(depts.get(stationRespVO.getDeptId()));
            //stationRespVO.setTypeName(deviceTypes.get(stationRespVO.getType()));
        }
        return stationRespVOS;
    }


    @Override
    public CockForStationResp getStationCockpitValue(SimpleUser user) {
        CockForStationResp cockForStationResp = new CockForStationResp();
        //返回对象
        CumulativeRespVO cumulative = cockpitService.getCumulative(user);
        if (cumulative != null) {
            //安全运行天数
            cockForStationResp.setSafeOperationDays(cumulative.getSafeOperationDays());
            //光伏累计发电量总和
            cockForStationResp.setPvPowerGeneration(cumulative.getPvPowerGeneration());
            //累计CO2减排
            cockForStationResp.setCo2Reductions(cumulative.getCo2Reductions());
            //累计森林减伐(树)
            cockForStationResp.setTreeReductions(cumulative.getTreeReductions());
            //累计节约石油
            cockForStationResp.setPetroleumReductions(cumulative.getPetroleumReductions());
            //累计节约煤炭
            cockForStationResp.setCoalReductions(cumulative.getCoalReductions());
        }
        GroupDataRespVo groupDataRespVo = cockpitService.getGroupData(user);
        if (groupDataRespVo != null) {
            //光伏装机量
            cockForStationResp.setPvCapacity(groupDataRespVo.getPvCapacity());
            //光伏当前总功率
            cockForStationResp.setPvCurrentPower(groupDataRespVo.getPvCurrentPower());
        }
        //电站总数、离线电站、故障电站
        ConditionMonitoringRespVO conditionMonitoring = notRealCockpitService.getConditionMonitoring(user);
        if (conditionMonitoring != null) {
            //电站总数
            cockForStationResp.setTotalStation(conditionMonitoring.getTotalStation());
            //离线电站
            cockForStationResp.setOfflineStation(conditionMonitoring.getOfflineStation());
            //故障电站
            cockForStationResp.setFaultStation(conditionMonitoring.getFaultStation());
            //设备在线率
            cockForStationResp.setOnlineDeviceRate(conditionMonitoring.getOnlineDeviceRate());
        }
        //电站排名
        List<StationOperationRespVO> stationPowerSortList = notRealCockpitService.getStationOperation(user);
        if (stationPowerSortList != null) {
            for (StationOperationRespVO stationOperationRespVO : stationPowerSortList) {
                bigDecimalUtil.ifIsNUll(stationOperationRespVO);
                bigDecimalUtil.keepTwoDecimalPlaces(stationOperationRespVO);
            }
            cockForStationResp.setStationPowerList(stationPowerSortList);
        }
        return cockForStationResp;
    }

    /**
     * 通过电站名称模糊查找电站
     *
     * @param vo
     * @return
     */
    @Override
    public List<Station> selectByDimName(WorkOrderStationReqVO vo, SimpleUser user) {
        StationPageReqVO stationPageReqVO = new StationPageReqVO();
        stationPageReqVO.setName(vo.getName());
        stationPageReqVO.setGroupId(user.getGroupId());
        List<Station> stations = stationMapper.selectByGroupIdNotExclude(stationPageReqVO);
        return stations;
    }

    //集团下离线电站个数
    @Override
    public List<Station> getOfflineStations(List<Station> stations) {
        List<Station> offlineStations = new ArrayList<>();
        //缓存中有对应sn的值，就认为该电站在线,否则离线
        for (Station station : stations) {
            //sn离线的个数
            int offSize = 0;
            //一个站有多个sn,只有每个sn间隔都大于5
            List<StationSn> snList = stationSnService.getSnListByStationId(station.getId());
            int snSize = snList.size();
            for (StationSn stationSn : snList) {
                String key = RedisKeyConstant.HEARTBEAT + stationSn.getSn();
                if (redisService.hasKey(key)) {
                    Date updateTime = (Date) redisService.hget(key, "updateTime");
                    if (updateTime != null) {
                        long between = DateUtil.between(updateTime, new Date(), DateUnit.MINUTE);
                        if (between > minute) {
                            //是一个离线的
                            offSize++;
                        }
                    }
                }
                //没有缓存 就是离线的
                else {
                    offSize++;
                }
            }
            //判断一个电站是否离线，根据
            if (offSize == snSize) {
                offlineStations.add(station);
            }
        }
        return offlineStations;
    }


    @Override
    public List<Station> selectStatistics(Integer deleted, Integer dailyCount) {
        List<Station> list = stationMapper.selectStatistics(deleted, dailyCount);
        return list;
    }

    @Override
    public PageResult<StationRespVO> selectPageList(StationPageListReqVO stationPageReqVO) {
        PageHelper.startPage(stationPageReqVO.getPageNum(), stationPageReqVO.getPageSize());
        List<StationInfoResp> list = stationMapper.selectByParam(stationPageReqVO);
        return PageUtils.getPageResult(new PageInfo<>(list));
    }

    @Override
    public Station selectByPrimaryKey(Integer id) {
        return stationMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Map<String,String>> getTermDictionary(String language){
        List<Map<String,String>> result = stationMapper.getTermDictionary(language);
        return result;
    }

    @Override
    public List<Station> selectStationByCondition(StationPageReqVO vo) {
        List<Station> stationList = stationMapper.selectByGroupIdNotExclude(vo);
        return stationList;
    }

    @Override
    public int updateStationList(List<Station> list) {
        int count = stationMapper.updateStationList(list);
        return count;
    }

    @Override
    public StationResp getNationStationList(SimpleUser user) {
        StationResp resp = new StationResp();
        Integer stationId = null;
        List<Station> stations = new ArrayList<>();
        List<Integer> stationIds = user.getStationIds();
        if (stationIds != null && !stationIds.isEmpty()) {
            StationPageReqVO vo = new StationPageReqVO();
            vo.setIds(stationIds);
            vo.setLang(user.getLang());
            stations = stationMapper.selectByGroupIdNotExclude(vo);
        }
        List<NationStation> nationList = new ArrayList<>();
        Map<String, List<Station>> nationMap = stations.stream().filter(i -> i.getNation() != null).collect(Collectors.groupingBy(Station::getNation));
        for (Map.Entry<String, List<Station>> m : nationMap.entrySet()) {
            List<Station> stationList = m.getValue();
            Map<String, List<Station>> pMap = stationList.stream().filter(i -> i.getProvince() != null).sorted(Comparator.comparing(Station::getName)).collect(Collectors.groupingBy(s -> {
                return s.getProvince().replace(CommonConstant.ChineseProvinces.PROVINCE, "").replace(CommonConstant.ChineseProvinces.CITY, "");
            }));
            if(stationId == null){
                for (Station s:stationList) {
                    if(s.getProvince() != null){
                        stationId = s.getId();
                        break;
                    }
                }
            }
            List<ProvinceStation> list = new ArrayList<>();
            pMap.forEach((k, v) -> {
                ProvinceStation provinceStation = new ProvinceStation();
                provinceStation.setName(k);
                provinceStation.setList(v);
                list.add(provinceStation);
            });
            NationStation nationStation = new NationStation();
            nationStation.setName(m.getKey());
            nationStation.setList(list);
            nationList.add(nationStation);
        }
        resp.setStationId(stationId);
        resp.setList(nationList);
        return resp;
    }
}
