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

import cn.com.qmth.stmms.ms.core.domain.enums.BuiltInAccountEnum;
import cn.com.qmth.stmms.ms.core.domain.user.MarkUser;
import cn.com.qmth.stmms.ms.core.domain.user.Role;
import cn.com.qmth.stmms.ms.core.repository.MarkUserRepo;
import cn.com.qmth.stmms.ms.core.vo.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class BultInAccountUtil {

    @Autowired
    MarkUserRepo markUserRepo;

    public void createAccout() {
        List<MarkUser> userList = new ArrayList<>();
        List<Map> mapList = BuiltInAccountEnum.listAccounts();
        if (mapList.size() > 0) {
            for (Map map : mapList) {
                //采集账号
                if (Objects.equals(BuiltInAccountEnum.SCAN.name(), map.get("type").toString())) {
                    for (int i = 1; i <= 10; i++) {
                        String loginName = map.get("code").toString().toLowerCase() + lpad(2, i);
                        MarkUser markUser = markUserRepo.findByLoginName(loginName);
                        if (markUser != null) {
                            continue;
                        }
                        //默认密码123456
                        //随机密码randomPassword()
                        String password = "123456";
                        markUser = new MarkUser(loginName, password, 0L, Subject.SC, loginName, Role.findByName((String) map.get("name")), null);
                        //默认为禁用
                        markUser.setEnabled(false);
                        userList.add(markUser);
                    }
                } else {
                    String loginName = map.get("code").toString().toLowerCase();
                    MarkUser markUser = markUserRepo.findByLoginName(loginName.toLowerCase());
                    if (markUser != null) {
                        continue;
                    }
                    markUser = new MarkUser(loginName, "123456", 0L, Subject.SC, loginName, Role.findByName((String) map.get("name")), null);
                    userList.add(markUser);
                }
            }
            markUserRepo.save(userList);
        }
    }

    private String randomPassword(){
        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;
    }

    /**
     * 补齐不足长度
     *
     * @param length 长度
     * @param number 数字
     * @return
     */
    private static String lpad(int length, int number) {
        String f = "%0" + length + "d";
        return String.format(f, number);
    }
}
