package com.bocloud.ims.service.scheduler.scheduler;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.common.enums.BoCloudMethod;
import com.bocloud.common.enums.BoCloudService;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.BocloudToken;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.MapTools;
import com.bocloud.service.core.CurrentService;
import com.bocloud.service.http.core.ServiceFactory;
import com.bocloud.service.http.model.RemoteService;

/**
 * 资源使用量统计定时统计任务
 *
 * @author lkx
 * @since 2018年4月27日
 */
@Component
public class ResourceUsageScheduler {

	private static Logger logger = LoggerFactory.getLogger(ResourceUsageScheduler.class);
	@Autowired
	private CurrentService currentService;
	@Autowired
	private ServiceFactory serviceFactory;

	@Scheduled(cron = "${resource.usage.scheduler:0 0 0 * * ?}")
	protected void usage() {
		if (currentService.isLeader()) {
			try {
				logger.info("Resource usage timing statistics start...");
				Map<String, Object> headers = new HashMap<>(1);
				headers.put(BocloudToken.INTERNAL_TOKEN, currentService.getToken());
				JSONObject object = new JSONObject();
				object.put(Common.CONDITION, "listTenants");
				RemoteService remote = serviceFactory.build(BoCloudService.SMS, "/v1/tenants", BoCloudMethod.GET,
						headers, MapTools.simpleMap(Common.CONDITION, object.toJSONString()));
				BocloudResult result = remote.invoke();
				if (result.isFailed()) {
					logger.error("从Soc获取租户信息失败, {}", result.toString());
					return;
				}
				// String tenantData =
				// JSONObject.toJSONString(result.getData());
				// List<Tenant> tenants = JSONArray.parseArray(tenantData,
				// Tenant.class);
				// for (Tenant tenant : tenants) {
				// List<ResourceQuota> resourceQuotas =
				// resourceQuotaRepository.listByTarget(tenant.getId(),
				// AlarmTargetCatalog.TENANT.name());
				// for (ResourceQuota quota : resourceQuotas) {
				// // 保存的时间是当前时间的前一天
				// // 比如2018年5月24号凌晨统计的使用量是2018年5月23号的使用量数据
				// ResourceUsage resourceUsage = new
				// ResourceUsage(quota.getCategory(),
				// DateUtils.addDay(new Date(), -1), tenant.getId(),
				// quota.getUsed());
				// resourceUsageRepository.save(resourceUsage);
				// }
				// }
				logger.info("Resource usage timing statistics end...");
			} catch (Exception e) {
				logger.error("保存资源使用情况失败:", e);
				logger.info("Resource usage timing statistics exception...");
			}
		}
	}
}
