package util;

import common.context.*;
import common.model.UserLog;
import common.repository.UserLogRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

import java.util.Date;

/**
 * Created by zxy on 2017/12/15.
 */
public class UserLogThread
        extends Thread
{
    protected Logger logger = LoggerFactory.getLogger(UserLogThread.class);

    private UserLogRepository userLogRepository = AppUtils.getApplicationContext().getBean(UserLogRepository.class);
    //操作用户
    private String operaAccount;
    //操作用户名
    private String accountName;
    //操作对象的类型：OperateObjectTypeEnum
    private String operateObjectType;
    //客户管理和系统账号管理是操作对象的账号，以后再加别的模块再定
    private String operateObject;
    //操作类型：“创建账号”“编辑账号”“录入缴费信息”“录入回访信息”“处理过期提醒”等等，如果都定下来有哪些，可以做一个字典
    private String operateType;
    //为了获取ip及解析地点
    private HttpServletRequest request;

    /**
     * 传入内容为对象
     * UserLogThread userlog = new UserLogThread("zxy@reyun.com", "zxy", OperateObjectTypeEnum.CUSTOMER.getKey(), "app", "查看app", request);
     * userlog.start();
     */
    public UserLogThread(String operaAccount, String accountName, String operateObjectType, String operateObject, String operateType, HttpServletRequest request)
    {
        this.operaAccount = operaAccount;
        this.accountName = accountName;
        this.operateObjectType = operateObjectType;
        this.operateObject = operateObject;
        this.operateType = operateType;
        this.request = request;
    }


    @Override
    public void run()
    {
        try
        {
            UserLog audit = new UserLog();
            audit.setOperaAccount(this.operaAccount);
            audit.setAccountName(this.accountName);
            audit.setOperateObjectType(this.operateObjectType);
            audit.setOperateObject(this.operateObject);
            audit.setOperateTime(DateUtil.format(new Date(), DateUtil.C_TIME_PATTON_DEFAULT));
            audit.setOperateType(this.operateType);

            if (this.request != null) {
                String ipAddr = IPAddrUtil.getIpAddrNew(request);
                audit.setIp(ipAddr);
                if(ValidateUtil.isValid(ipAddr)){
                    String locationFromIpAddr = IPAddrUtil.getLocationFromIpAddr(ipAddr);
                    audit.setLocation(locationFromIpAddr);
                }
            }


            userLogRepository.save(audit);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
