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

import com.neusoft.smart.pos.dto.ota.request.API.DevicePostBaseRequest;
import com.neusoft.smart.pos.dto.ota.request.API.DevicePostRequestByXK;
import com.neusoft.smart.pos.dto.ota.response.API.DevicePostBaseResponse;
import com.neusoft.smart.pos.dto.ota.response.API.DevicePostResponseByXK;
import com.neusoft.smart.pos.framework.task.TaskExecutor;
import com.neusoft.smart.pos.gateway.task.DevicePostRequest2XKTask;
import com.neusoft.smart.pos.gateway.task.UpdateDeviceRequestTimeTask;
import com.neusoft.smart.pos.redis.bean.DeviceVersion;
import com.neusoft.smart.pos.redis.bean.DeviceVersionList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

@Service("upgradeService4XK")
public class UpgradeService4XKImpl implements UpgradeServiceInterface {
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private TaskExecutor taskExecutor;
    
    @Override
    public DevicePostBaseResponse solveDeviceRequest(DevicePostBaseRequest devicePostBaseRequest) {
        DevicePostResponseByXK response = new DevicePostResponseByXK();
        DevicePostRequestByXK devicePostRequest = (DevicePostRequestByXK) devicePostBaseRequest;
        BoundHashOperations<String, String, DeviceVersionList> deviceMap = redisTemplate.boundHashOps("deviceVersionsMap");
        BoundHashOperations<String, String, DeviceVersionList> deviceSnMap = redisTemplate.boundHashOps("deviceVersionsMapWithSn");
        DeviceVersionList deviceVersions = deviceMap.get(devicePostRequest.getSn());
        //mac地址里边没有，换个序列号的试试看
        if (null == deviceVersions) {
            deviceVersions = deviceSnMap.get(devicePostRequest.getSn());
        }
        
        //没找到机具
        //机具的状态是已停用
        if (null == deviceVersions || deviceVersions.getDeviceInfo().getStatus().equals(1) || deviceVersions.getDeviceInfo().getStatus().equals(2)) {
            return response;
        }
        
        //更新一下设备的最新请求时间 熙康没有 ip 信号强度 设置成空
        UpdateDeviceRequestTimeTask updateDeviceRequestTimeTask = new UpdateDeviceRequestTimeTask();
        updateDeviceRequestTimeTask.setIPAddress(null);
        updateDeviceRequestTimeTask.setSignalStrength(null);
        updateDeviceRequestTimeTask.setSerialno(devicePostRequest.getSn());
        taskExecutor.getExecutorService().submit(updateDeviceRequestTimeTask);
        
        //拿请求版本的下一个版本
        String deviceReqVersion = devicePostRequest.getVersion_from();
        if (!StringUtils.isEmpty(deviceReqVersion)) {
            deviceReqVersion = deviceReqVersion.substring(deviceReqVersion.indexOf("#") + 1);
        }
        //首先判断xxx_xxx格式的版本
        Integer toVersion = 0;
        for (String key : deviceVersions.getVersionsMap().keySet()) {
            String[] versionPair = key.split("_");
            if (versionPair.length == 2) {
                Integer temp = Integer.valueOf(versionPair[1]);
                if (key.startsWith(deviceReqVersion + "_") && temp > toVersion) {
                    toVersion = temp;
                }
            }
        }
        DeviceVersion nextVersion;
        //如果xxx_xxx版本没找到,兼容以前的格式 查询一下新版本
        if (toVersion == 0) {
            Integer reqSubVersion = Integer.parseInt(deviceReqVersion);
            //拿请求版本的下一个版本
            nextVersion = this.getNextVersion(deviceVersions, deviceReqVersion, reqSubVersion);
        } else {
            nextVersion = deviceVersions.getVersionsMap().get(deviceReqVersion + "_" + toVersion);
        }
        
        
        //没找到新版本, 已经是最新版
        if (null == nextVersion) {
            return response;
        }
        
        //查询看看是否有全量包 暂时未考虑策略状态
        Integer nextSubVersion =nextVersion.getVersionCode().contains("_")?Integer.valueOf(nextVersion.getVersionCode().split("_")[1]):
                Integer.parseInt(nextVersion.getVersionCode().substring(nextVersion.getVersionCode().lastIndexOf(".") + 1));
//        for (Map.Entry<String, DeviceVersion> entry : deviceVersions.getVersionsMap().entrySet()) {
//            if (nextSubVersion < Integer.parseInt(entry.getKey().substring(entry.getKey().lastIndexOf(".") + 1))
//                    && entry.getValue().getFileType().equals(1)) {
//                nextVersion = entry.getValue();
//            }
//        }
        //设置下最新的版本
//        nextSubVersion = Integer.parseInt(nextVersion.getVersionCode().substring(nextVersion.getVersionCode().lastIndexOf(".") + 1));
        //没到时间等一会儿
        Long now = new Date().getTime();
        Long differ = nextVersion.getUpdateBeginTime() - now;
        if (differ > 0 && differ > 1000 * 60 * 60) {
            return response;
        }
        
        response.setPackageid(nextVersion.getId().toString());
        response.setVersion_to(devicePostRequest.getModel() + "-user_#" + nextSubVersion);
        response.setReleaseNote(nextVersion.getReleaseNote());
        response.setDownload_url(nextVersion.getFilePath() + nextVersion.getFileName().replace("#", "%23"));
//        returnMap.put("ReleaseNote", devicePostRequestByXK.getModel()+" official " + devicePostRequest.getVersion()+"-"+nextVersion.getVersionCode());
        //最终返回之前 处理一下升级历史和设备版本
        DevicePostRequest2XKTask devicePostRequestTask = new DevicePostRequest2XKTask();
        devicePostRequestTask.setSerialno(devicePostRequest.getSn());
        devicePostRequestTask.setVersion(nextVersion.getVersionCode());
        taskExecutor.getExecutorService().submit(devicePostRequestTask);
        return response;
    }
}
