package com.reyun.saas.mob.user.task;

import cn.hutool.core.util.RandomUtil;
import com.reyun.saas.common.constants.ConfigEnumType;
import com.reyun.saas.common.util.DingDingSendMsgUtil;
import com.reyun.saas.common.util.RedisUtils;
import com.reyun.saas.mob.user.service.ConfigParamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @desc生成万能密码任务类
 */
@Slf4j
@Component
public class UniversalPwdTask {

    @Value("${spring.profiles.active}")
    private String env;

    @Autowired
    private ConfigParamService configParamServiceImpl;

    @Resource
    private RedisUtils redisUtils;

    @Async
    @Scheduled(cron = "0 0 8 * * ? ")
    public void genUniversalPwd(){
        if(!"pro".equals(env)){//线上生效
            return;
        }

        if (!redisUtils.tryLock("UniversalPwd",10)) {
            log.info("另一台服务正再生成万能密码中.......");
            return;
        }
        String randomString = RandomUtil.randomString(8);
        configParamServiceImpl.updateValueByKey(ConfigEnumType.UNIVERSAL_PWD.getKey(),randomString);
        DingDingSendMsgUtil dingDingSendMsgUtil = new DingDingSendMsgUtil(DingDingSendMsgUtil.TOKEN_PWD_MSG, DingDingSendMsgUtil.KEY_PWD_MSG);
        dingDingSendMsgUtil.sendMsg(randomString);
    }
}
