package com.ruoyi.auth.service;

import com.ruoyi.auth.domain.OauthAccount;
import com.ruoyi.auth.mapper.Oauth2Mapper;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.constant.Constant;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Oauth2Service {
    @Value("${oauth2.client-id}")
    String clientId;

    @Autowired
    private Oauth2Mapper oauth2Mapper;

    public int insertOauth2User(SysUser user) {
        OauthAccount oauthAccount = new OauthAccount();
        oauthAccount.setClientId(clientId);
        oauthAccount.setUsername(user.getUserName());
        oauthAccount.setPassword(user.getPassword());
        oauthAccount.setMobile(user.getPhonenumber());
        oauthAccount.setEmail(user.getEmail());
        oauthAccount.setEnabled(Constant.State_valid);
        return oauth2Mapper.insertOauth2User(oauthAccount);
    }

    public int updateOauth2User(SysUser user) {
        OauthAccount oauthAccount = new OauthAccount();
        oauthAccount.setClientId(clientId);
        oauthAccount.setUsername(user.getUserName());
        if (StringUtils.isNotEmpty(user.getPassword())) {
            oauthAccount.setPassword(user.getPassword());
        }
        oauthAccount.setMobile(user.getPhonenumber());
        oauthAccount.setEmail(user.getEmail());
        if (Constant.DelFlag.equals(user.getDelFlag())) {
            oauthAccount.setEnabled(Constant.State_invalid);
        }
        return oauth2Mapper.updateOauth2User(oauthAccount);
    }
}
