package ink.wgink.service.user.init;

import ink.wgink.interfaces.init.IInitBaseUser;
import ink.wgink.pojo.dtos.user.UserDTO;
import ink.wgink.service.user.dao.IUserDao;
import ink.wgink.util.date.DateUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: InitUser
 * @Description: 创建用户
 * @Author: wanggeng
 * @Date: 2021/6/15 4:30 下午
 * @Version: 1.0
 */
@Component
public class InitUser implements IInitBaseUser {

    private static final Logger LOG = LoggerFactory.getLogger(InitUser.class);
    private IUserDao userDao;
    private PasswordEncoder passwordEncoder;

    public InitUser(IUserDao userDao, PasswordEncoder passwordEncoder) {
        this.userDao = userDao;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public void init() {
        LOG.debug("检查 admin 是否存在");
        Map<String, Object> params = new HashMap<>(2);
        params.put("userUsername", "admin");
        UserDTO userDTO = userDao.get(params);
        if (userDTO == null) {
            LOG.debug("admin 不存在，新增");
            String currentDate = DateUtil.getTime();
            params.put("userId", "1");
            params.put("userPassword", passwordEncoder.encode(DigestUtils.md5Hex(DigestUtils.md5Hex(DigestUtils.md5Hex("aaa111!!!")))));
            params.put("userName", "超级管理员");
            params.put("userType", 1);
            params.put("userState", 0);
            params.put("gmtCreate", currentDate);
            params.put("creator", "1");
            params.put("gmtModified", currentDate);
            params.put("modifier", "1");
            params.put("isDelete", 0);
            userDao.save(params);
        }
    }
}
