package com.gitee.sop.admin.service.sys;

import com.gitee.sop.admin.common.enums.ConfigKeyEnum;
import com.gitee.sop.admin.common.util.PasswordUtil;
import com.gitee.sop.admin.dao.entity.SysUser;
import com.gitee.sop.admin.dao.mapper.UpgradeMapper;
import com.gitee.sop.admin.service.sys.login.enums.RegTypeEnum;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;


/**
 * @author 六如
 */
@Service
public class UpgradeService {

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private UpgradeMapper upgradeMapper;

    @PostConstruct
    public void init() {
        this.initJwtSecret();
        this.insertAdmin();
    }

    private void initJwtSecret() {
        String configKey = ConfigKeyEnum.JWT_SECRET.getKey();
        String value = sysConfigService.getRawValue(configKey);
        if (StringUtils.isBlank(value)) {
            value = PasswordUtil.getRandomSimplePassword(30);
            sysConfigService.setConfig(configKey, value);
        }
    }


    public void insertAdmin() {
        SysUser userInfo = sysUserService.getByUsername("admin");
        if (userInfo != null) {
            return;
        }
        String username = "admin";
        String tpl = "INSERT INTO `sys_user` (`id`, `username`, `password`, `nickname`, `reg_type`) VALUES \n" +
                "\t(%s, '%s','%s','%s','%s');";
        // 初始密码
        String defPassword = "123456";
        defPassword = DigestUtils.sha256Hex(defPassword);
        String encodedPassword = BCrypt.hashpw(defPassword, BCrypt.gensalt());
        Long userId = 1L;
        String sql = String.format(tpl, userId, username, encodedPassword, username, RegTypeEnum.BACKEND.getValue());
        runSql(sql);
    }

    protected void runSql(String sql) {
        upgradeMapper.runSql(sql);
    }

}
