package org.springblade.modules.nh.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springblade.common.cache.DictCache;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.enums.DictEnum;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.nh.excel.PowerStationExcel;
import org.springblade.modules.nh.excel.PowerStationImport;
import org.springblade.modules.nh.mapper.*;
import org.springblade.modules.nh.pojo.dto.MonitorEntryStatDTO;
import org.springblade.modules.nh.pojo.dto.PowerStationDTO;
import org.springblade.modules.nh.pojo.dto.StationDTO;
import org.springblade.modules.nh.pojo.dto.open.YXPowerStationDTO;
import org.springblade.modules.nh.pojo.entity.*;
import org.springblade.modules.nh.pojo.vo.*;
import org.springblade.modules.nh.service.*;
import org.springblade.modules.nh.wrapper.PowerStationWrapper;
import org.springblade.modules.operation.excel.EntryPaymentTimeExcel;
import org.springblade.modules.operation.excel.EntrySiteExcel;
import org.springblade.modules.operation.mapper.OperationSiteEmployeeMapper;
import org.springblade.modules.operation.pojo.entity.OperationSiteEntity;
import org.springblade.modules.operation.pojo.vo.EmpAuthVo;
import org.springblade.modules.operation.pojo.vo.OperationSiteVO;
import org.springblade.modules.operation.service.impl.OperationSiteServiceImpl;
import org.springblade.modules.operation.service.impl.PlatformEmployeeServiceImpl;
import org.springblade.modules.order.constant.OrderConstants;
import org.springblade.modules.order.mapper.OperationOrderMapper;
import org.springblade.modules.order.pojo.entity.OperationOrderEntity;
import org.springblade.modules.order.pojo.vo.OrderHomeVo;
import org.springblade.modules.order.pojo.vo.OrderListConditionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scala.collection.mutable.StringBuilder;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 电站 服务实现类
 *
 * @author AlexWang
 * @since 2024-05-31
 */
@Service
@AllArgsConstructor
public class PowerStationServiceImpl extends BaseServiceImpl<PowerStationMapper, PowerStationEntity> implements IPowerStationService {

	private final IMonitorEntryStatService entryStatService;

	private final MonitorEntryDailyStatMapper dailyStatMapper;
	private final MonitorEntryMonthStatMapper monthStatMapper;
	private final MonitorEntryYearStatMapper yearStatMapper;

	private final MonitorEntryStatMapper entryStatMapper;

	private final AlarmInfoMapper alarmInfoMapper;

	private final DeviceMapper deviceMapper;

	private final MonitorInverterStatMapper monitorInverterStatMapper;

	private final BladeRedis bladeRedis;
	@Autowired
	OperationSiteServiceImpl siteService;
	@Autowired
	OperationSiteEmployeeMapper employeeMapper;

	@Autowired
	PlatformEmployeeServiceImpl platformEmployeeService;

	private final OperationOrderMapper operationOrderMapper;





	private final IInverterDataService inverterDataService;


	@Override
	public IPage<PowerStationVO> selectPowerStationPage(IPage<PowerStationVO> page, StationDTO powerStation) {
		BladeUser user = AuthUtil.getUser();
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			powerStation.setOmProviderId(site.getId());
		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			powerStation.setOmProviderId(authVo.getSiteId());
			powerStation.setProvince(authVo.getProvinces());
			powerStation.setCity(authVo.getCity());
			powerStation.setDistrict(authVo.getArea());
		}else if("4".equals(user.getDeptId())){ //平台员工
			EmpAuthVo authVoP=platformEmployeeService.findPlatEmpAuthByUserId(user.getUserId());
			if(authVoP!= null){
				powerStation.setSiteIds(authVoP.getSiteId());
				if(StringUtil.isBlank(powerStation.getProvince())){
					powerStation.setProvince(authVoP.getProvinces());
				}

				powerStation.setCity(authVoP.getCity());
				powerStation.setDistrict(authVoP.getArea());
				powerStation.setEntryIds(authVoP.getEntryId());
				if(StringUtil.isBlank(powerStation.getCapitalName())){
					powerStation.setCapitalName(authVoP.getPartnerName());
				}
			}

		}
//		if(powerStation.getEto() == null){
//			powerStation.setEto(new BigDecimal("1"));
//		}

	//	powerStation.setApplyStatus(1);
		List<PowerStationVO> list = baseMapper.selectPowerStationPage(page, powerStation);
		for(PowerStationVO vo : list){
			vo.setEntryStat(entryStatService.getByPowerStation(vo));
			if(isDuringTime(vo)){
				String during = CommonUtil.calDuringToNow(vo.getLastStatusStart());
				if(vo.getStatus()==2){
					vo.setErrDuring(during);
				}else{
					vo.setLastDuringStr(during);
				}

			}else{
				vo.setErrDuring("");
				vo.setLastDuringStr("");
			}
			vo.setAddress(vo.getAddress().replaceAll(vo.getProvince()+vo.getCity(),""));
		}
		return page.setRecords(list);
	}

	private boolean isDuringTime(PowerStationVO vo){
		boolean ret  = false;
		String today = DateUtil.format(new Date(),"yyyyMMdd");
		Date start = DateUtil.parse(today+"080000","yyyyMMddHHmmss");
		Date end = DateUtil.parse(today+"180000","yyyyMMddHHmmss");
		Date now = new Date();
		if(vo.getStatus()!=1){
			if(end.after(now) && start.before(now)){
				ret = true;
			}
		}
		return ret;
	}

	@Override
	public PowerStationVO getStationDetail(PowerStationEntity powerStation) {
		PowerStationEntity entity=null;
		if(powerStation.getId()!= null){
			 entity=  this.getById(powerStation.getId());
		}else if(StringUtil.isNotBlank(powerStation.getStationCode())){
			 entity=  this.getStationDetailByPowCode(powerStation.getStationCode());
		}
		PowerStationVO vo = PowerStationWrapper.build().entityVO(entity);
		vo.setEntryStat(entryStatService.realTimeDetail(vo));
		vo.setOverviewVo(alarmInfoMapper.stationAlarm(vo.getOutStationId()));
		return vo;
	}

	@Override
	public PowerStationEntity getStationDetailByPowCode(String powCode) {
		return baseMapper.getStationDetailByPowCode(powCode);
	}

	@Override
	public List<PowerStationDTO> getStationListByPowCode(String powCode) {
		BladeUser user = AuthUtil.getUser();
		String siteId = null;
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			siteId = site.getId();
		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			siteId = authVo.getSiteId();
		}

		return baseMapper.getStationListByPowCode(powCode,siteId);
	}


	@Override
	public HomeOverviewVO staticsHomeOverview(Long traderId) {
		List<String> outStationIds = this.baseMapper.getOutStationIds();
		HomeOverviewVO vo = monitorInverterStatMapper.staticsHomeViewData(outStationIds);
		StationDTO powerStation=new StationDTO();
		OrderListConditionVo ordervo = new OrderListConditionVo();
		BladeUser user = AuthUtil.getUser();
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			powerStation.setOmProviderId(site.getId());
			ordervo.setSiteId(site.getId());
		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			powerStation.setOmProviderId(authVo.getSiteId());
			powerStation.setProvince(authVo.getProvinces());
			powerStation.setCity(authVo.getCity());
			powerStation.setDistrict(authVo.getArea());
			ordervo.setSiteId(authVo.getId());
			ordervo.setProvinces(authVo.getProvinces());
			ordervo.setCity(authVo.getCity());
			ordervo.setArea(authVo.getArea());
		}else if("4".equals(user.getDeptId())){ //平台员工
			EmpAuthVo authVoP=platformEmployeeService.findPlatEmpAuthByUserId(user.getUserId());
			if(authVoP!= null){
				powerStation.setSiteIds(authVoP.getSiteId());
				powerStation.setProvince(authVoP.getProvinces());
				powerStation.setCity(authVoP.getCity());
				powerStation.setDistrict(authVoP.getArea());
				powerStation.setEntryIds(authVoP.getEntryId());
				powerStation.setCapitalName(authVoP.getPartnerName());
				ordervo.setSiteIds(authVoP.getSiteId());
				ordervo.setProvinces(authVoP.getProvinces());
				ordervo.setCity(authVoP.getCity());
				ordervo.setArea(authVoP.getArea());
				ordervo.setEntryIds(authVoP.getEntryId());
			}

		}
		List<StaticsStatusVO> status = this.baseMapper.staticsStatus(powerStation);
		status.forEach(item -> {
			switch (item.getStatus()){
				case 1:vo.setOnlineCnt(item.getNum());break;
				case 2:vo.setOfflineCnt(item.getNum());break;
				case 3:vo.setFaultCnt(item.getNum());break;
			}
		});
		vo.setTreeCount(vo.getEtd()*0.0054);
		vo.setTotalTreeCount(vo.getEto()*0.0054);

		HomeOverviewVO temp = alarmInfoMapper.statusAllAlarm();
		vo.setAlarmDealed(temp.getAlarmDealed());
		vo.setAlarmDealing(temp.getAlarmDealing());
		vo.setAlarmUnDeal(temp.getAlarmUnDeal());

		OrderHomeVo orderHomeVo = operationOrderMapper.findOrderHomeIndex(ordervo);
		vo.setClzCount(orderHomeVo.getFwzCount());
		vo.setYwcCount(orderHomeVo.getYwcCount());
		return vo;
	}

	@Override
	public void updatePowerStationBrand() {
		this.baseMapper.updatePowerStationBrand();
	}

	@Override
	public List<PowerStationExcel> exportPowerStation(StationDTO powerSta) {
	//	List<PowerStationEntity> powerStationList = this.list(queryWrapper);
		BladeUser user = AuthUtil.getUser();
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			powerSta.setOmProviderId(site.getId());
		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			powerSta.setOmProviderId(authVo.getSiteId());
			powerSta.setProvince(authVo.getProvinces());
			powerSta.setCity(authVo.getCity());
			powerSta.setDistrict(authVo.getArea());
		}else if("4".equals(user.getDeptId())){ //平台员工
			EmpAuthVo authVoP=platformEmployeeService.findPlatEmpAuthByUserId(user.getUserId());
			if(authVoP!= null){
				powerSta.setSiteIds(authVoP.getSiteId());
				if(StringUtil.isBlank(powerSta.getProvince())){
					powerSta.setProvince(authVoP.getProvinces());
				}

				powerSta.setCity(authVoP.getCity());
				powerSta.setDistrict(authVoP.getArea());
				powerSta.setEntryIds(authVoP.getEntryId());
				if(StringUtil.isBlank(powerSta.getCapitalName())){
					powerSta.setCapitalName(authVoP.getPartnerName());
				}
			}
		}

	/*	if(powerSta.getEto() == null){
			powerSta.setEto(new BigDecimal("1"));
		}
*/
		//powerSta.setApplyStatus(1);
		List<PowerStationVO> powerStationList = baseMapper.selectPowerStationListEx(powerSta);

	//	List<String> outIds = powerStationList.stream().map(PowerStationEntity::getOutStationId).collect(Collectors.toList());;

		List<MonitorEntryStatEntity> statEntityList = entryStatService.list();
		Map<String, MonitorEntryStatEntity> outIdToObjMap = statEntityList.stream()  // 将list转换为Stream
			.collect(Collectors.toMap(MonitorEntryStatEntity::getOutStationId, obj -> obj));

		List<PowerStationExcel> excelList = Lists.newArrayList();
		powerStationList.forEach(powerStation -> {
			PowerStationExcel excel = BeanUtil.copyProperties(powerStation, PowerStationExcel.class);
			excel.setStatusStr(DictCache.getValue(DictEnum.POWER_STATION_STATUS, powerStation.getStatus()));
			//excel.setAddress(powerStation.getDistrict()+powerStation.getAddress());

			String outStationId = powerStation.getOutStationId();

			if(StringUtil.isNotBlank(outStationId)){
				MonitorEntryStatEntity entryStat = new MonitorEntryStatEntity();
				for(String str:powerStation.getOutStationId().split(",")){
					MonitorEntryStatEntity entryStatEntity = outIdToObjMap.get(str);
					if(entryStatEntity != null){
						if(entryStat.getId()==null){
							BeanUtil.copyProperties(entryStatEntity,entryStat);
						}else{
							entryStat.setEtd(CommonUtil.sum(entryStat.getEtd(),entryStatEntity.getEtd()));
							entryStat.setEtm(CommonUtil.sum(entryStat.getEtm(),entryStatEntity.getEtm()));
							entryStat.setEty(CommonUtil.sum(entryStat.getEty(),entryStatEntity.getEty()));
							entryStat.setEta(CommonUtil.sum(entryStat.getEta(),entryStatEntity.getEta()));
						}
					}
				}
			/*	LambdaQueryWrapper<MonitorEntryStatEntity>  queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.in(MonitorEntryStatEntity::getOutStationId,stationIds);
				List<MonitorEntryStatEntity> entryStatList = entryStatService.list(queryWrapper);*/


					if(entryStat.getFisGenerateTime()!=null){
						excel.setFisGenTime(DateUtil.formatDateTime(entryStat.getFisGenerateTime()));
					}
					excel.setEtd(entryStat.getEtd());
					excel.setEtm(entryStat.getEtm());
					excel.setEty(entryStat.getEty());
					excel.setEto(entryStat.getEta());

			}
			excel.initDefaultData();
			//Integer brand=powerStation.getBrand();
			excel.setBrand(DictCache.getValue(DictEnum.DEVICE_BRAND, powerStation.getBrand()));
			excel.setActualCapacity(powerStation.getActualCapacity()!=null?powerStation.getActualCapacity().doubleValue():0L);
			if(isDuringTime(PowerStationWrapper.build().entityVO(powerStation))){
				String during = CommonUtil.calDuringToNow(powerStation.getLastStatusStart());
				if(powerStation.getStatus()==2){
					excel.setErrDuring(during);
				}else{
					excel.setLastDuringStr(during);
				}

			}else{
				excel.setErrDuring("");
				excel.setLastDuringStr("");
			}

			excelList.add(excel);
			//			powerStation.setTypeName(DictCache.getValue(DictEnum.YES_NO, PowerStation.getType()));
		});
		return excelList;
	}

	@Override
	public List<InverterTreeVO> getLazyTree(String parentId, String parentName, int level) {

		List<InverterTreeVO> result = Lists.newArrayList();

		LambdaQueryWrapper<PowerStationEntity> queryWrapper = new LambdaQueryWrapper<>();

		BladeUser user = AuthUtil.getUser();
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			queryWrapper.eq(PowerStationEntity::getOmProviderId,site.getId());
		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			queryWrapper.eq(PowerStationEntity::getOmProviderId,authVo.getSiteId())
				.eq(PowerStationEntity::getProvince,authVo.getProvinces())
				.eq(PowerStationEntity::getCity,authVo.getCity())
				.eq(PowerStationEntity::getDistrict,authVo.getArea());
		}else if("4".equals(user.getDeptId())){ //平台员工
			EmpAuthVo authVoP=platformEmployeeService.findPlatEmpAuthByUserId(user.getUserId());
			if(authVoP!= null){
				queryWrapper.eq(PowerStationEntity::getOmProviderId,authVoP.getSiteId());
			}
		}

		switch (level) {
			case 0:{
				queryWrapper
					.select(PowerStationEntity::getCapitalCode,PowerStationEntity::getCapitalName)
					.groupBy(PowerStationEntity::getCapitalName);
				List<Map<String,Object>> listMaps = this.listMaps(queryWrapper);
				listMaps.forEach(res->{
					InverterTreeVO vo = new InverterTreeVO();
					vo.setHasChildren(true);
					String code = (String) res.get("capital_code");
					String name = (String) res.get("capital_name");
					vo.setId(name);
					vo.setParentId("0");
					vo.setKey(code);
					vo.setTitle(name);
					vo.setValue(code);
					result.add(vo);
				});
				break;
			}
			case 1:{
				queryWrapper
					.select(PowerStationEntity::getProjectCompanyId,PowerStationEntity::getProjectCompanyName)
					.eq(PowerStationEntity::getCapitalName, parentName)
					.groupBy(PowerStationEntity::getProjectCompanyName);
				List<Map<String,Object>> listMaps = this.listMaps(queryWrapper);
				listMaps.forEach(res->{
					InverterTreeVO vo = new InverterTreeVO();
					vo.setHasChildren(true);
					String code = (String) res.get("project_company_id");
					String name = (String) res.get("project_company_name");
					vo.setId(name);
					vo.setParentId(parentName);
					vo.setKey(code);
					vo.setTitle(name);
					vo.setValue(code);
					result.add(vo);
				});
				break;
			}
			case 2:{
				queryWrapper
					.select(PowerStationEntity::getCity)
					.eq(PowerStationEntity::getProjectCompanyName, parentName)
					.groupBy(PowerStationEntity::getCity);
				List<Map<String,Object>> listMaps = this.listMaps(queryWrapper);
				listMaps.forEach(res->{
					String city = (String) res.get("city");
					InverterTreeVO vo = new InverterTreeVO();
					vo.setId(parentName+city);
					vo.setParentId(parentName);
					vo.setHasChildren(true);
					vo.setKey(city);
					vo.setTitle(city);
					vo.setValue(city);
					result.add(vo);
				});
				break;
			}
			case 3:{
				queryWrapper.eq(PowerStationEntity::getCity, parentName)
					.eq(PowerStationEntity::getProjectCompanyName, parentId);
				List<PowerStationEntity> listMaps = this.list(queryWrapper);
				Set<String> idSet = new HashSet<>();
				listMaps.forEach(res->{
					String treeId = parentName+"-"+res.getAgentName();
					InverterTreeVO vo = new InverterTreeVO();
					vo.setHasChildren(true);
					vo.setId(treeId);
					vo.setParentId(parentId+parentName);
					vo.setKey(parentName);
					vo.setTitle(res.getAgentName());
					vo.setValue(res.getId()+"");
					if(!idSet.contains(treeId)){
						result.add(vo);
						idSet.add(treeId);
					}

				});
				break;
			}
			case 4:{
				queryWrapper.eq(PowerStationEntity::getCity, parentId)
					.eq(PowerStationEntity::getAgentName, parentName);
				List<PowerStationEntity> listMaps = this.list(queryWrapper);
				listMaps.forEach(res->{
					InverterTreeVO vo = new InverterTreeVO();
					vo.setHasChildren(false);
					vo.setId(res.getId()+"");
					vo.setParentId(parentId+parentName);
					vo.setKey(res.getId()+"");
					vo.setTitle(res.getOwnerName()+"-"+res.getActualCapacity()+"KW-"+res.getStationCode());
					vo.setValue(res.getId()+"");
					result.add(vo);
				});
				break;
			}
		}


		return result;
	}

	@Override
	public InverterTreeVO getTotalTree() {
		InverterTreeVO treeVo = new InverterTreeVO();
		treeVo.setHasChildren(true);
		treeVo.setId("0");
		treeVo.setTitle("全部");
		getChildTree(treeVo,null,null,0);
		return treeVo;
	}

	private void getChildTree(InverterTreeVO parent,String parentId, String parentName, int level) {
		if (level > 4 || parent==null) return;

		List<InverterTreeVO> result = Lists.newArrayList();

		LambdaQueryWrapper<PowerStationEntity> queryWrapper = new LambdaQueryWrapper<>();
		switch (level) {
			case 0: {
				queryWrapper
					.select(PowerStationEntity::getCapitalCode, PowerStationEntity::getCapitalName)
					.groupBy(PowerStationEntity::getCapitalName);
				List<Map<String, Object>> listMaps = this.listMaps(queryWrapper);
				listMaps.forEach(res -> {
					InverterTreeVO vo = new InverterTreeVO();
					vo.setHasChildren(true);
					String code = (String) res.get("capital_code");
					String name = (String) res.get("capital_name");
					vo.setId(name);
					vo.setParentId("0");
					vo.setKey(code);
					vo.setTitle(name);
					vo.setValue(code);
					result.add(vo);
				});
				break;
			}
			case 1: {
				queryWrapper
					.select(PowerStationEntity::getProjectCompanyId, PowerStationEntity::getProjectCompanyName)
					.eq(PowerStationEntity::getCapitalName, parentName)
					.groupBy(PowerStationEntity::getProjectCompanyName);
				List<Map<String, Object>> listMaps = this.listMaps(queryWrapper);
				listMaps.forEach(res -> {
					InverterTreeVO vo = new InverterTreeVO();
					vo.setHasChildren(true);
					String code = (String) res.get("project_company_id");
					String name = (String) res.get("project_company_name");
					vo.setId(name);
					vo.setParentId(parentName);
					vo.setKey(code);
					vo.setTitle(name);
					vo.setValue(code);
					result.add(vo);
				});
				break;
			}
			case 2: {
				queryWrapper
					.select(PowerStationEntity::getCity)
					.eq(PowerStationEntity::getProjectCompanyName, parentName)
					.groupBy(PowerStationEntity::getCity);
				List<Map<String, Object>> listMaps = this.listMaps(queryWrapper);
				listMaps.forEach(res -> {
					String city = (String) res.get("city");
					InverterTreeVO vo = new InverterTreeVO();
					vo.setId(parentName + city);
					vo.setParentId(parentName);
					vo.setHasChildren(true);
					vo.setKey(city);
					vo.setTitle(city);
					vo.setValue(city);
					result.add(vo);
				});
				break;
			}
			case 3: {
				queryWrapper.eq(PowerStationEntity::getCity, parentName)
					.eq(PowerStationEntity::getProjectCompanyName, parentId);
				List<PowerStationEntity> listMaps = this.list(queryWrapper);
				listMaps.forEach(res -> {
					InverterTreeVO vo = new InverterTreeVO();
					vo.setHasChildren(true);
					vo.setId(parentName + "-" + res.getAgentName());
					vo.setParentId(parentId + parentName);
					vo.setKey(parentName);
					vo.setTitle(res.getAgentName());
					vo.setValue(res.getId() + "");
					result.add(vo);
				});
				break;
			}
			case 4: {
				queryWrapper.eq(PowerStationEntity::getCity, parentId)
					.eq(PowerStationEntity::getAgentName, parentName);
				List<PowerStationEntity> listMaps = this.list(queryWrapper);
				listMaps.forEach(res -> {
					InverterTreeVO vo = new InverterTreeVO();
					vo.setHasChildren(false);
					vo.setId(res.getId() + "");
					vo.setParentId(parentId + parentName);
					vo.setKey(res.getId() + "");
					vo.setTitle(res.getOwnerName() + "-" + res.getActualCapacity() + "KW-" + res.getStationCode());
					vo.setValue(res.getId() + "");
					result.add(vo);
				});
				break;
			}


		}

		if(result.size()==0) {
			parent.setHasChildren(false);
		}else{
			parent.setHasChildren(true);
			parent.setChildren(result);
			parent.getChildren().forEach(e->{
				String key1 = e.getId();
				String key2 = e.getTitle();
				int nextLvl = level+1;
				if (nextLvl == 3) {
					key1 = e.getParentId();
					key2 = e.getTitle();
				}
				if (nextLvl == 4) {
					key1 = e.getKey();
					key2 = e.getTitle();
				}
				getChildTree(e,key1,key2,nextLvl);
			});
		}
	}

	@Override
	public PowerStationEntity getPowerStationByInId(String inId) {
		LambdaQueryWrapper<PowerStationEntity> queryWrapper2 = new LambdaQueryWrapper<>();
		queryWrapper2.eq(PowerStationEntity::getInnerStationId,inId);
		return getOne(queryWrapper2);
	}

	@Override
	public R syncPowerStation(PowerStationDTO dto) {
		if(StringUtil.isBlank(dto.getInnerStationId())){
			return R.fail("内部电站ID为空");
		}

//		if(StringUtil.isBlank(dto.getOutStationId())){
//			return R.fail("外部电站ID为空");
//		}

		LambdaQueryWrapper<PowerStationEntity> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(PowerStationEntity::getInnerStationId,dto.getInnerStationId());
		if(this.count(queryWrapper)>0){
			return R.data(501,null,"电站内部id重复，该电站已同步");
		}
		LambdaQueryWrapper<PowerStationEntity> queryWrapper2 = new LambdaQueryWrapper<>();
		queryWrapper2.eq(PowerStationEntity::getStationCode,dto.getStationCode());
		if(this.count(queryWrapper2)>0){
			return R.data(501,null,"电站Code重复，该电站已同步");
		}

		PowerStationEntity entity = Objects.requireNonNull(BeanUtil.copyProperties(dto, PowerStationEntity.class));
		entity.init();
		entity.setOutStationId(null);
		if(dto.getApplyStatus()==null){
			entity.setApplyStatus(0);
		}
		entity.setAddress(entity.getProvince()+entity.getCity()+entity.getDistrict()+entity.getAddress());
		this.save(entity);

		return R.success("添加电站成功");
	}

	@Override
	public R<List<Map<String, Object>>> getMapdistribution() {

		String omProviderId = siteService.getOmProviderId();

		List<Map<String, Object>> result = Lists.newArrayList();

		List<StaticsStatusVO> list = this.baseMapper.getStatusByProvince(omProviderId);
		Map<String, Object> current = null;
		String currntName = "";
		for(StaticsStatusVO vo : list){
			if(!StringUtil.equals(currntName,vo.getName())){
				currntName = vo.getName();
				if(current!=null){
					result.add(current);
				}
				current = Maps.newHashMap();
				current.put("province",currntName);
				current.put("total",vo.getNum());
				if(vo.getStatus()!=1){
					current.put("error",vo.getNum());
				}else{
					current.put("error",0);
				}
			}else{
				current.put("total",(int)current.get("total")+vo.getNum());
				if(vo.getStatus()!=1){
					current.put("error",vo.getNum()+(int)current.get("error"));
				}
			}
		}
		result.add(current);

		return R.data(result);
	}

	@Override
	public IPage<YXPowerStationDTO>  queryListForYX(IPage<YXPowerStationDTO> page,StationDTO powerStation) {

		List<YXPowerStationDTO> yxList = Lists.newArrayList();
		List<PowerStationVO> list = baseMapper.selectPowerStationList(page,powerStation);

		 for(PowerStationVO vo : list){
			 YXPowerStationDTO dto = PowerStationWrapper.build().entityYXDTO(vo);
			 dto.setAddress(vo.getDistrict()+vo.getAddress());
			 dto.setNbqSn(deviceMapper.queryIdsByStation(vo.getId()));
			 MonitorEntryStatVO entryVO = entryStatService.getByPowerStation(vo);
			 if(entryVO!=null){
				 dto.setEtd(entryVO.getEtd());
				 dto.setEtm(entryVO.getEtm());
				 dto.setEty(entryVO.getEty());
				 dto.setEta(entryVO.getEta());
			 }
			 yxList.add(dto);
		 }

		return page.setRecords(yxList);
	}

	@Override
	public Map<String, Integer> staticsStatus() {
		StationDTO powerStation=new StationDTO();
		Map<String,Integer> map = Maps.newHashMap();
		BladeUser user = AuthUtil.getUser();
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			powerStation.setOmProviderId(site.getId());
		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			powerStation.setOmProviderId(authVo.getSiteId());
			powerStation.setProvince(authVo.getProvinces());
			powerStation.setCity(authVo.getCity());
			powerStation.setDistrict(authVo.getArea());
		}else if("4".equals(user.getDeptId())){ //平台员工
			EmpAuthVo authVoP=platformEmployeeService.findPlatEmpAuthByUserId(user.getUserId());
			if(authVoP!= null){
				powerStation.setSiteIds(authVoP.getSiteId());
				powerStation.setProvince(authVoP.getProvinces());
				powerStation.setCity(authVoP.getCity());
				powerStation.setDistrict(authVoP.getArea());
				powerStation.setEntryIds(authVoP.getEntryId());
				powerStation.setCapitalName(authVoP.getPartnerName());

			}

		}
		powerStation.setApplyStatus(1);
		for(StaticsStatusVO vo : this.baseMapper.staticsStatus(powerStation)){
			map.put(String.valueOf(vo.getStatus()),vo.getNum());
		}
		return map;
	}

	@Override
	public Map<String, Integer> staticsYkStatus() {
		StationDTO powerStation=new StationDTO();
		Map<String,Integer> map = Maps.newHashMap();
		BladeUser user = AuthUtil.getUser();
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			powerStation.setOmProviderId(site.getId());
		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			powerStation.setOmProviderId(authVo.getSiteId());
			powerStation.setProvince(authVo.getProvinces());
			powerStation.setCity(authVo.getCity());
			powerStation.setDistrict(authVo.getArea());
		}else if("4".equals(user.getDeptId())){ //平台员工
			EmpAuthVo authVoP=platformEmployeeService.findPlatEmpAuthByUserId(user.getUserId());
			if(authVoP!= null){
				powerStation.setSiteIds(authVoP.getSiteId());
				powerStation.setProvince(authVoP.getProvinces());
				powerStation.setCity(authVoP.getCity());
				powerStation.setDistrict(authVoP.getArea());
				powerStation.setEntryIds(authVoP.getEntryId());

				powerStation.setCapitalName(authVoP.getPartnerName());
			}

		}
		powerStation.setSource("2");
		for(StaticsStatusVO vo : this.baseMapper.staticsStatus(powerStation)){
			map.put(String.valueOf(vo.getStatus()),vo.getNum());
		}
		return map;
	}

	@Override
	public PowerGenerationTrendCoordinatesVO powerGenerationTrendsHome(String type, String traderId) {
		BladeUser user = AuthUtil.getUser();
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			traderId=site.getId();
		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			traderId=authVo.getSiteId();
		}
		String redisKey = "POWER_GENERATION_TRENDS_HOME:"+type+traderId;
		PowerGenerationTrendCoordinatesVO vo = bladeRedis.get(redisKey);
		if(vo!=null){
			return vo;
		}
		PowerGenerationTrendCoordinatesVO trend = new PowerGenerationTrendCoordinatesVO();
		List<String> xAxis = new ArrayList<>();
		List<Object> yAxisForElectricity = new ArrayList<>();

		xAxis.add("0");
		yAxisForElectricity.add(0);

		List<String> outStationIds = this.baseMapper.getOutStationIds();

		if("day".equals(type)){  //按日统计
			String time = DateUtil.format(new Date(),"yyyy-MM-dd");
			Map<String, Object> resMap = dailyStatMapper.overviewHourStatic(null,outStationIds, time,traderId);
			for (int i = 1; i < 25; i++) {
				if (i < 10) {
					xAxis.add("0" + i);
				} else {
					xAxis.add(String.valueOf(i));
				}
				if (resMap == null) {
					yAxisForElectricity.add(0d);
				} else {
					if (i == 1) {
						yAxisForElectricity.add(resMap.get("h" + i));
					} else {
						BigDecimal v = new BigDecimal(resMap.get("h" + i).toString()).subtract(CommonUtil.getPreHourMax(resMap,i));
						if (v.compareTo(BigDecimal.ZERO) < 0) {
							yAxisForElectricity.add(0);
						} else {
							yAxisForElectricity.add(v);
						}
					}
				}
			}
		}else if("week".equals(type)){  //按日统计
			List<Map<String, Object>> weekList = monthStatMapper.overviewLast7Days(null, outStationIds,traderId);
			String month = DateUtil.format(new Date(),"MM");
			for(Map<String, Object> map : weekList){
				xAxis.add(map.get("DAY").toString());
				Double fdl = (Double) map.get("energy");
				yAxisForElectricity.add(fdl);
			}
		}else if("month".equals(type)){  //按日统计
			String time = DateUtil.format(new Date(),"yyyy-MM");
			List<Map<String, Object>> monList = monthStatMapper.overviewMonthStatic(null, outStationIds,time,traderId);
			Double fdl = null;

//			monList.forEach(mon -> {
//				xAxis.add(mon.get("day").toString());
//				Double fdl = (Double) mon.get("energy");
//				yAxisForElectricity.add(fdl);
//			});

			for (int i = 1; i <= getDaysOfMonth(time); i++) {
				if (i < 10) {
					xAxis.add("0" + i);
				} else {
					xAxis.add(String.valueOf(i));
				}
				fdl = 0d;
				for (Map<String, Object> map : monList) {
					if (Integer.valueOf(map.get("day").toString()) == i) {
						fdl = (Double) map.get("energy");
					}
				}
				yAxisForElectricity.add(fdl);
			}
		}else if("year".equals(type)){  //按月统计
			String year=DateUtil.format(new Date(),"yyyy");
			List<MonitorEntryYearStatEntity> yerList = yearStatMapper.overviewYearStatic(null, outStationIds,Integer.valueOf(year),traderId);
			Double fdl = null;
			for (int i = 1; i <= 12; i++) {
				if (i < 10) {
					xAxis.add("0" + i);
				} else {
					xAxis.add(String.valueOf(i));
				}
				fdl = 0d;
				for (MonitorEntryYearStatEntity map : yerList) {
					if (map.getMonth() == i) {
						fdl += map.getEnergy();
					}
				}
				if (fdl != null) {
					yAxisForElectricity.add(fdl);
				} else {
					yAxisForElectricity.add(0d);
				}
			}
		}

		trend.setXAxis(xAxis);
		trend.setYAxisForElectricity(CommonUtil.retainNum(yAxisForElectricity,1));

		List<Double> powerList = CommonUtil.repeatNum(xAxis.size(),0D);
		trend.setYAxisForPower(powerList);

		bladeRedis.setEx(redisKey,trend,15*60L);
		return trend;
	}

	@Override
	public PowerGenerationTrendCoordinatesVO statByProjectCompany(String type, String traderId) {
		String redisKey = "HOME_PROJECT_COMPANY:"+type;

		PowerGenerationTrendCoordinatesVO vo = bladeRedis.get(redisKey);
		if(vo!=null){
			return vo;
		}

		//查询出来所有电站
		LambdaQueryWrapper<PowerStationEntity> queryWrapper = new LambdaQueryWrapper<>();
		List<PowerStationEntity> stationEntityList = this.list(queryWrapper);

		//用来保存所有的公司与电站ID的关联
		Map<String,List<String>> companyStationIdsMap = Maps.newHashMap();

		stationEntityList.forEach(entity->{
			if(StringUtil.isNoneBlank(entity.getProjectCompanyName())){
				List<String> ids;
				if(companyStationIdsMap.containsKey(entity.getProjectCompanyName())){
					ids = companyStationIdsMap.get(entity.getProjectCompanyName());
				}else{
					ids = Lists.newArrayList();
				}
				ids.add(entity.getOutStationId());
				if(!companyStationIdsMap.containsKey(entity.getProjectCompanyName())){
					companyStationIdsMap.put(entity.getProjectCompanyName(),ids);
				}
			}
		});

		List<String> xAxis = new ArrayList<>();
		List<Object> yAxisForElectricity = new ArrayList<>();
		List<Double> powerList = new ArrayList<>();
		PowerGenerationTrendCoordinatesVO trend = new PowerGenerationTrendCoordinatesVO();

		Map<String,Double> top5map = Maps.newHashMap();

		companyStationIdsMap.forEach((companyName, stationIds) -> {
			String year = DateUtil.format(new Date(),"yyyy");
			String month = DateUtil.format(new Date(),"MM");
			Double yAxis = 0d;
			if("year".equals(type)){
				yAxis = yearStatMapper.sumYearPowerByStationIds(stationIds,year,null);
			}else if("month".equals(type)){
				yAxis = yearStatMapper.sumYearPowerByStationIds(stationIds,year,month);
			}else if("week".equals(type)){
				yAxis = monthStatMapper.sumLast7DaysEnergy(stationIds);
			}else{
				yAxis = entryStatMapper.sumDayPowerByStationIds(stationIds);
			}

			if(yAxis!=null){
				if(top5map.size()<5){
					top5map.put(companyName,yAxis);
				}else{
					for (Map.Entry<String,Double> entry : top5map.entrySet()) {
						String key = entry.getKey();
						Double value = entry.getValue();
						if(yAxis>value){
							top5map.remove(key);
							top5map.put(companyName,yAxis);
							break;
						}
					}
				}
			}


		});

		List<Double> vals = new ArrayList<>(top5map.values());

//		yAxisForElectricity.addAll(top5map.values());

		Collections.sort(vals,new Comparator<Double>() {
			public int compare(Double a, Double b) {
				return  a.compareTo(b) ; // 降序排序
			}
		});

		for(int i=0;i<vals.size();i++){
			for (Map.Entry<String,Double> entry : top5map.entrySet()) {
				String key = entry.getKey();
				Double value = entry.getValue();
				if(vals.get(i)==value){
					xAxis.add(key);
					yAxisForElectricity.add(value);
				}
			}
		}



		trend.setXAxis(xAxis);
		trend.setYAxisForElectricity(yAxisForElectricity);
		trend.setYAxisForPower(powerList);

		bladeRedis.setEx(redisKey,trend,5*60L);
		return trend;
	}

	@Override
	public Map<String, Object> powerGenerationTrends(Long stationId, String type, String time,String stationCode) {
		PowerStationEntity powerStation = null;
        if(stationId != null){
			powerStation = this.getById(stationId);
		}else if(StringUtil.isNotBlank(stationCode)){
			powerStation = this.getStationDetailByPowCode(stationCode);
		}

		return powerGenTrendsByStation(type, time, powerStation);
	}

	@Override
	public PowerStationEntity getByInnerId(String innerStationId) {
		if(StringUtil.isBlank(innerStationId)) return null;
		LambdaQueryWrapper<PowerStationEntity> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(PowerStationEntity::getInnerStationId,innerStationId);
		PowerStationEntity entity = this.getOne(queryWrapper);
		return entity;
	}

	@Override
	public PowerStationEntity getByOutStationId(String outStationId) {
		if(StringUtil.isBlank(outStationId)) return null;
		LambdaQueryWrapper<PowerStationEntity> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(PowerStationEntity::getOutStationId,outStationId);
		List<PowerStationEntity> list = this.list(queryWrapper);
		return CollectionUtil.isNotEmpty(list)?list.get(0):null;
	}

	@Override
	public Map<String, Object> powerGenTrendsByInnerId(String innerStationId, String type, String time) {
		PowerStationEntity entity = this.getByInnerId(innerStationId);
		if(entity==null){return Maps.newHashMap();}
		return powerGenTrendsByStation(type, time, entity);
	}

	private Map<String, Object> powerGenTrendsByStation(String type, String time, PowerStationEntity powerStation) {
		List<String> XStr= Lists.newArrayList();  //X轴
		List<Object> fdlY= Lists.newArrayList();  //发电量的Y轴

		XStr.add("0");
		fdlY.add("0");


		List<String> outStationIds = Lists.newArrayList();
		if(powerStation.getOutStationId()!=null){
			for(String str:powerStation.getOutStationId().split(",")){
				outStationIds.add(str);
			}
		}else{
			Map<String,Object> result=Maps.newHashMap();
			result.put("XStr", XStr);
			result.put("fdlY",fdlY);
			return result;
		}
		BigDecimal total= BigDecimal.ZERO;
		if("day".equals(type)){  //按日统计
			Map<String, Object> resMap = dailyStatMapper.overviewHourStatic(null,outStationIds, time,"");
			for (int i = 1; i < 25; i++) {
				if (i < 10) {
					XStr.add("0" + i);
				} else {
					XStr.add(String.valueOf(i));
				}
				if (resMap == null) {
					fdlY.add(0);
				} else {
					if (i == 1) {
						fdlY.add(resMap.get("h" + i));
						total = new BigDecimal(resMap.get("h" + i).toString());
					} else {
						BigDecimal v = new BigDecimal(resMap.get("h" + i).toString()).subtract(CommonUtil.getPreHourMax(resMap,i));
						if (v.compareTo(BigDecimal.ZERO) < 0) {
							fdlY.add(0);
						} else {
							fdlY.add(v.setScale(2, RoundingMode.HALF_UP));
							total = total.add(v);
						}
					}
				}
			}
		}else if("month".equals(type)){  //按月统计
			List<Map<String, Object>> monList = monthStatMapper.overviewMonthStatic(null, outStationIds, time,"");
			Double fdl = null;
			for (int i = 1; i <= getDaysOfMonth(time); i++) {
				if (i < 10) {
					XStr.add("0" + i);
				} else {
					XStr.add(String.valueOf(i));
				}
				fdl = 0d;
				for (Map<String, Object> map : monList) {
					if (Integer.valueOf(map.get("day").toString()) == i) {
						fdl = (Double) map.get("energy");

					}
				}
				fdlY.add(CommonUtil.round(fdl,3));
			}
			MonitorEntryStatDTO dto = entryStatMapper.findByOutStationIds(outStationIds);
			total = dto != null ?new BigDecimal(dto.getEtm()):BigDecimal.ZERO;
		}else if("week".equals(type)){  //按日统计
			List<Map<String, Object>> weekList = monthStatMapper.overviewLast7Days(null, outStationIds,"");
			Double fdl = null;

			for(Map<String, Object> map : weekList){
				XStr.add(map.get("DAY").toString());
				fdl = (Double) map.get("energy");
				fdlY.add(CommonUtil.round(fdl,3));
				total = total.add(new BigDecimal(fdl));
			}
		}else if("year".equals(type)){  //按年统计
			List<MonitorEntryYearStatEntity> yerList = yearStatMapper.overviewYearStatic(null,outStationIds, 2024,"");
			Double fdl = null;
			for (int i = 1; i <= 12; i++) {
				if (i < 10) {
					XStr.add("0" + i);
				} else {
					XStr.add(String.valueOf(i));
				}
				fdl = 0d;
				for (MonitorEntryYearStatEntity map : yerList) {
					if (map.getMonth() == i) {
						fdl = map.getEnergy();
						break;
					}
				}
				if (fdl != null) {
					fdlY.add(CommonUtil.round(fdl,3));
					total = total.add(new BigDecimal(fdl));
				} else {
					fdlY.add(0d);
				}
			}
		}
		Map<String,Object> result=Maps.newHashMap();
		result.put("XStr", XStr);
		result.put("fdlY",fdlY);
		result.put("total",total.setScale(4, RoundingMode.HALF_UP));
		return result;
	}

	public static int getDaysOfMonth(String dateStr) {
		LocalDate date = LocalDate.parse(dateStr + "-01");
		return date.lengthOfMonth();
	}

	@Override
	public IPage<PowerStationEntity> findMyPowerStation(IPage<PowerStationEntity> page, String empId,String siteId,String condition) {
		List<PowerStationEntity> list = baseMapper.findMyPowerStation(page, empId,siteId,condition);
		return page.setRecords(list);
	}


	@Override
	public List<StationDTO> getSelectPowerStaion(Map<String,Object> map){
		return baseMapper.getSelectPowerStaion(map);
	}

	@Override
	public R importSite(List<EntrySiteExcel> data) {
		//siteService
		int shiB = 0, m=0;
		List<OperationSiteVO> findSiteList =siteService.findSiteList();
		Map<String,OperationSiteVO> mapsite = findSiteList.stream().collect(Collectors.toMap(e -> e.getName().trim(), e -> e));
		StringBuilder sf = new StringBuilder();
		BladeUser user= AuthUtil.getUser();
		//获取所有运维商
		List<PowerStationEntity> entry = Lists.newArrayList();
		for(EntrySiteExcel en :data){
			if(mapsite.containsKey(en.getName().trim())){
				OperationSiteVO site = mapsite.get(en.getName().trim());
				PowerStationEntity powerStation = getStationDetailByPowCode(en.getStationCode().trim());
				if(powerStation==null){
					sf.append(en.getStationCode()+"电站系统中未查到。");
					shiB++;
					continue;
				}
				powerStation.setOmProviderName(site.getName());
				powerStation.setOmProviderId(site.getId());
				powerStation.setBindingUnbindId(user.getUserId());
				entry.add(powerStation);
				m++;
			}else{
				sf.append(en.getName()+"系统中未查到");
				shiB++;
			}
		}
		if(entry.size()>0){
			if(!updateBatchById(entry)){
				log.debug("更新数据失败==============");
				shiB = data.size();
			}
		}

		if(shiB>0){
			StringBuilder sb = new StringBuilder("批量绑定运维商失败.");
			sb.append("成功："+m+"条；");
			sb.append("失败："+shiB+"条；");
			sb.append("失败原因："+sf.toString());
			return R.fail(sb.toString());
		}else{
			return R.success("批量绑定运维商成功"+m+"条");
		}
	}

	@Override
	public boolean batchUpdateStation(List<PowerStationEntity> stationList) {
		List<PowerStationEntity> list = Lists.newArrayList();
		stationList.stream().forEach(station->{
			PowerStationEntity entity = this.getPowerStationByInId(station.getInnerStationId());
			entity.setStartGenDate(station.getStartGenDate());
			list.add(entity);

		});
		return updateBatchById(list);
	}

	@Override
	public void importPaymentTime(List<EntryPaymentTimeExcel> list) {
        for(EntryPaymentTimeExcel paymentTimeExcel:list){
        	try{
        		if(paymentTimeExcel.getStationCode()==null || paymentTimeExcel.getPaymentTime()==null){
        			continue;
				}
				PowerStationEntity powerStation = getStationDetailByPowCode(paymentTimeExcel.getStationCode().trim());
			    if(powerStation==null || powerStation.getPaymentTime()!=null){
			    	continue;
				}else{
					LambdaUpdateWrapper<PowerStationEntity> updateWrapper=new LambdaUpdateWrapper<>();
					updateWrapper.eq(PowerStationEntity::getId,powerStation.getId());
					updateWrapper.set(PowerStationEntity::getPaymentTime,paymentTimeExcel.getPaymentTime());
					Date warrantyTime=DateUtils.addYears(paymentTimeExcel.getPaymentTime(),1);
					updateWrapper.set(PowerStationEntity::getWarrantyExpiresTime,warrantyTime);
					update(updateWrapper);
					LambdaUpdateWrapper<OperationOrderEntity> orderEntityLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
					orderEntityLambdaUpdateWrapper.eq(OperationOrderEntity::getEntryId,powerStation.getInnerStationId());
					orderEntityLambdaUpdateWrapper.set(OperationOrderEntity::getPaymentTime,paymentTimeExcel.getPaymentTime());
				    orderEntityLambdaUpdateWrapper.set(OperationOrderEntity::getWarrantyExpiresTime,warrantyTime);
				    operationOrderMapper.update(orderEntityLambdaUpdateWrapper);
			    }
        	}catch (Exception e){
        		e.printStackTrace();
        		log.error("importPaymentTime e:",e);
			}

		}
	}


}
