package com.rongwei.trainingcommon.sys.utils;

import com.rongwei.commonservice.serial.service.SysSerialNumberService;
import com.rongwei.commonservice.service.RedisService;
import com.rongwei.rwadmincommon.system.domain.SysOrganizationDo;
import com.rongwei.rwadmincommon.system.vo.SysOrganizationVo;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.rongwei.safecommon.utils.SaveConstans.MINUS_ONE;

/**
 * TrainingUtils class
 *
 * @author XH
 * @date 2023/12/12
 */
@Component
public class TrainingUtils {

    private static final Logger log = LoggerFactory.getLogger(TrainingUtils.class.getName());
    private static SysSerialNumberService sysSerialNumberService;
    private static RedisService redisService;
    @Autowired
    private SysSerialNumberService autoSysSerialNumberService;
    @Autowired
    private RedisService autoRedisService;

    public static SysUserVo getCurrentUser() {
        // 获取当前登录人信息
        SysUserVo currUser = null;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            if (request != null) {
                String token = request.getHeader("token");
                if (com.rongwei.rwcommon.utils.StringUtils.isNotEmpty(token)) {
                    currUser = redisService.getLoginUser(token);
                }
            }
        }
        return currUser;
    }

    public static String getCurrentUserFactoryId(SysUserVo currentUser) {
        if (currentUser == null) {
            currentUser = getCurrentUser();
        }
        List<SysOrganizationVo> organizationDoList = currentUser.getOrganizationDoList();
        String factoryId = organizationDoList.stream()
                .filter(org -> MINUS_ONE.equals(org.getPid()))
                .map(SysOrganizationDo::getId)
                .distinct()
                .collect(Collectors.joining(","));
        if (StringUtils.isBlank(factoryId)) {
            factoryId = organizationDoList.stream().map(info -> info.getFullpid().split(",")[1]).distinct().collect(Collectors.joining(","));
        }
        return factoryId;
    }


    @PostConstruct
    public void init() {
        redisService = autoRedisService;
        sysSerialNumberService = autoSysSerialNumberService;
    }
}
