package com.blueland.core.util;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.ObjectUtil;
import com.blueland.model.TPfSysOplog;
import com.blueland.service.ISysOplogService;
import com.blueland.service.impl.SysOplogServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.blueland.bo.SysOplogEntity;

import java.util.Date;

/**
 * 日志操作
 *@author zhengTao
 *
 */
@Component
public class LogUtil {
	
	private static ISysOplogService sysOplogService;
	
	@Autowired
	private ISysOplogService sysOplogService2;

    
    @PostConstruct
    public void beforeInit() {
    	sysOplogService = sysOplogService2;
    }
	
	/**
	 * 
	 * @param request 请求
	 * @param bizId 业务ID
	 * @param bizType 业务类型
	 * @param type 操作类型
	 * @param content 操作内容
	 * @param status 操作状态：成功：success，失败：failed
	 * @param remark 备注
	 */
	public static void addSysOplog(HttpServletRequest request, String bizId, String bizType, String type,
			String content, String status, String sys, String remark) {
		TPfSysOplog oplog = new TPfSysOplog();
		if(null != request) {
			String userAgent = request.getHeader("USER-AGENT");
			if(StringUtil.isEmpty(userAgent)) {
				userAgent = request.getHeader("User-Agent");
			}
			String userId = request.getHeader("iv-user");
			String aceessIp = getRemoteAddr(request);
			String aceessBrowse = getBrowserName(userAgent);
			oplog.setUserId(null!=userId?userId:"");
			oplog.setUserName("");
			oplog.setAceessIp(aceessIp!=null?aceessIp:"");
			oplog.setAceessBrowse(aceessBrowse!=null?aceessBrowse:"");
		}else {
			oplog.setUserId("admin");
			oplog.setUserName("管理员");
			oplog.setAceessIp("");
			oplog.setAceessBrowse("");
		}
		oplog.setBizId(bizId);
		oplog.setBizType(bizType);
		oplog.setType(type);
		oplog.setContent(content);
		oplog.setStatus(status);
		oplog.setCreateTime(new Date());
		oplog.setAppId("sys");
		oplog.setRemark(remark);
		try {
			sysOplogService.save(oplog);
		} catch (Exception e) {
			System.out.println(e);
		}
	}
	
	/**
	 * @param userId 操作人ID
	 * @param userName 操作人姓名
	 * @param request 请求
	 * @param bizId 业务ID
	 * @param bizType 业务类型
	 * @param type 操作类型
	 * @param content 操作内容
	 * @param status 操作状态：成功：success，失败：failed
	 * @param remark 备注
	 */
	public static void addSysOplog4Render(HttpServletRequest request,
			String userId,String userName,String bizId, String bizType, String type,
			String content, String status, String sys, String remark) {
		TPfSysOplog oplog = new TPfSysOplog();
		if(null != request) {
			String userAgent = request.getHeader("USER-AGENT");
			if(StringUtil.isEmpty(userAgent)) {
				userAgent = request.getHeader("User-Agent");
			}
			if(StringUtil.isEmpty(userId)) {
				userId = request.getHeader("iv-user");
			}
			String aceessIp = getRemoteAddr(request);
			String aceessBrowse = getBrowserName(userAgent);
			oplog.setUserName(userName);
			oplog.setUserId(null!=userId?userId:"");
			oplog.setAceessIp(aceessIp!=null?aceessIp:"");
			oplog.setAceessBrowse(aceessBrowse!=null?aceessBrowse:"");
		}else {
			oplog.setUserId("admin");
			oplog.setUserName("管理员");
			oplog.setAceessIp("127.0.0.1");
			oplog.setAceessBrowse("");
		}
		oplog.setCreateTime(new Date());
		oplog.setBizId(bizId);
		oplog.setBizType(bizType);
		oplog.setType(type);
		oplog.setContent(content);
		oplog.setStatus(status);
		oplog.setAceessIp(sys);
		oplog.setRemark(remark);
		try {
			sysOplogService.save(oplog);
		} catch (Exception e) {
			System.out.println(e);
		}
	}
	
	public static String getBrowserName(String agent) {
		  if(agent.indexOf("msie 7")>0){
			  return "ie7";
		  }else if(agent.indexOf("msie 8")>0){
			  return "ie8";
		  }else if(agent.indexOf("msie 9")>0){
			  return "ie9";
		  }else if(agent.indexOf("msie 10")>0){
			  return "ie10";
		  }else if(agent.indexOf("msie")>0){
			  return "ie";
		  }else if(agent.indexOf("opera")>0){
			  return "opera";
		  }else if(agent.indexOf("Chrome")>0){
			  return "Chrome";
		  }else if(agent.indexOf("firefox")>0 || agent.indexOf("Firefox") > 0){
			  return "firefox";
		  }else if(agent.indexOf("webkit")>0){
			  return "webkit";
		  }else if(agent.indexOf("QQBrowser")>0){
			  return "QQBrowser";
		  }else if(agent.indexOf("360SE")>0){
			  return "360SE";
		  }else if(agent.indexOf("gecko")>0 && agent.indexOf("rv:11")>0){
			  return "ie11";
		  }else{
			  return "Others";
		  }
	}
	

	/**
     * 获取客户端ip地址(可以穿透代理)
     * @param request
     * @return
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
		if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			if (ip.indexOf(",") != -1) {
				ip = ip.split(",")[0];
			}
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");		
		}
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");           
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_VIA");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("REMOTE_ADDR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("X-Real-IP");
        }
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip.equals("0:0:0:0:0:0:0:1")) {
			ip = "本地";
		}
		return ip;
    }

}
