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

import com.neusoft.smart.pos.framework.task.RedisTask;
import com.neusoft.smart.pos.framework.utils.SpringUtils;
import com.neusoft.smart.pos.ota.persistent.domain.UpgradeStrategy;
import com.neusoft.smart.pos.redis.bean.DeviceVersion;
import com.neusoft.smart.pos.redis.bean.DeviceVersionList;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class StrategyCancelTask extends RedisTask {
    
    @Setter
    @Getter
    List<UpgradeStrategy> upgradeStrategyList;
    
    private RedisTemplate redisTemplate = SpringUtils.getBean("redisTemplate", RedisTemplate.class);
    
    @Override
    public void executeTask() {
        //子策略设备id去重，得到此策略全部设备id
        List<Integer> deviceIdList = upgradeStrategyList.stream().map(UpgradeStrategy::getDeviceId).distinct().collect(Collectors.toList());
        //缓存拿出升级数据
        BoundHashOperations<String, String, DeviceVersionList> deviceHash = redisTemplate.boundHashOps("deviceVersionsMap");
        BoundHashOperations<String, String, DeviceVersionList> deviceHashWithSn = redisTemplate.boundHashOps("deviceVersionsMapWithSn");
        Collection<DeviceVersionList> deviceVersionListInRedis = deviceHash.entries().values();
        //循环机具id
        deviceIdList.forEach(deviceId -> {
            //查出此策略中此机具所有的子策略
            List<UpgradeStrategy> willCancelStrategyList = upgradeStrategyList.stream().filter(item -> item.getDeviceId().equals(deviceId)).collect(Collectors.toList());
            //循环子策略
            willCancelStrategyList.forEach(willCancelStrategy -> {
                //在缓存中查询出要取消的策略机具版本列表数据
                DeviceVersionList deviceVersions = deviceVersionListInRedis.stream().filter(item ->
                        item.getDeviceInfo().getId().equals(deviceId)).findAny().orElse(null);
                if (null != deviceVersions && !deviceVersions.getVersionsMap().isEmpty()) {
                    LinkedHashMap<String, DeviceVersion> map = deviceVersions.getVersionsMap();
                    //根据版本id把要取消的子策略版本号过滤出来
                    String versionCode = map.values().stream().filter(item -> item.getId().equals(willCancelStrategy.getPackageId())).map(DeviceVersion::getVersionCode).findAny().orElse("");
                    map.remove(versionCode);
                    //塞回缓存
                    deviceVersions.setVersionsMap(map);
                    deviceHash.put(deviceVersions.getDeviceInfo().getMacAddr(), deviceVersions);
                    deviceHashWithSn.put(deviceVersions.getDeviceInfo().getSerialNo(), deviceVersions);
                }
            });
        });
    }
}
