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.DevicePostRequest;
import com.neusoft.smart.pos.dto.ota.response.API.DevicePostBaseResponse;
import com.neusoft.smart.pos.dto.ota.response.API.DevicePostResponse;
import com.neusoft.smart.pos.framework.task.TaskExecutor;
import com.neusoft.smart.pos.gateway.constants.ResponseStatusEnum;
import com.neusoft.smart.pos.gateway.task.DevicePostRequestTask;
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 lombok.extern.slf4j.Slf4j;
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 java.util.Date;
import java.util.Map;

@Service("upgradeService")
@Slf4j
public class UpgradeServiceImpl implements UpgradeServiceInterface {
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	@Autowired
	private TaskExecutor taskExecutor;
	
	@Override
	public DevicePostBaseResponse solveDeviceRequest(DevicePostBaseRequest devicePostBaseRequest) {
		DevicePostRequest devicePostRequest = (DevicePostRequest) devicePostBaseRequest;
		DevicePostResponse response = new DevicePostResponse();
		BoundHashOperations<String, String, DeviceVersionList> deviceMap = redisTemplate.boundHashOps("deviceVersionsMap");
		BoundHashOperations<String, String, DeviceVersionList> deviceSnMap = redisTemplate.boundHashOps("deviceVersionsMapWithSn");
		DeviceVersionList deviceVersions = deviceMap.get(devicePostRequest.getSerialno());
		//mac地址里边没有，换个序列号的试试看
		if (null == deviceVersions) {
			deviceVersions = deviceSnMap.get(devicePostRequest.getSerialno());
		}
		//没找到机具
		if (null == deviceVersions) {
			response.getSystem().setRet(ResponseStatusEnum.RESPONSE_STATUS.STATUS_201.getKey());
			response.getSystem().setMsg(ResponseStatusEnum.RESPONSE_STATUS.STATUS_201.getValue());
			return response;
		}
		//机具的状态是已停用 和删除的
		if (deviceVersions.getDeviceInfo().getStatus().equals(1) || deviceVersions.getDeviceInfo().getStatus().equals(2)) {
			response.getSystem().setRet(ResponseStatusEnum.RESPONSE_STATUS.STATUS_203.getKey());
			response.getSystem().setMsg(ResponseStatusEnum.RESPONSE_STATUS.STATUS_203.getValue());
			return response;
		}
		
		//更新一下设备的最新请求时间 ip 信号强度
		UpdateDeviceRequestTimeTask updateDeviceRequestTimeTask = new UpdateDeviceRequestTimeTask();
		updateDeviceRequestTimeTask.setIPAddress(devicePostRequest.getIPAddress());
		updateDeviceRequestTimeTask.setSignalStrength(devicePostRequest.getSignalStrength());
		updateDeviceRequestTimeTask.setSerialno(devicePostRequest.getSerialno());
		taskExecutor.getExecutorService().submit(updateDeviceRequestTimeTask);
		
		String deviceReqVersion = devicePostRequest.getVersion();
		Integer reqSubVersion;
		
		//取出请求最后小版本号,出异常了表示版本号不是x.x.x的格式
		try {
			reqSubVersion = Integer.parseInt(devicePostRequest.getVersion().substring(devicePostRequest.getVersion().lastIndexOf(".") + 1));
		} catch (Exception e) {
			response.getSystem().setRet(ResponseStatusEnum.RESPONSE_STATUS.STATUS_202.getKey());
			response.getSystem().setMsg(ResponseStatusEnum.RESPONSE_STATUS.STATUS_202.getValue());
			return response;
		}
		
		//拿请求版本的下一个版本
		DeviceVersion nextVersion = this.getNextVersion(deviceVersions, deviceReqVersion, reqSubVersion);
		
		//没找到新版本, 已经是最新版
		if (null == nextVersion) {
			response.getSystem().setRet(ResponseStatusEnum.RESPONSE_STATUS.STATUS_101.getKey());
			response.getSystem().setMsg(ResponseStatusEnum.RESPONSE_STATUS.STATUS_101.getValue());
			return response;
		}
		
		//查询看看是否有全量包 暂时未考虑策略状态
		Integer nextSubVersion = 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();
			}
		}
		
		//没到时间等一会儿
		Long now = new Date().getTime();
		Long differ = nextVersion.getUpdateBeginTime() - now;
		if (differ > 0 && differ < 1000 * 60 * 60) {
			response.getSystem().setRet(ResponseStatusEnum.RESPONSE_STATUS.STATUS_103.getKey());
			response.getSystem().setMsg(ResponseStatusEnum.RESPONSE_STATUS.STATUS_103.getValue());
			response.setUpdatetime(Math.ceil(differ / (1000 * 60)) + "");
			return response;
		}
		
		response.getSystem().setRet(ResponseStatusEnum.RESPONSE_STATUS.STATUS_0.getKey());
		response.getSystem().setVersion(nextVersion.getVersionCode());
		//云pos 必须去掉最后边的斜线.........
		if (nextVersion.getFilePath().endsWith("/")) {
			nextVersion.setFilePath(nextVersion.getFilePath().substring(0, nextVersion.getFilePath().length() - 1));
		}
		response.getSystem().setPath(nextVersion.getFilePath());
		response.getSystem().setName(nextVersion.getFileName());
		response.getSystem().setMd5(nextVersion.getMd5Code().toUpperCase());
		//为了云pos分片下载计算错误,小于某个版本的都有这个问题
		if (reqSubVersion < 447) {
			response.getSystem().setSize((nextVersion.getFileSize() - 1) + "");
		} else {
			response.getSystem().setSize(nextVersion.getFileSize().toString());
		}
		response.getSystem().setMsg(ResponseStatusEnum.RESPONSE_STATUS.STATUS_0.getValue());
		//return downloadQueueService.add2Queue(devicePostRequest.getSerialno(), response);
		//最终返回之前 处理一下升级历史和设备版本
		DevicePostRequestTask devicePostRequestTask = new DevicePostRequestTask();
		devicePostRequestTask.setVersion(nextVersion.getVersionCode());//设置下最新版本的code
		devicePostRequestTask.setSerialno(devicePostRequest.getSerialno());
		taskExecutor.getExecutorService().submit(devicePostRequestTask);
		return response;
	}
}
