package com.mcwl.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.mcwl.system.domain.SysUserThirdAccount;
import com.mcwl.system.service.IWXService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * 微信登录 业务处理层
 *
 * @author DaiZibo
 * @date 2024/12/31
 * @apiNote
 */

@Service
public class IWXServiceImpl implements IWXService {

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

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

    @Override
    public SysUserThirdAccount getOpenid(String code) {

        RestTemplate restTemplate = new RestTemplate();
        JSONObject jsonData = null;

        // 构建获取access_token的URL
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                + "appid=" + appId
                + "&secret=" + secret
                + "&code=" + code
                + "&grant_type=authorization_code";

        System.out.println("url: " + url);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);

        System.out.println("responseEntity: " + responseEntity);
        if (responseEntity.getStatusCodeValue() == 200 && responseEntity.getBody() != null) {
            jsonData = JSONObject.parseObject(responseEntity.getBody());
        }

        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?lang=zh_CN"
                + "&access_token=" + jsonData.getString("access_token")
                + "&openid=" + jsonData.getString("openid");

        ResponseEntity<String> responseUserEntity = restTemplate.getForEntity(userInfoUrl, String.class);
        if (responseUserEntity.getStatusCodeValue() == 200 && responseUserEntity.getBody() != null) {
            JSONObject jsonUserData = JSONObject.parseObject(new String(responseUserEntity.getBody().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
            System.out.println("jsonUserData: " + jsonUserData);
            SysUserThirdAccount sysUserThirdAccount = new SysUserThirdAccount();
            sysUserThirdAccount.setOpenid(jsonUserData.getString("openid"));
            sysUserThirdAccount.setOpenName(jsonUserData.getString("nickname"));
            return sysUserThirdAccount;
        }

        return null;
    }
}
