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


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.neusoft.smart.pos.dto.device.request.DeviceQueryRequest;
import com.neusoft.smart.pos.dto.device.response.DeviceResponse;
import com.neusoft.smart.pos.dto.ota.request.ApkUpgradeRequest;
import com.neusoft.smart.pos.dto.ota.request.UpgradeHistoryQueryRequest;
import com.neusoft.smart.pos.dto.ota.request.UpgradePackageQueryRequest;
import com.neusoft.smart.pos.dto.ota.response.ApkStrategyResponse;
import com.neusoft.smart.pos.dto.ota.response.ApkVersionStrategyDetailResponse;
import com.neusoft.smart.pos.dto.ota.response.AppInfoResponse;
import com.neusoft.smart.pos.dto.ota.response.UpgradeHistoryResponse;
import com.neusoft.smart.pos.dto.ota.response.UpgradePackageResponse;
import com.neusoft.smart.pos.dto.ota.response.UpgradeStrategyResponse;
import com.neusoft.smart.pos.framework.bean.PaginationExtendBean;
import com.neusoft.smart.pos.framework.utils.BeanUtil;
import com.neusoft.smart.pos.gateway.service.feignService.RemoteDeviceService;
import com.neusoft.smart.pos.gateway.service.feignService.RemoteOTAService;
import com.neusoft.smart.pos.redis.bean.AppStrategy;
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.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OTAService {
	
	@Autowired
	private RemoteOTAService remoteOTAService;
	
	@Autowired
	private RemoteDeviceService remoteDeviceService;
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	/**
	 * @param upgradeHistoryQueryRequest
	 * @return
	 */
	public PaginationExtendBean<JSONObject> queryHistoryList(UpgradeHistoryQueryRequest upgradeHistoryQueryRequest) {
		DeviceQueryRequest deviceQueryRequest = new DeviceQueryRequest();
		deviceQueryRequest.setIsPage(false);
		deviceQueryRequest.setMacAddr(upgradeHistoryQueryRequest.getDeviceMac());
		deviceQueryRequest.setSerialNo(upgradeHistoryQueryRequest.getDeviceSn());
		deviceQueryRequest.setExcludeDeleted(false);
		//先查询出来机具
		PaginationExtendBean<DeviceResponse> devices = remoteDeviceService.fetchList(deviceQueryRequest).getResult();
		List<Integer> deviceIds = devices.getRows().stream().map(DeviceResponse::getId).collect(Collectors.toList());
		PaginationExtendBean<JSONObject> result = new PaginationExtendBean<>();
		if (null != deviceIds && !deviceIds.isEmpty()) {
			upgradeHistoryQueryRequest.setDeviceIdList(deviceIds);
			//然后通过机具ids查询出来更新历史
			PaginationExtendBean<UpgradeHistoryResponse> histories = remoteOTAService.historyList(upgradeHistoryQueryRequest).getResult();
			List<JSONObject> historiesJson = histories.getRows().stream().map(item -> {
				//根据deviceId匹配机具
				DeviceResponse deviceResponse = devices.getRows().stream().filter(device -> device.getId().equals(item.getDeviceId())).findAny().orElse(new DeviceResponse());
				//都转换成json
				JSONObject resultJson = (JSONObject) JSONObject.toJSON(item);
				JSONObject deviceJson = (JSONObject) JSONObject.toJSON(deviceResponse);
				resultJson.putAll(deviceJson);
				return resultJson;
			}).collect(Collectors.toList());
			result.setRows(historiesJson);
			result.setTotal(histories.getTotal());
		} else {
			result.setRows(new ArrayList<>());
			result.setTotal(0);
		}
		return result;
	}
	
	/**
	 * @param groupId
	 * @return
	 */
	public JSONArray getStrategyList(Integer groupId) {
		JSONArray jsonArray = new JSONArray();
		List<UpgradeStrategyResponse> strategyResponseList = remoteOTAService.strategyList(groupId).getResult();
		if (!strategyResponseList.isEmpty()) {
			//查询出所有更新版本
			List<Integer> packageIds = strategyResponseList.stream().map(UpgradeStrategyResponse::getPackageId).collect(Collectors.toList());
			UpgradePackageQueryRequest upgradePackageQueryRequest = new UpgradePackageQueryRequest();
			upgradePackageQueryRequest.setIsPage(false);
			upgradePackageQueryRequest.setIds(packageIds);
			upgradePackageQueryRequest.setStatusArr(new Integer[]{0, 1, 2});
			List<UpgradePackageResponse> upgradePackageResponseList = remoteOTAService.list(upgradePackageQueryRequest).getResult().getRows();
			
			//再查询出来机具
			List<Integer> deviceIds = strategyResponseList.stream().map(UpgradeStrategyResponse::getDeviceId).collect(Collectors.toList());
			DeviceQueryRequest deviceQueryRequest = new DeviceQueryRequest();
			deviceQueryRequest.setIsPage(false);
			deviceQueryRequest.setIds(deviceIds);
			deviceQueryRequest.setExcludeDeleted(false);
			List<DeviceResponse> devices = remoteDeviceService.fetchList(deviceQueryRequest).getResult().getRows();
			
			strategyResponseList.forEach(strategy -> {
				DeviceResponse deviceResponse = devices.stream().filter(device -> strategy.getDeviceId().equals(device.getId())).findAny().orElse(new DeviceResponse());
				UpgradePackageResponse upgradePackageResponse = upgradePackageResponseList.stream().filter(upgradePackage -> strategy.getPackageId().equals(upgradePackage.getId())).findAny().orElse(new UpgradePackageResponse());
				
				JSONObject jsonObject = (JSONObject) JSONObject.toJSON(deviceResponse);
				jsonObject.putAll((JSONObject) JSONObject.toJSON(upgradePackageResponse));
				jsonArray.add(jsonObject);
			});
			
		}
		return jsonArray;
	}
	
	
	/**
	 * @param apkUpgradeRequest
	 * @return
	 */
	public AppStrategy check(ApkUpgradeRequest apkUpgradeRequest) {
		AppStrategy apkUpgradeResponse = new AppStrategy();
		try {
			if (!StringUtils.isEmpty(apkUpgradeRequest.getSn())) {
				BoundHashOperations<String, String, AppStrategy> appStrategyOperations = redisTemplate.boundHashOps("apkVersionStrategy");
				AppStrategy appStrategy = appStrategyOperations.get(apkUpgradeRequest.getSn());
				if (null == appStrategy) {
					apkUpgradeResponse.setRet(201);
					apkUpgradeResponse.setMsg("终端上报产品编码不匹配");
					return apkUpgradeResponse;
				}
				appStrategy.getApps().forEach(app -> apkUpgradeResponse.getApps().add(app)
				);
				apkUpgradeResponse.setForce(appStrategy.getForce());
				Long now = System.currentTimeMillis();
				Long differ = appStrategy.getUpgradeTime().getTime() - now;
				if (differ > 0 && differ < 1000 * 60 * 60) {
					apkUpgradeResponse.setUpdatetime((int) Math.ceil(differ / (1000 * 60)));
				}
			}
			apkUpgradeResponse.setRet(200);
			apkUpgradeResponse.setMsg("success");
		} catch (Exception e) {
			apkUpgradeResponse.setRet(500);
			apkUpgradeResponse.setMsg("检查更新失败,错误信息:" + e.getMessage());
		}
		return apkUpgradeResponse;
	}
	
	
	public ApkVersionStrategyDetailResponse getApkStrategyDetail(Integer groupId) {
		List<Integer> deviceIds = remoteOTAService.getApkVersionStrategy(groupId).getResult().stream().map(ApkStrategyResponse::getDeviceId).collect(Collectors.toList());
		DeviceQueryRequest deviceQueryRequest = new DeviceQueryRequest();
		deviceQueryRequest.setIsPage(false);
		deviceQueryRequest.setIds(deviceIds);
		deviceQueryRequest.setExcludeDeleted(false);
		List<DeviceResponse> devices = remoteDeviceService.fetchList(deviceQueryRequest).getResult().getRows();
		
		List<AppInfoResponse> appInfoResponses = remoteOTAService.getApps(groupId).getResult();
		
		ApkVersionStrategyDetailResponse apkVersionStrategyDetailResponse = new ApkVersionStrategyDetailResponse();
		apkVersionStrategyDetailResponse.setDevices(BeanUtil.parseList(devices, DeviceResponse.class));
		apkVersionStrategyDetailResponse.setApps(appInfoResponses);
		
		return apkVersionStrategyDetailResponse;
	}
}