package cn.com.qmth.stmms.ms.admin.utils;

import cn.com.qmth.stmms.ms.core.domain.Organization;
import cn.com.qmth.stmms.ms.core.domain.user.MarkUser;
import cn.com.qmth.stmms.ms.core.repository.MarkUserRepo;
import cn.com.qmth.stmms.ms.core.repository.OrganizationRepo;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class RandomUtils {

    @Autowired
    private OrganizationRepo organizationRepo;

    @Autowired
    private MarkUserRepo markUserRepo;

    public String numericPassword() {
        String sources = "0123456789";
        String password = "123456";
        for (int i = 0; i <= 100; i++) {
            Random rand = new Random();
            StringBuffer flag = new StringBuffer();
            for (int j = 0; j < 6; j++) {
                flag.append(sources.charAt(rand.nextInt(10)) + "");
            }
            password = flag.toString();
        }
        return password;
    }


    /**
     * 生成3位a-z随机机构唯一编码
     *
     * @return
     */
    public String organAbbreviation() {
        //3位a-z的字母
        String string = RandomStringUtils.randomAlphabetic(3);

        Organization organization = organizationRepo.findByAbbreviation(string.toUpperCase());
        //已使用，重新生成
        while (organization != null) {
            organAbbreviation();
        }
        return string.toUpperCase();
    }

    /**
     * 生成6位字母+数字组合随机密码（区分大小写）
     *
     * @return
     */
    public String alphanumericPassword() {
        //6位字母+数字混合
        String string = RandomStringUtils.randomAlphanumeric(6);

        MarkUser markUser = markUserRepo.findByPassword(string);
        //已存在，重新生成
        while (markUser != null) {
            alphanumericPassword();
        }
        return string;
    }
}
