/**
 * Copyright
 * All right reserved.
 * 项目名称:
 * 创建日期:2022/5/22
 */
package org.springblade.etl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.ConcurrentDateFormat;
import org.springblade.core.tool.utils.Func;
import org.springblade.etl.entity.EtlRainDataEntity;
import org.springblade.etl.service.IEtlRainDataService;
import org.springblade.modules.business.rtu.data.entity.RtuDataRainEntity;
import org.springblade.modules.business.rtu.data.service.IRtuDataRainService;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;

/***
 * Date:2022/5/22
 * Title: 环境辐射与气象监测系统(KRS) 模块
 * Description：MODBUS TCP 协议传输 ,读取任务
 * @author swp
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Slf4j
public class EtlRainDataTask implements Callable<Integer> {

	private RedisTemplate redisTemplate;
	private IEtlRainDataService etlRainDataService;
	private IRtuDataRainService rtuDataRainService;


	EtlRainDataTask(RedisTemplate redisTemplate, IEtlRainDataService rainDataService, IRtuDataRainService rtuDataRainService) {
		this.redisTemplate = redisTemplate;
		this.etlRainDataService = rainDataService;
		this.rtuDataRainService = rtuDataRainService;
	}

	@Override
	public Integer call() {
		try {
			HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
			Date date = new Date();
			if (opsHash.hasKey("etl", "rain_update_time")) {
				String dt = opsHash.get("etl", "rain_update_time");
				date = Func.parse(dt, ConcurrentDateFormat.of("yyyy-MM-dd"));
			} else {
				String dt = Func.formatDateTime(date);
				date = Func.parse(dt, ConcurrentDateFormat.of("yyyy-MM-dd"));
			}
			EtlRainDataEntity dto = new EtlRainDataEntity();
			dto.setTm(date);
			List<EtlRainDataEntity> list = etlRainDataService.selectLastList(dto);
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					EtlRainDataEntity entity = list.get(i);
					LambdaQueryWrapper<RtuDataRainEntity> dataWrapper = Wrappers.<RtuDataRainEntity>query().lambda();
					dataWrapper.eq(RtuDataRainEntity::getRtuCode, entity.getRtuCode());
					RtuDataRainEntity rainEntity = rtuDataRainService.getOne(dataWrapper);
					if (null == rainEntity) {
						rainEntity = new RtuDataRainEntity();
					}
					rainEntity.setDrp(entity.getDrp());
					rainEntity.setIntv(entity.getIntv());
					rainEntity.setRtuCode(entity.getRtuCode());
					rainEntity.setTm(entity.getTm());
					rtuDataRainService.saveOrUpdate(rainEntity);
				}
			}
		} catch (Exception e) {
			log.error("实时数据统计任务异常 {}", e.getMessage());
		}
		return 0;
	}
}
