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.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 新建完策略后更新redis的任务
 * Created by 姜涛 on 2017/3/29.
 */
@Slf4j
@Data
public class DeviceStrategyTask extends RedisTask {
    
    private String curVersion;
    
    private String macAddr;
    
    private String serialNo;
    
    private LinkedList<DeviceVersion> versionList = new LinkedList<>();
    
    private RedisTemplate redisTemplate = SpringUtils.getBean("redisTemplate", RedisTemplate.class);
    
    
    @Override
    public void executeTask() {
        //兼容key是mac的和新建的sn格式的
        BoundHashOperations<String, String, DeviceVersionList> deviceHash = redisTemplate.boundHashOps("deviceVersionsMap");
        BoundHashOperations<String, String, DeviceVersionList> deviceHashWithSn = redisTemplate.boundHashOps("deviceVersionsMapWithSn");
        DeviceVersionList deviceVersions = deviceHash.entries().get(this.macAddr);  //原来使用mac,新版本使用sn
        if (null != deviceVersions) {
            LinkedHashMap<String, DeviceVersion> map = deviceVersions.getVersionsMap();
            if (null != this.versionList) {
                this.versionList.forEach(strategyInfo -> map.put(strategyInfo.getVersionCode(), strategyInfo));
            }
            String string = deviceVersions.getVersionsMap().keySet().stream().findAny().orElse("");
            if (!string.contains("_")) {
                //key 重新排序一下
                List<String> list = deviceVersions.getVersionsMap().keySet().stream()
                        .sorted(Comparator.comparingInt(x ->
                                Integer.parseInt(x.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);
            }
            deviceVersions.setVersionsMap(map);
            deviceHash.put(deviceVersions.getDeviceInfo().getMacAddr(), deviceVersions);
            deviceHashWithSn.put(deviceVersions.getDeviceInfo().getSerialNo(), deviceVersions);
            log.info(this.serialNo + "执行了添加更新版本任务");
        }
    }
}
