package com.yh.saas.platform.controller;

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.winsea.svc.base.base.util.ClientTypeChecker;

/**
 * <p>
 * 服务器 前端控制器
 * </p>
 *
 * @author zhaojz
 * @since 2019-04-03
 */
@RestController
@RequestMapping("/system")
public class SystemController {

	@Value("${comany-mgr-url}")
	private String comanyMgrUrl;

	@Value("${file-show-path}")
	private String fileShowPath;

	@Value("${pc-url}")
	private String pcUrl;

	/**
	 * 获得服务器地址
	 * 
	 * @param request
	 * @return
	 * @throws UnknownHostException
	 * @throws Exception
	 */
	@GetMapping("/query/getRootUrl")
	public Object getRootUrl(HttpServletRequest request) {
		String ip = getIpAddr(request);
		int port = request.getLocalPort();
		return "http://" + ip + ":" + port + "/";
	}

	/**
	 * 获得服务器地址
	 *
	 * @param request
	 * @return
	 * @throws UnknownHostException
	 * @throws Exception
	 */
	@GetMapping("/query/getComanyMgrUrl")
	public Object getFileUploadUrl() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("fileUrl", fileShowPath);
		map.put("comanyMgrUrl", comanyMgrUrl);
		map.put("pcUrl", pcUrl);
		return map;
	}

	/**
	 * 判断当前客户端是否是船端
	 */
	@GetMapping("/query/isVesselTerminal")
	public boolean isVesselTerminal() {
		return ClientTypeChecker.isVesselTerminal();
	}

	/**
	 * 判断当前客户端是否是岸基
	 */
	@GetMapping("/query/isLandBased")
	public boolean isLandBased() {
		return ClientTypeChecker.isLandBased();
	}

	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (!isNullIp(ip) && ip.indexOf(',') != -1) {
			ip = ip.split(",")[0];
		}
		if (isNullIp(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (isNullIp(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (isNullIp(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (isNullIp(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (isNullIp(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (isNullIp(ip)) {
			ip = request.getLocalAddr();
		}
		return ip;
	}

	private boolean isNullIp(String ip) {
		return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || StringUtils.equals("127.0.0.1", ip);
	}
}
