package com.sf.oauth.service.impl;

import com.sf.common.core.domain.AjaxResult;
import com.sf.common.core.domain.entity.SysUser;
import com.sf.common.enums.UserStatus;
import com.sf.common.utils.SecurityUtils;
import com.sf.common.utils.ip.IpUtils;
import com.sf.framework.web.service.SysLoginService;
import com.sf.oauth.domain.AuthUser;
import com.sf.oauth.exception.AuthException;
import com.sf.oauth.service.IAuthService;
import com.sf.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 功能描述:
 *
 * @author a_kun
 * @date 2024/4/12 10:21
 */
@Slf4j
@Service
public class IAuthServiceImpl implements IAuthService {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService userService;


    @Override
    public String authLogin(AuthUser authUser, HttpSession session) {
        // TODO 应该要登录后绑定一个平台账号，没有平台账号要创建，保存用户的三方来源，及用户的三方唯一标识和绑定的用户
        if (authUser != null) {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(authUser.getUsername());
            if (userService.checkUserNameUnique(sysUser)) {
                // 注册用户后登录
                sysUser.setNickName(authUser.getNickname());
                sysUser.setEmail(authUser.getEmail());
                sysUser.setPhonenumber(authUser.getMobileNumber());
                sysUser.setSex(authUser.getGender().getCode());
                sysUser.setAvatar(authUser.getAvatar());
                sysUser.setPassword(SecurityUtils.encryptPassword("ztzh@sac123"));
                sysUser.setStatus(UserStatus.OK.getCode());
                sysUser.setDelFlag("0");
                sysUser.setLoginIp(IpUtils.getHostIp());
                sysUser.setLoginDate(new Date());
                userService.insertUser(sysUser);
            }
            // 生成令牌
            return loginService.noPwdLogin(authUser.getUsername(), session);
        }
        throw new AuthException("login error");
    }
}
