package com.apobates.forum.trident.controller.admin;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.member.api.service.MemberActiveRecordsService;
import com.apobates.forum.utils.CommonBean;
import com.apobates.forum.utils.DateTimeUtils;
import com.google.gson.Gson;

/**
 * 仪表盘(Dashboard)控制器
 * 
 * @author xiaofanku@live.cn
 * @since 20190321
 */
@Controller
@RequestMapping(value = "/admin/recent")
public class HomeRecentController {
	@Autowired
	private MemberActiveRecordsService memberActiveRecordsService;
	private final static Logger logger = LoggerFactory.getLogger(HomeRecentController.class);
	
	@GetMapping(path = "/home")
	public String home(HttpServletRequest request, Model model) {
		// java Env
		Map<String, String> javaEnv = new HashMap<>();
		javaEnv.put("vm", System.getProperty("java.vm.name"));
		javaEnv.put("vm.vendor", System.getProperty("java.vm.vendor"));
		javaEnv.put("vm.mode", System.getProperty("java.vm.info"));
		javaEnv.put("version", System.getProperty("java.version"));
		javaEnv.put("specification", System.getProperty("java.specification.version"));
		model.addAttribute("javaEnv", javaEnv);
		// os Env
		Map<String, String> osEnv = new HashMap<>();
		osEnv.put("name", System.getProperty("os.name"));
		osEnv.put("version", System.getProperty("os.version"));
		osEnv.put("arch", System.getProperty("os.arch"));
		osEnv.put("cpu.endian", System.getProperty("sun.cpu.endian"));
		osEnv.put("cpu.processor", Runtime.getRuntime().availableProcessors() + "");
		model.addAttribute("osEnv", osEnv);
		model.addAttribute("hmp", calcRuntimeMemoryPercent());
		//近七天会员的活跃情况
		LocalDateTime finish = LocalDateTime.now();
		LocalDateTime start = DateTimeUtils.beforeDayForDate(finish, 7);
		//没有数据填上0
		TreeMap<String, Long> data = memberActiveRecordsService.groupMemberForActivity(start, finish);
		logger.info("[AR] DB Query Size: "+data.size());
		if(data == null || data.size()<7){
			data = DateTimeUtils.fillEmptyResult(start, finish, data);
		}
		logger.info("[AR] Fill Result Size: "+data.size());
		List<CommonBean> rs = new ArrayList<>();
		for(Entry<String,Long> entry : data.entrySet()){
			logger.info("[AR] loop day: "+entry.getKey()+", size: "+entry.getValue());
			rs.add(new CommonBean(entry.getValue(), entry.getKey()));
		}
		model.addAttribute("rs", new Gson().toJson(rs));
		return "admin/index";
	}
	@GetMapping(path="/stats/device/json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String,Float> groupMemberDeviceForGroup(HttpServletRequest request, Model model){
		Map<String,Long> data = memberActiveRecordsService.statsDevice();
		if(!data.isEmpty()){
			long total = data.values().stream().reduce(0L, (x, y) -> x + y);
			Map<String,Float> rs = new HashMap<>();
			for(Entry<String,Long> entry : data.entrySet()){
				Float tmp = entry.getValue() / Float.valueOf(total * 1.00f) * 100;
				rs.put(entry.getKey(), tmp); //计算百分比
			}
			return rs;
		}
		return Collections.emptyMap();
	}
	@GetMapping(path="/stats/isp/json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String,Long> groupMemberISPForGroup(HttpServletRequest request, Model model){
		return memberActiveRecordsService.statsIsp();
	}
	@GetMapping(path="/stats/province/json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String,Long> groupMemberProvinceForGroup(HttpServletRequest request, Model model){
		return memberActiveRecordsService.statsProvince();
	}
	
	private int calcRuntimeMemoryPercent() {
		double tm = Runtime.getRuntime().totalMemory() / (1024 * 1024);
		double fm = Runtime.getRuntime().freeMemory() / (1024 * 1024);
		double pm = (tm - fm) / tm * 100;
		BigDecimal bg = new BigDecimal(pm).setScale(2, RoundingMode.UP);
		return bg.intValue();
	}
	
}
