package com.mosty.common.core.business.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.common.base.constant.Constants;
import com.mosty.common.base.entity.log.SysOperLog;
import com.mosty.common.base.util.IpUtil;
import com.mosty.common.base.util.StringUtils;
import com.mosty.common.core.business.entity.SysDept;
import com.mosty.common.core.business.entity.SysLogininfor;
import com.mosty.common.core.business.entity.SysUser;
import com.mosty.common.core.business.entity.SysUserDept;
import com.mosty.common.core.business.entity.request.LoginLogPage;
import com.mosty.common.core.business.entity.vo.DeptVo;
import com.mosty.common.core.business.mapper.SysDeptMapper;
import com.mosty.common.core.business.mapper.SysLogininforMapper;
import com.mosty.common.core.business.mapper.SysUserDeptMapper;
import com.mosty.common.core.business.service.SysLogininforService;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.common.util.PermissionsUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author li
 * @description 针对表【sys_logininfor(系统访问记录)】的数据库操作Service实现
 * @createDate 2022-03-20 15:01:16
 */
@Service
public class SysLogininforServiceImpl extends ServiceImpl<SysLogininforMapper, SysLogininfor>
        implements SysLogininforService {
    @Resource
    private SysLogininforMapper sysLogininforMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysUserDeptMapper sysUserDeptMapper;

    @Override
    public void recordLogininfor(SysUser user, String status, String message, HttpServletRequest request, String type) {
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));

        // 获取客户端操作系统
        String os = userAgent.getOs().getName() == null ? "未知" : userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName() == null ? "未知" : userAgent.getBrowser().getName();
        // 封装对象
        SysLogininfor logininfor = new SysLogininfor();
        try {
            String ipAddress = IpUtil.getIpAddress(request);
            logininfor.setIpaddr(ipAddress);
        }catch (Exception e){
            log.error("IP获取异常"+e.getMessage());
        }
        logininfor.setUserName(user.getUserName());
        logininfor.setBrowser(browser);
        logininfor.setOs(os);
        logininfor.setMsg(message);
        logininfor.setType(type);
        logininfor.setAccessTime(LocalDateTime.now());
        logininfor.setUserId(String.valueOf(user.getId()));
        logininfor.setSfzh(user.getIdEntityCard());
        // 日志状态
        if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
            logininfor.setStatus(Constants.SUCCESS);
        } else if (Constants.LOGIN_FAIL.equals(status)) {
            logininfor.setStatus(Constants.FAIL);
        }
        DeptVo dept = this.getDeptInfoByUserId(String.valueOf(user.getId()));
        logininfor.setSsbm(dept.getDeptname());
        logininfor.setSsbmid(dept.getDeptid());
        logininfor.setSsbmdm(dept.getDeptcode());
        logininfor.setSsxgajdm(dept.getFxjcode());
        logininfor.setSsxgajid(dept.getFxjid());
        logininfor.setSsxgaj(dept.getFxjname());
        logininfor.setSssgaj(dept.getDszname());
        logininfor.setSssgajdm(dept.getDszcode());
        logininfor.setSssgajid(dept.getDszid());

        // 插入数据
        this.save(logininfor);
    }

    public DeptVo getDeptInfoByUserId(String userId) {
        SysUserDept sysUserDept = this.sysUserDeptMapper.selectOne(
                new QueryWrapper<SysUserDept>()
                        .eq("user_id", String.valueOf(userId))
                        .last(" limit 1")
        );
        if (sysUserDept != null) {
            SysDept sysDept = this.sysDeptMapper.selectById(sysUserDept.getDeptId());
            if (sysDept != null) {
                return this.getOrgByDeptId(String.valueOf(sysDept.getId()));
            }
        }
        return null;
    }

    public DeptVo getOrgByDeptId(String deptid) {
        DeptVo vo = new DeptVo();
        SysDept dept = this.sysDeptMapper.selectById(deptid);
        if (dept != null) {
            vo.setOrgType(dept.getOrgType());
            vo.setOrgLevel(dept.getOrgLevel());
            String rootPath = dept.getRootPath();
            if (rootPath != null) {
                String[] paths = rootPath.split("_");
                if (paths.length == 2) {
                    this.setDept(vo, dept);
                    this.setDsz(vo, dept);
                } else if (paths.length == 3) {
                    this.setDept(vo, dept);
                    this.setFxj(vo, dept);
                    SysDept dsz = this.sysDeptMapper.selectById(paths[1]);
                    this.setDsz(vo, dsz);
                } else if (paths.length >= 4) {
                    this.setDept(vo, dept);
                    SysDept fxj = this.sysDeptMapper.selectById(paths[2]);
                    this.setFxj(vo, fxj);
                    SysDept dsz = this.sysDeptMapper.selectById(paths[1]);
                    this.setDsz(vo, dsz);
                }
            }
        }
        return vo;
    }

    // 设置所属单位
    private void setDept(DeptVo vo, SysDept dept) {
        if (dept != null) {
            vo.setDeptid(String.valueOf(dept.getId()));
            vo.setDeptcode(dept.getOrgCode());
            vo.setDeptname(dept.getOrgName());
        }
    }

    // 设置分县局
    private void setFxj(DeptVo vo, SysDept dept) {
        if (dept != null) {
            vo.setFxjid(String.valueOf(dept.getId()));
            vo.setFxjcode(dept.getOrgCode());
            vo.setFxjname(dept.getOrgName());
        }
    }

    // 设置地市州
    private void setDsz(DeptVo vo, SysDept dept) {
        if (dept != null) {
            vo.setDszid(String.valueOf(dept.getId()));
            vo.setDszcode(dept.getOrgCode());
            vo.setDszname(dept.getOrgName());
        }
    }

    @Override
    public void deleteOperLogByIds(List<Long> ids) {
        sysLogininforMapper.delete(new LambdaQueryWrapper<SysLogininfor>().in(SysLogininfor::getInfoId, ids));
    }

    @Override
    public void cleanOperLog() {
        sysLogininforMapper.cleanOperLog();
    }

    @Override
    public IPage<SysLogininfor> selectByPage(LoginLogPage dto) {
        QueryWrapper<SysLogininfor> qw = new QueryWrapper<>();
        UserInfo user = UserInfoManager.get();
        PermissionsUtil.queryWrapperUtil(qw, user);
        qw.lambda().like(StringUtils.isNotBlank(dto.getUserName()), SysLogininfor::getUserName, dto.getUserName())
                .eq(Objects.nonNull(dto.getStatus()), SysLogininfor::getStatus, dto.getStatus());
        qw.lambda().orderByDesc(SysLogininfor::getInfoId);
        return this.page(dto, qw);
    }
}




