package com.neusoft.smart.pos.ota.task;

import com.neusoft.smart.pos.dto.ota.request.AppStrategyGroupRequest;
import com.neusoft.smart.pos.framework.task.RedisTask;
import com.neusoft.smart.pos.framework.utils.SpringUtils;
import com.neusoft.smart.pos.redis.bean.AppStrategy;
import com.neusoft.smart.pos.redis.bean.AppVersion;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

public class AppStrategyTask extends RedisTask {
	
	Logger logger = LoggerFactory.getLogger(AppStrategyTask.class);
	
	@Setter
	private AppStrategyGroupRequest appStrategyGroupRequest;
	
	private RedisTemplate redisTemplate = SpringUtils.getBean("redisTemplate", RedisTemplate.class);
	
	
	@Override
	public void executeTask() {
		BoundHashOperations<String, String, AppVersion> operations = redisTemplate.boundHashOps("apkVersion");
		BoundHashOperations<String, String, AppStrategy> appStrategyOperations = redisTemplate.boundHashOps("apkVersionStrategy");
		appStrategyGroupRequest.getDeviceIds().forEach(deviceId -> {
			AppStrategy appStrategy = new AppStrategy();
			List<AppVersion> apps = new ArrayList<>();
			appStrategyGroupRequest.getApps().forEach(app -> {
				AppVersion appVersion = operations.get(app.getAppPackage() + "." + app.getAppName());
				if (null != appVersion) {
					apps.add(appVersion);
				}
			});
			appStrategy.setApps(apps);
			appStrategy.setForce(appStrategyGroupRequest.getIsForce() != 0);
			appStrategy.setUpgradeTime(appStrategyGroupRequest.getUpgradeTime());
			String deviceSn = appStrategyGroupRequest.getDeviceSnList().get(appStrategyGroupRequest.getDeviceIds().indexOf(deviceId));
			appStrategyOperations.put(deviceSn, appStrategy);
			logger.info(deviceSn + "执行了app策略redis任务");
		});
		
	}
	
}
