package org.springblade.modules.nh.job;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.constant.NhConstants;
import org.springblade.common.utils.TaskControl;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.utils.*;
import org.springblade.modules.nh.factory.ginlong.GinlongApi;
import org.springblade.modules.nh.factory.ginlong.IRet;
import org.springblade.modules.nh.factory.ginlong.dto.collectorlist.GetCollectorListR;
import org.springblade.modules.nh.factory.ginlong.dto.inverterdetaillist.GetInverterDetailR;
import org.springblade.modules.nh.pojo.entity.*;
import org.springblade.modules.nh.service.*;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@EnableScheduling
@Component
@Slf4j
@AllArgsConstructor
public class UpdateDataScheduler {

	private final IPowerStationService powerStationService;
	private final IDeviceService deviceService;
	private final IInverterDataService inverterDataService;
	private final IMonitorEntryStatService entryStatService;
	private final IMonitorInverterStatService inverterStatService;
	private final GinlongApi ginlongApi;

	private final BladeRedis redis;

	private final IInverterUapService uapService;

	@Scheduled(cron = "50 30 15 * * ?")
	public void checkPowerStationOutId() {
		//每天全量核对一次电站的外部id是否正确
		TaskControl.newSingleInstanceTask("pw:checkPowerStationOutId", new Runnable() {
			@Override
			public void run() {
				int i=0;
				for(PowerStationEntity item:powerStationService.list()){
					String stationName = item.getStationCode();
					LambdaQueryWrapper<MonitorEntryStatEntity> queryWrapper = new LambdaQueryWrapper<>();
					queryWrapper.like(MonitorEntryStatEntity::getStationName, "%"+stationName+"%");
					MonitorEntryStatEntity current = null;
					List<MonitorEntryStatEntity> list = entryStatService.list(queryWrapper);
					for(MonitorEntryStatEntity entryStat : list){
						if(current==null){
							current = entryStat;
						}else{
							if(entryStat.getSyncTime().after(current.getSyncTime())){
								current = entryStat;
							}
						}
					}
					if(current!=null
						&& StringUtil.isNotBlank(current.getOutStationId())
						&& !current.getOutStationId().equals(item.getOutStationId())){
						LambdaUpdateWrapper<PowerStationEntity> updateWrapper = new LambdaUpdateWrapper<>();
						updateWrapper.eq(PowerStationEntity::getId,item.getId())
							.set(PowerStationEntity::getOutStationId,current.getOutStationId());
						powerStationService.update(updateWrapper);
						System.out.println(++i);
					}

				}
			}
		});
	}

//	@Scheduled(cron = "11 25 23 * * ?")
//	public void syncOutIdByCollectNo() {
//		//通过采集机同步外部电站id
//		TaskControl.runTask("pw:syncOutIdByCollectNo", new Runnable() {
//			@Override
//			public void run() {
//				LambdaQueryWrapper<DeviceEntity> queryWrapper = new LambdaQueryWrapper<>();
//				queryWrapper
//					.isNull(DeviceEntity::getOutStationId)
//					.eq(DeviceEntity::getBrand, NhConstants.SYS_TYPE_GINLONG)
//					.eq(DeviceEntity::getType,2)
//					.isNotNull(DeviceEntity::getSn);
//				List<DeviceEntity> deviceEntityList = deviceService.list(queryWrapper);
//				for(DeviceEntity deviceEntity : deviceEntityList){
//					try {
//						IRet<GetCollectorListR> ret = ginlongApi.collectorDetail(,null, deviceEntity.getSn());
//						if("0".equals(ret.getCode())){
//							GetCollectorListR r = ret.getData();
//							deviceEntity.setOutDeviceId(r.getId());
//							deviceEntity.setOutStationId(r.getStationId());
//							deviceService.updateById(deviceEntity);
//
//							LambdaUpdateWrapper<PowerStationEntity> updateWrapper3 = new LambdaUpdateWrapper<>();
//							updateWrapper3.eq(PowerStationEntity::getId, deviceEntity.getStationId())
//								.set(PowerStationEntity::getOutStationId,deviceEntity.getOutStationId());
//							powerStationService.update(updateWrapper3);
//						}
//					}catch (Exception e){
//						log.error("通过采集机同步外部电站id异常:{}",e);
//					}
//					ThreadUtil.sleep(2*1000L);
//				}
//			}
//		});
//	}


	@Scheduled(cron = "18 41 7 * * ?")
	public void delUapData() {
		TaskControl.runTask("pw:delUapData", new Runnable() {
			@Override
			public void run() {
				Date now = new Date();
				Date pre15Day = DateUtil.minusDays(now,15);
				LambdaQueryWrapper<InverterUapEntity> deleteWrapper = new LambdaQueryWrapper<>();
				deleteWrapper.lt(InverterUapEntity::getStateTime,pre15Day);
				uapService.remove(deleteWrapper);
			}
		});
	}

	@Scheduled(cron = "18 * * * * ?")
	public void saveUapData() {
		TaskControl.runTask("pw:saveUapData", new Runnable() {
			@Override
			public void run() {
				Set<InverterUapEntity> set =redis.sMembers(NhConstants.UAP_LIST_TEMP_KEY);
				redis.del(NhConstants.UAP_LIST_TEMP_KEY);
				for(InverterUapEntity uap : set){
					LambdaQueryWrapper<InverterUapEntity> queryWrapper = new LambdaQueryWrapper<>();
					queryWrapper.eq(InverterUapEntity::getSn,uap.getSn())
						.eq(InverterUapEntity::getType,uap.getType())
						.eq(InverterUapEntity::getStateTime,uap.getStateTime());
					if(uapService.count(queryWrapper)==0 && uap.getUv1()!=null){
						uapService.save(uap);
					}
				}
			}
		});
	}

	@Scheduled(cron = "18 5 23 * * ?")
	public void updateDeviceOutIds() {
		TaskControl.runTask("pw:updateDeviceOutIds", new Runnable() {
			@Override
			public void run() {
				inverterDataService.updateDeviceOutIds();
			}
		});
	}

	@Scheduled(cron = "0 19 17 * * ?")
	public void updateStationSnFromDevice() {
		TaskControl.runTask("pw:updateStationSnFromDevice", new Runnable() {
			@Override
			public void run() {
				LambdaQueryWrapper<PowerStationEntity> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.isNull(PowerStationEntity::getSn)
					.eq(PowerStationEntity::getIsDeleted,0);
				List<PowerStationEntity> stationEntityList = powerStationService.list(queryWrapper);
				for(PowerStationEntity stationEntity : stationEntityList) {
					LambdaQueryWrapper<DeviceEntity> queryWrapper2 = new LambdaQueryWrapper<>();
					queryWrapper2.eq(DeviceEntity::getType,1)
						.eq(DeviceEntity::getStationId,stationEntity.getId());
					List<DeviceEntity> deviceEntityList = deviceService.list(queryWrapper2);
					StringBuilder snSb = new StringBuilder();
					for(DeviceEntity deviceEntity : deviceEntityList) {
						snSb.append(deviceEntity.getSn()+",");
					}
					LambdaUpdateWrapper<PowerStationEntity> updateWrapper = new LambdaUpdateWrapper<>();
					updateWrapper.eq(PowerStationEntity::getId,stationEntity.getId())
						.set(PowerStationEntity::getSn,snSb.toString());
					powerStationService.update(updateWrapper);
				}

			}
		});
	}

//	@Scheduled(cron = "0 11 23 * * ?")
//	public void syncInverterStatBySn() {
//		//有些设备逆变器没有同步，每晚定时同步一次
//		TaskControl.runTask("pw:syncInverterStatBySn", new Runnable() {
//			@Override
//			public void run() {
//				LambdaQueryWrapper<DeviceEntity> queryWrapper = new LambdaQueryWrapper<>();
//				queryWrapper.isNull(DeviceEntity::getOutDeviceId)
//					.eq(DeviceEntity::getBrand, NhConstants.SYS_TYPE_GINLONG)
//					.eq(DeviceEntity::getType,1)
//					.isNotNull(DeviceEntity::getSn);
//				List<DeviceEntity> deviceEntityList = deviceService.list(queryWrapper);
//				for (DeviceEntity deviceEntity : deviceEntityList) {
//					try{
//						MonitorInverterStatEntity temp =inverterStatService.getBySn(deviceEntity.getSn());
//						IRet<GetInverterDetailR> ret =  ginlongApi.inverterDetail(temp.getVendorIndex(),null,deviceEntity.getSn());
//						if("0".equals(ret.getCode())){
//							MonitorInverterStatEntity inverterStat = inverterStatService.initNewInverterStat(NhConstants.SYS_TYPE_GINLONG,ret.getData());
//							inverterStatService.save(inverterStat);
//
//							LambdaUpdateWrapper<DeviceEntity> updateWrapper = new LambdaUpdateWrapper<>();
//							updateWrapper.eq(DeviceEntity::getId, deviceEntity.getId())
//								.set(DeviceEntity::getOutDeviceId,inverterStat.getOutInverterId());
//							deviceService.update(updateWrapper);
//
//							LambdaUpdateWrapper<InverterDataEntity> updateWrapper2 = new LambdaUpdateWrapper<>();
//							updateWrapper2.eq(InverterDataEntity::getDeviceId, deviceEntity.getId())
//								.set(InverterDataEntity::getOutDeviceId,inverterStat.getOutInverterId());
//							inverterDataService.update(updateWrapper2);
//
//							LambdaUpdateWrapper<PowerStationEntity> updateWrapper3 = new LambdaUpdateWrapper<>();
//							updateWrapper3.eq(PowerStationEntity::getId, deviceEntity.getStationId())
//								.set(PowerStationEntity::getOutStationId,inverterStat.getOutStationId());
//							powerStationService.update(updateWrapper3);
//						}
//					}catch (Exception e){
//						log.error("单独同步逆变器数据异常:{}",e);
//					}
//				}
//			}
//		});
//	}

//	@Scheduled(cron = "0 31 1 * * ?")
//	public void checkInverterHasData() {
//		//有些逆变器没有data。每天定时统计一下
//		TaskControl.runTask("pw:checkInverterHasData", new Runnable() {
//			@Override
//			public void run() {
//				LambdaQueryWrapper<DeviceEntity> query = new LambdaQueryWrapper<>();
//				query.eq(DeviceEntity::getType,1);
//				List<DeviceEntity> list = deviceService.list(query);
//				for (DeviceEntity deviceEntity : list) {
//					LambdaQueryWrapper<InverterDataEntity> query2 = new LambdaQueryWrapper<>();
//					query2.eq(InverterDataEntity::getDeviceId,deviceEntity.getId());
//					if(inverterDataService.count(query2)==0){
//						LambdaQueryWrapper<InverterDataEntity> query3 = new LambdaQueryWrapper<>();
//						query3.eq(InverterDataEntity::getOutDeviceId,deviceEntity.getOutDeviceId());
//						if(inverterDataService.count(query3)>0){
//							inverterDataService.remove(query3);
//						}
//
//						InverterDataEntity dataEntity = BeanUtil.copyProperties(deviceEntity,InverterDataEntity.class);
//						dataEntity.setDeviceId(deviceEntity.getId());
//						dataEntity.setOutDeviceId(deviceEntity.getOutDeviceId());
//						dataEntity.init();
//						inverterDataService.save(dataEntity);
//						if(StringUtil.isNotBlank(deviceEntity.getOutDeviceId())){
//							inverterDataService.updateDataFromInverterStatByOutInverterId(deviceEntity.getOutDeviceId());
//						}
//					}
//				}
//			}
//		});
//	}

	@Scheduled(cron = "30 22 6 * * ?")
	public void updateGoodweEntryMonthYearData() {
		//每个小时统计一次固德威的月数据和日数据
		TaskControl.runTask("pw:updateGoodweEntryMonthYearData", new Runnable() {
			@Override
			public void run() {
				entryStatService.updateGoodweEntryMonthYearData();
			}
		});
	}

	@Scheduled(cron = "45 25 * * * ?")
	public void updatePowerStationBrand() {
		//每小时从逆变器品牌同步到电站
		TaskControl.runTask("pw:updatePowerStationBrand", new Runnable() {
			@Override
			public void run() {
				powerStationService.updatePowerStationBrand();
			}
		});
	}

	@Scheduled(cron = "18 */5 * * * ?")
	public void updateDataFromInverterStat() {
		inverterDataService.updateDataFromInverterStat();
	}

	/**
	 * 每5分钟根据设备的sn同步MonitorInverterStat的外部厂商id到Device。
	 */
	@Scheduled(cron = "20 */13 * * * ?")
	public void updateDeviceOutDeviceId() {
		TaskControl.runTask("pw:updateDeviceOutDeviceId", new Runnable() {
				@Override
				public void run() {
					//查询没有outDeviceId的逆变
					LambdaQueryWrapper<DeviceEntity> queryWrapper = new LambdaQueryWrapper<>();
					queryWrapper.eq(DeviceEntity::getType,1).isNull(DeviceEntity::getOutDeviceId);
					deviceService.list(queryWrapper).forEach(deviceEntity -> {
						MonitorInverterStatEntity inverterStat = inverterStatService.getBySn(deviceEntity.getSn());
						if(inverterStat != null){
							LambdaUpdateWrapper<DeviceEntity> updateWrapper1 = new LambdaUpdateWrapper<>();
							updateWrapper1.eq(DeviceEntity::getId,deviceEntity.getId())
								.set(DeviceEntity::getOutDeviceId,inverterStat.getOutInverterId())
								.set(DeviceEntity::getOutStationId,inverterStat.getOutStationId());
							deviceService.update(updateWrapper1);

							LambdaUpdateWrapper<InverterDataEntity> updateWrapper2 = new LambdaUpdateWrapper<>();
							updateWrapper2.eq(InverterDataEntity::getDeviceId,deviceEntity.getId())
								.set(InverterDataEntity::getOutDeviceId,inverterStat.getOutInverterId());
							inverterDataService.update(updateWrapper2);
						}
					});
				}
			});
	}
    /**
     * 每1个小时根据设备的outStationId同步到powerStation。
     */
   @Scheduled(cron = "20 */17 * * * ?")
    public void updatePSOutStationId() {
        TaskControl.runTask("pw:updatePSOutStationId", new Runnable() {
            @Override
            public void run() {
				LambdaQueryWrapper<PowerStationEntity> query = new LambdaQueryWrapper<>();
				query.isNull(PowerStationEntity::getOutStationId);
				List<PowerStationEntity> list = powerStationService.list(query);
				for(PowerStationEntity powerStationEntity : list){
					Set<String> outDeviceIdSet = new HashSet<>();
					deviceService.listByPowerStation(powerStationEntity).forEach(pwe->{
						outDeviceIdSet.add(pwe.getOutDeviceId());
					});
					if(outDeviceIdSet.size() > 0){
						LambdaQueryWrapper<MonitorInverterStatEntity> query2 = new LambdaQueryWrapper<>();
						query2.in(MonitorInverterStatEntity::getOutInverterId,outDeviceIdSet);
						List<MonitorInverterStatEntity> list2 = inverterStatService.list(query2);
						Set<String> outStationIdSet = new HashSet<>();
						list2.forEach(mise->{
							outStationIdSet.add(mise.getOutStationId());
						});
						if(outStationIdSet.size() > 0){
							LambdaUpdateWrapper<PowerStationEntity> update = new LambdaUpdateWrapper<>();
							update.eq(PowerStationEntity::getId,powerStationEntity.getId())
								.set(PowerStationEntity::getOutStationId,String.join(",",outStationIdSet));
							powerStationService.update(update);
						}
					}
				}
            }
        });
    }


	/**
	 * 每天同步电站发电数据
	*/
	@Scheduled(cron = "5 44 20 * * ?")
	public void checkStationData() {
		TaskControl.runTask("pw:checkStationData", new Runnable() {
			@Override
			public void run() {
				LambdaQueryWrapper<PowerStationEntity> query = new LambdaQueryWrapper<>();
				query.isNotNull(PowerStationEntity::getOutStationId);
				List<PowerStationEntity> list = powerStationService.list(query);
				for (PowerStationEntity entity : list) {
					try {
						LambdaQueryWrapper<MonitorEntryStatEntity> query2 = new LambdaQueryWrapper<>();
						query2.in(MonitorEntryStatEntity::getOutStationId, Func.toLongList(entity.getOutStationId()));
						List<MonitorEntryStatEntity> statList = entryStatService.list(query2);
						for(MonitorEntryStatEntity sta :statList){
							if(entity.getEtd() == null){
								entity.setEtd(new BigDecimal(sta.getEtd()).setScale(4, RoundingMode.HALF_UP));

							}else{
								entity.setEtd((entity.getEtd().add(new BigDecimal(sta.getEtd()))).setScale(4, RoundingMode.HALF_UP));
							}
							entity.setEto((entity.getEto().add(new BigDecimal(sta.getEta()))).setScale(4, RoundingMode.HALF_UP));
						}
						boolean hd=	powerStationService.updateById(entity);
						if(!hd){
							log.error("更新数据失败"+ entity.getStationCode());
						}
					}catch (Exception e){
						log.error( "更新数据失败===="+e);
					}


				}

			}
		});
	}


}
