package com.qmth.jkserver.core;

import com.qmth.jkserver.common.MD5;
import com.qmth.jkserver.constant.SystemConstant;
import com.qmth.jkserver.core.exception.JkServerException;
import com.qmth.jkserver.enums.UserRole;
import com.qmth.jkserver.model.User;
import com.qmth.jkserver.service.UserService;
import com.qmth.jkserver.util.Base64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private UserService userService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        User user = userService.findByUserName("super");
        if (user == null) {
            user = new User();
            user.setId(SystemConstant.getDbUuid());
            user.setCreateTime(System.currentTimeMillis());
            user.setUserName("super");
            user.setPassword(Base64Util.encode("qmth87863577".getBytes(StandardCharsets.UTF_8)));
            user.setRealName("超级管理员");
            user.setRole(UserRole.SUPER_ADMIN);
            user.setSchoolId(-1L);
            try {
                userService.saveOrUpdate(user);
            } catch (Exception e) {
                throw new JkServerException("初始化超级管理员用户失败");
            }
        }
        System.out.println("...SUPER ADMIN INIT SUCCESSFULLEY!...");
    }

}
