package com.ruoyi.framework.web.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.WxUser;
import com.ruoyi.common.core.domain.model.LoginWxUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.recovery.service.IWxUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class WxLoginService {
    @Autowired
    private WxTokenService wxTokenService;

    @Autowired
    IWxUserService wxUserService;

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    /**
     * 小程序登录
     *
     * @param code
     * @return
     */
    public String minLogin(String code) {
        //1根据code执行小程序登录获取 openId
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", appid).replace("{1}", secret).replace("{2}", code);
        log.info("微信调用：{}", replaceUrl);
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(replaceUrl));
        if (jsonObject.get("errcode") != null) {
            throw new ServiceException(String.format("获取微信授权信息失败，错误编码：%s，错误信息：%s", String.valueOf(jsonObject.get("errcode")), (String) jsonObject.get("errmsg")));
        }
        //2根据openId判断用户是否存在 不存在自动注册 openId对应数据库表user_name
        WxUser wxUser = wxUserService.selectWxUSerByOpenid(String.valueOf(jsonObject.get("openid")));
        if (wxUser == null) {
            wxUser = new WxUser();
            wxUser.setWxOpenid(String.valueOf(jsonObject.get("openid")));
            wxUser.setUsername(String.valueOf(jsonObject.get("openid")));
            wxUser.setGender(1L);
            wxUser.setStatus(0L);
            wxUserService.insertWxUser(wxUser);
            wxUser = wxUserService.selectWxUSerByOpenid(String.valueOf(jsonObject.get("openid")));
        }
        //3生成token
        LoginWxUser loginWxUser = new LoginWxUser(wxUser.getId(), wxUser);
        recordLoginInfo(loginWxUser.getUserId());
        return wxTokenService.createAppToken(loginWxUser);
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    private void recordLoginInfo(Long userId) {
        WxUser appUser = new WxUser();
        appUser.setId(userId);
        appUser.setLastLoginIp(IpUtils.getIpAddr());
        appUser.setLastLoginTime(DateUtils.getNowDate());
        wxUserService.updateWxUser(appUser);
    }
}
