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.redis.bean.DeviceVersion;
import com.neusoft.smart.pos.redis.bean.DeviceVersionList;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Data
public class DeviceInitStrategyTask extends RedisTask {
    private Map<String, DeviceVersionList> deviceHashMap = new HashMap<>();
    
    private LinkedList<DeviceVersion> versionList = new LinkedList<>();
    
    private RedisTemplate redisTemplate = SpringUtils.getBean("redisTemplate", RedisTemplate.class);

    @Override
    public void executeTask() {
        log.error("DeviceInitStrategyTask 任务");
        BoundHashOperations<String, String, DeviceVersionList> deviceHash = redisTemplate.boundHashOps("deviceVersionsMap");
        BoundHashOperations<String, String, DeviceVersionList> deviceHashWithSn = redisTemplate.boundHashOps("deviceVersionsMapWithSn");
        Map<String, DeviceVersionList> deviceHashWithSnMap = new HashMap<>();
        deviceHashMap.forEach((macAddr, deviceVersions)-> {
            if (null != deviceVersions) {
                LinkedHashMap<String, DeviceVersion> versionMap = deviceVersions.getVersionsMap();
                String string = versionMap.keySet().stream().findAny().orElse("");
                if (!string.contains("_")) {
                    List<String> list = versionMap.keySet().stream().sorted(Comparator.comparingInt(x ->
                                    Integer.parseInt(x.substring(x.lastIndexOf("_") + 1).substring(x.lastIndexOf(".") + 1)))).collect(Collectors.toList());
                    LinkedHashMap<String, DeviceVersion> temp = new LinkedHashMap<>();
                    list.forEach(item -> temp.put(item, deviceVersions.getVersionsMap().get(item)));
                    deviceVersions.setVersionsMap(temp);
                }
                deviceHashWithSnMap.put(deviceVersions.getDeviceInfo().getSerialNo(), deviceVersions);
                log.info(deviceVersions.getDeviceInfo().getSerialNo() + " 执行了添加更新版本任务");
            }
        });

        deviceHash.putAll(deviceHashMap);
        deviceHashWithSn.putAll(deviceHashWithSnMap);
        log.error("DeviceInitStrategyTask 任务 End size" + deviceHashMap.size());
    }
}
