package com.sckw.user.service;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sckw.core.utils.AESUtil;
import com.sckw.core.utils.IdWorker;
import com.sckw.user.entity.KwBusinessUser;
import com.sckw.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.Base64;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;

/**
 * @desc:
 * @author: Lt
 * @date: 2024-05-22
 */
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public String generateUserByTenantId(String tenantId) throws Exception {
        KwBusinessUser user = userMapper.selectOneByTenantId(tenantId);
        if (ObjectUtils.isNotNull(user)) {
            throw new Exception("用户已存在");
        } else {
            KwBusinessUser kwBusinessUser = new KwBusinessUser();
            kwBusinessUser.setId(new IdWorker(1L).nextId());
            String username = generateRandomAccount(6,12);
            kwBusinessUser.setName(username);
            kwBusinessUser.setUsername(username);
            //生成盐
            String salt = AESUtil.generateSalt(16);
            kwBusinessUser.setSlat(salt);
            String encryptPwd = AESUtil.encrypt("123456", salt);
            kwBusinessUser.setPassword(encryptPwd);
            kwBusinessUser.setType(0);
            kwBusinessUser.setTenantId(tenantId);
            final int insert = userMapper.insert(kwBusinessUser);
            if (insert > 0) {
                return "创建成功";
            }else {
                return "创建失败";
            }
        }

    }

    /**
     * 生成介于最小长度和最大长度之间的随机账号。
     *
     * @param minLen 最小长度。
     * @param maxLen 最大长度。
     * @return 生成的随机账号。
     */
    public static String generateRandomAccount(int minLen, int maxLen) {
        if (minLen <= 0 || maxLen <= 0 || minLen > maxLen) {
            throw new IllegalArgumentException("Invalid length range");
        }

        // 创建Random对象
        Random random = new Random();
        // 确定账号的长度，随机选择在最小长度和最大长度之间
        int length = random.nextInt(maxLen - minLen + 1) + minLen;
        // 定义可能包含的字符
        String possibleChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        // 使用StringBuilder构建随机账号
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            // 从可能的字符中随机选择一个字符
            sb.append(possibleChars.charAt(random.nextInt(possibleChars.length())));
        }
        return sb.toString();
    }




}
