package com.boyue.oauth.wx.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.boyue.auth.common.domain.OauthUser;
import com.boyue.auth.common.service.IOauthUserService;
import com.boyue.common.core.domain.entity.SysUser;
import com.boyue.common.core.domain.model.LoginUser;
import com.boyue.common.exception.ServiceException;
import com.boyue.common.utils.StringUtils;
import com.boyue.framework.web.service.TokenService;
import com.boyue.framework.web.service.UserDetailsServiceImpl;
import com.boyue.oauth.wx.constant.WxMiniAppConstant;
import com.boyue.oauth.wx.service.WxLoginService;
import com.boyue.system.service.ISysUserService;

@Service
public class WxMiniAppLoginServiceImpl implements WxLoginService {
    @Autowired
    private WxMiniAppConstant wxAppConstant;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IOauthUserService oauthUserService;

    @Override
    public String doLogin(String code) {
        String openid = doAuth(
                wxAppConstant.getUrl(),
                wxAppConstant.getAppId(),
                wxAppConstant.getAppSecret(),
                code).getString("openid");
        OauthUser selectOauthUser = oauthUserService.selectOauthUserByUUID(openid);
        if (selectOauthUser == null) {
            return null;
        }
        SysUser sysUser = userService.selectUserById(selectOauthUser.getUserId());
        if (sysUser == null) {
            throw new ServiceException("该微信未绑定用户");
        }
        LoginUser loginUser = (LoginUser) userDetailsServiceImpl.createLoginUser(sysUser);
        return tokenService.createToken(loginUser);
    }

    @Override
    public String doRegister(OauthUser oauthUser) {
        if (StringUtils.isEmpty(oauthUser.getCode())) {
            return "没有凭证";
        }
        if (oauthUser.getUserId() == null) {
            return "请先注册账号";
        }
        JSONObject doAuth = doAuth(
                wxAppConstant.getUrl(),
                wxAppConstant.getAppId(),
                wxAppConstant.getAppSecret(),
                oauthUser.getCode());
        oauthUser.setOpenId(doAuth.getString("openid"));
        oauthUser.setUuid(doAuth.getString("openid"));
        oauthUser.setSource("WXMiniApp");
        oauthUser.setAccessToken(doAuth.getString("sessionKey"));
        oauthUserService.insertOauthUser(oauthUser);
        return "";
    }

}
