package com.ruoyi.framework.manager.factory;

import java.util.TimerTask;

import com.ruoyi.common.core.domain.dto.SchoolGradeClassesDto;
import com.ruoyi.common.core.domain.entity.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysLogininforService;
import com.ruoyi.system.service.ISysOperLogService;
import eu.bitwalker.useragentutils.UserAgent;

/**
 * 异步工厂（产生任务用）
 * 
 * @author voluntary
 */
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(SysUser currentUser, final String username, final String status, final String message,
                                             final Object... args) {
        if (username.startsWith("batch")) {
            return new TimerTask() {
                @Override
                public void run() {

                }
            };
        }
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        return new TimerTask()
        {
            @Override
            public void run()
            {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                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();
                // 封装对象
                SysLogininfor logininfor = new SysLogininfor();
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                if(null != currentUser) {
                    if(null!=currentUser.getSchool()){
                        SchoolGradeClassesDto school =currentUser.getSchool();
                        logininfor.setSchoolId(school.getSchoolId());
                        logininfor.setSchoolName(school.getSchoolName());
                    }
                }
                //莫20211101
                logininfor.setSource(getSource(username,os,browser));
                // 日志状态
                if (Constants.LOGIN_SUCCESS.equals(status))
                {
                    logininfor.setStatus(Constants.SUCCESS);
                }
                else if (Constants.LOGOUT.equals(status))
                {
                    logininfor.setStatus(Constants.LOGOUT_COMM);
                }
                else if (Constants.LOGIN_FAIL.equals(status))
                {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
            }
        };
    }

    /**
     * @param userName * 来源（1web端，2app，3后台，4名学微课宝，5h5，6家长端（微信公众号））
     * @return
     */
    static Integer getSource(String userName,String os,String browser){
        Integer source = -1;
        if(userName.contains("frontApp")){
            source = 2;
        }else if(userName.contains("front")){
            source = 1;
        }else if(userName.contains("back")){
            source = 3;
        }else if(userName.contains("microClass")){
            source = 4;
        }else if(userName.contains("h5")){
            source = 5;
        }else if(userName.contains("wechat")){
            source = 6;
        }

        //处理"null:GS00000008"或“GS00000008”的情况，增加补充机制
        if(source==-1){
            if(StringUtils.isNotBlank(os)){
                if(os.contains("Android")&&StringUtils.isNotEmpty(browser)&&browser.contains("Chrome")){
                    //h5
                    source = 5;
                    return source;
                }else if(os.contains("Android")||os.contains("iPhone")){
                    source = 2;
                }else if(os.contains("Windows")){
                    source = 1;
                }
            }
        }
        return source;
    }


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