package com.tuoheng.system.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tuoheng.common.utils.*;
import com.tuoheng.system.constant.Constants;
import com.tuoheng.system.entity.LoginLog;
import com.tuoheng.system.entity.OperLog;
import com.tuoheng.system.entity.Tenant;
import com.tuoheng.system.entity.User;
import com.tuoheng.system.mapper.TenantMapper;
import com.tuoheng.system.query.UserQuery;
import com.tuoheng.system.service.ILoginLogService;
import com.tuoheng.system.service.IOperLogService;
import com.tuoheng.system.service.impl.TenantServiceImpl;
import com.tuoheng.system.service.impl.UserServiceImpl;
import com.tuoheng.system.utils.ShiroUtils;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 */
@Slf4j
public class AsyncFactory {

    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    /**
     * 记录登陆信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message,
                                             final Object... args) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        //final String ip = ShiroUtils.getIp();
        log.info("获取ip地址为：" + ip);
        String ipArr[] = ip.split(",");
        return new TimerTask() {
            @Override
            public void run() {
                //String address = IpUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ipArr[0]));
                //s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                LoginLog loginLog = new LoginLog();
                if (Constants.LOGIN_SUCCESS.equals(status)) {
                    loginLog.setType(1);
                    loginLog.setTitle("登录系统");
                } else if (Constants.LOGOUT.equals(status)) {
                    loginLog.setType(2);
                    loginLog.setTitle("注销系统");
                }
                loginLog.setUsername(username);
                loginLog.setLoginIp(ipArr[0]);
                //loginLog.setLoginLocation(address);
                loginLog.setBrowser(browser);
                //add tenantId 2023.1.12
                loginLog.setTenantId(getTenantId(username));
                //end
                loginLog.setOs(os);
                loginLog.setNote(message);
                // 日志状态
                if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
                    loginLog.setStatus(Integer.valueOf(Constants.SUCCESS));
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    loginLog.setStatus(Integer.valueOf(Constants.FAIL));
                }
                // 插入数据
                SpringUtils.getBean(ILoginLogService.class).insertLoginLog(loginLog);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final OperLog operLog) {
        return new TimerTask() {
            @Override
            public void run() {
                operLog.setTenantId(getTenantId(operLog.getOperName()));
                // 远程查询操作地点
                operLog.setOperLocation(IpUtils.getRealAddressByIP(operLog.getOperIp()));
                SpringUtils.getBean(IOperLogService.class).insertOperlog(operLog);
            }
        };
    }

    public static int getTenantId(String username){
        //add tenantId 2023.1.12
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        queryWrapper.eq("mark",1);
        User user = SpringUtils.getBean(UserServiceImpl.class).getOne(queryWrapper);
        if (user.getTenantId()==0){
            queryWrapper =new QueryWrapper();
            queryWrapper.eq("user_id",user.getId());
            queryWrapper.eq("mark",1);
            Tenant tenant = SpringUtils.getBean(TenantMapper.class).selectOne(queryWrapper);
            return tenant.getId();
        }
        return user.getTenantId();
        //end add tenantId
    }
}
