package com.xy.third.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.dev33.satoken.stp.StpUtil;
import com.xy.collections.map.JHashMap;
import com.xy.dto.ThirdLoginDto;
import com.xy.dto.WxMaDto;
import com.xy.service.ThirdLoginService;
import com.xy.third.config.ThirdLoginConfig;
import com.xy.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;

import static com.xy.utils.Beans.copy;

@Service
@AllArgsConstructor
@Api(tags = "第三方登录")
public class ThirdLoginServiceImpl implements ThirdLoginService {

    private ThirdLoginConfig thirdLoginConfig;

    @Override
    @ApiOperation("登录")
    public R<String> login(ThirdLoginDto thirdLoginDto) {
        StpUtil.login(thirdLoginDto.getLoginId());
        return R.ok(StpUtil.getTokenValue());
    }

    @Override
    @ApiOperation("获取用户信息-微信小程序")
    public R<WxMaDto.Vo> getUserInfoWxMa(@RequestBody @Validated WxMaDto.GetUserInfo getUserInfo) {
        ThirdLoginConfig.Wx wx = thirdLoginConfig.getWx();
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(wx.getAppid());
        config.setSecret(wx.getSecret());
        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setMultiConfigs(new JHashMap<String, WxMaConfig>().set("config", config));
        try {
            WxMaUserService userService = wxMaService.getUserService();
            //获取session
            WxMaJscode2SessionResult session = userService.getSessionInfo(getUserInfo.getCode());
            String sessionKey = session.getSessionKey();
            //获取用户信息
            WxMaUserInfo userInfo = userService.getUserInfo(sessionKey, getUserInfo.getEncryptedData(), getUserInfo.getIv());
            //获取手机信息
            WxMaPhoneNumberInfo phoneNoInfo = userService.getPhoneNoInfo(sessionKey, getUserInfo.getEncryptedData(), getUserInfo.getIv());
            //封装返回值
            WxMaDto.Vo vo = copy(WxMaDto.Vo.class, userInfo)
                    .setOpenId(session.getOpenid())
                    .setTel(phoneNoInfo.getPhoneNumber());
            return R.ok(vo);
        } catch (Exception e) {
            return R.fail("code无效");
        } finally {
            WxMaConfigHolder.remove();
        }
    }
}
