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

import com.alibaba.fastjson.JSONObject;
import com.neusoft.smart.pos.dto.advertisement.response.MediaStrategyResponse;
import com.neusoft.smart.pos.dto.device.request.DeviceQueryRequest;
import com.neusoft.smart.pos.dto.device.response.DeviceResponse;
import com.neusoft.smart.pos.framework.task.TaskExecutor;
import com.neusoft.smart.pos.gateway.service.feignService.RemoteAdvertisementService;
import com.neusoft.smart.pos.gateway.service.feignService.RemoteDeviceService;
import com.neusoft.smart.pos.gateway.task.MediaStrategyCancelTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AdvertisementService {
	
	@Autowired
	private RemoteAdvertisementService remoteAdvertisementService;
	
	@Autowired
	private RemoteDeviceService remoteDeviceService;
	
	@Autowired
	private TaskExecutor taskExecutor;
	
	/**
	 * 查询广告策略关系数据
	 *
	 * @param groupId
	 * @return
	 */
	public JSONObject getStrategyList(Integer groupId) {
		JSONObject jsonObject = new JSONObject();
		List<MediaStrategyResponse> strategyResponseList = remoteAdvertisementService.getRelation(groupId).getResult();
		List<Integer> deviceIds = strategyResponseList.stream().map(MediaStrategyResponse::getDeviceId).collect(Collectors.toList());
		DeviceQueryRequest deviceQueryRequest = new DeviceQueryRequest();
		deviceQueryRequest.setIsPage(false);
		deviceQueryRequest.setIds(deviceIds);
		List<DeviceResponse> deviceList = remoteDeviceService.fetchList(deviceQueryRequest).getResult().getRows();
		jsonObject.put("deviceList", deviceList);
		Map<Integer, MediaStrategyResponse> resourceMap = strategyResponseList.stream().collect(Collectors.toMap(MediaStrategyResponse::getMediaResourceId,
				mediaStrategyResponse -> mediaStrategyResponse, (oldValue, newValue) -> oldValue));
		jsonObject.put("resourceList", resourceMap.values());
		
		return jsonObject;
	}
	
	/**
	 * @param groupId
	 */
	public void cancel(Integer groupId) {
		remoteAdvertisementService.cancel(groupId);
		MediaStrategyCancelTask mediaStrategyCancelTask = new MediaStrategyCancelTask();
		mediaStrategyCancelTask.setGroupId(groupId);
		taskExecutor.getExecutorService().submit(mediaStrategyCancelTask);
	}
	
	public JSONObject queryAd(String sn) {
		return remoteAdvertisementService.queryAd(sn);
	}
}
