package com.emr.service.emrLog;

import com.emr.dao.emrLog.Emr_LogMapper;
import com.emr.entity.Power_User;
import com.emr.entity.emrLog.Emr_Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/7/10 10:33
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/7/10 10:33
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Service
@Transactional
public class LogServiceImpl implements LogService {
    @Autowired
    private Emr_LogMapper logMapper;
    @Override
    public void insert(Emr_Log log) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        // 从session获取用户名
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String username = user.getUserName();
        log.setCreater(username);
        // 获取系统当前时间
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        log.setCreateDate(fmt.format(new Date()));
        // 获取访问真实IP
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                assert inet != null;
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        log.setSysFlag("emr_record");
        //字符串太长，截取
        String remark = log.getRemark();
        if(StringUtils.isNoneBlank(remark) && remark.length() > 100){
            remark = remark.substring(0,100);
            log.setRemark(remark);
        }
        log.setIp(ipAddress);
        logMapper.insert(log);
    }

    @Override
    public void insertInterface(Emr_Log log, String userName) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        // 从session获取用户名
        log.setCreater(userName);
        // 获取系统当前时间
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        log.setCreateDate(fmt.format(new Date()));
        // 获取访问真实IP
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                assert inet != null;
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        log.setSysFlag("emr_record");
        //字符串太长，截取
        String remark = log.getRemark();
        if(StringUtils.isNoneBlank(remark) && remark.length() > 100){
            remark = remark.substring(0,100);
            log.setRemark(remark);
        }
        log.setIp(ipAddress);
        logMapper.insert(log);
    }

    @Override
    public void autoInsert(Emr_Log log) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        log.setCreateDate(fmt.format(new Date()));
        log.setSysFlag("emr_record");
        logMapper.insert(log);
    }

    @Override
    public void deleteLogById(Integer logId) {
        logMapper.deleteByPrimaryKey(logId);
    }

    @Override
    public Map<String,Object> selectObjectByKey(String tableName, String whereSql) {
        return logMapper.selectObjectByKey(tableName, whereSql);
    }

    @Override
    public int delLogsByDate(String date) {
        return logMapper.delLogsByDate(date);
    }

    @Override
    public void deleteLogByIds(String str) {
        logMapper.deleteLogByIds(str);
    }
}
