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

import com.neusoft.smart.pos.dto.ota.request.UpgradeHistoryRequest;
import com.neusoft.smart.pos.framework.task.RedisTask;
import com.neusoft.smart.pos.framework.utils.SpringUtils;
import com.neusoft.smart.pos.gateway.service.feignService.RemoteOTAService;
import com.neusoft.smart.pos.redis.bean.DeviceVersion;
import com.neusoft.smart.pos.redis.bean.DeviceVersionList;
import lombok.Setter;
import org.springframework.data.util.Pair;

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

public abstract class AbstractDevicePostRequestTask extends RedisTask {
	
	@Setter
	protected String serialno;
	
	@Setter
	protected String version;
	
	
	private RemoteOTAService remoteOTAService = SpringUtils.getBean(RemoteOTAService.class);
	
	
	protected void updateStatusAndCreateHistory(DeviceVersionList versions) {
		DeviceVersion curVersion = versions.getVersionsMap().get(this.version);
		List<Pair<Integer, Integer>> pairs = new ArrayList<>();
		//把更新版本之前的所有未更新数据设置下状态
		if (null != curVersion) {
			LinkedList<DeviceVersion> list = new LinkedList<>(versions.getVersionsMap().values());
			int index = list.indexOf(curVersion);
			for (int i = 0; i <= index; i++) {
				Pair<Integer, Integer> pair = Pair.of(list.get(i).getId(), versions.getDeviceInfo().getId());
				pairs.add(pair);
			}
		}
		remoteOTAService.updateStatus(pairs);
		//记录设备更新历史
		UpgradeHistoryRequest deviceUpgradeHistory = new UpgradeHistoryRequest();
		deviceUpgradeHistory.setDeviceId(versions.getDeviceInfo().getId());
		deviceUpgradeHistory.setPrevVersion(versions.getDeviceInfo().getCurVersion());
		deviceUpgradeHistory.setCurVersion(this.version);
		remoteOTAService.create(deviceUpgradeHistory);
	}
}
