package com.rongwei.sfcommon.utils;

import com.rongwei.commonservice.serial.service.SysSerialNumberService;
import com.rongwei.commonservice.service.RedisService;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommonentity.commonservers.vo.SysSerialVo;
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.Calendar;
import java.util.Date;

import static com.rongwei.safecommon.utils.SaveConstans.AQ_ORG_CODE_MAP;
import static com.rongwei.safecommon.utils.SaveConstans.ORG_CODE_MAP;

/**
 * CommonUtil class
 *
 * @author XH
 * @date 2021/01/08
 */
@Component
public class CommonUtil {

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

    public static String getWeekForYear(boolean returnLastWeek) {
        return getWeekForYear(new Date(), returnLastWeek);
    }

    /**
     * @param date           日期
     * @param returnLastWeek 判断是否返回上一周
     * @return
     */
    public static String getWeekForYear(Date date, boolean returnLastWeek) {
        if (date == null) {
            return getWeekForYear(new Date(), returnLastWeek);
        }
        log.debug("get week and year for date:{}", date);
        Calendar instance = Calendar.getInstance();
        // MinimalDaysInFirstWeek 在今年的第一个星期所需的最少天数
        instance.setFirstDayOfWeek(Calendar.MONDAY);
        instance.setMinimalDaysInFirstWeek(1);
        instance.setTime(date);
        int weekNum = instance.get(Calendar.WEEK_OF_YEAR);
        int YearNum = instance.getWeekYear();
        if (returnLastWeek) {
            log.debug("需要获取上一周的数据");
            if (weekNum - 1 == 0) {
                weekNum = 52;
                YearNum = YearNum - 1;
            }
            return YearNum + ";" + (weekNum - 1);
        }
        return YearNum + ";" + weekNum;
    }

    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;
    }

    /**
     * 流水码生成
     *
     * @param moduleCode      流水码CODE
     * @param ruleTemplateStr 流水码编码规则
     * @param tenantId        租户id
     * @return
     */
    public static String streamCodeGeneration(String moduleCode, String ruleTemplateStr, String tenantId) {
        String orgCode = ORG_CODE_MAP.getOrDefault(tenantId, "");
        log.info("开始生成流水码");
        SysSerialVo sysSerialVo = new SysSerialVo();
        sysSerialVo.setModulecode(String.format("%s_%s", moduleCode, orgCode));
        sysSerialVo.setRuleTemplateStr(String.format("%s-%s", orgCode, ruleTemplateStr));
        String streamCode = sysSerialNumberService.getCodeByTemplate(sysSerialVo);
        log.info("流水码生成成功：{}", streamCode);
        return streamCode;
    }

    /**
     * 流水码生成
     *
     * @param moduleCode      流水码CODE
     * @param ruleTemplateStr 流水码编码规则
     * @param tenantId        租户id
     * @return
     */
    public static String streamCodeGeneration(String moduleCode, String ruleTemplateStr, String resetRule, String tenantId) {

        String orgCode = (moduleCode.contains("_aq") ? AQ_ORG_CODE_MAP : ORG_CODE_MAP).getOrDefault(tenantId, "");
        log.info("开始生成流水码");
        SysSerialVo sysSerialVo = new SysSerialVo();
        sysSerialVo.setModulecode(String.format("%s_%s", moduleCode, orgCode));
        sysSerialVo.setRuleTemplateStr(String.format("%s-%s", orgCode, ruleTemplateStr));
        sysSerialVo.setResetrule(resetRule);
        if (resetRule.isEmpty()) {
            sysSerialVo.setIfautomaticreset("y");
        }
        String streamCode = sysSerialNumberService.getCodeByTemplate(sysSerialVo);
        log.info("流水码生成成功：{}", streamCode);
        return streamCode;
    }

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