package com.org.hktshop.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.org.hktshop.Interface.admin.WechatAuthService;
import com.org.hktshop.base.BaseException;
import com.org.hktshop.constant.CommonConstant;
import com.org.hktshop.entity.vo.WechatAuthVo;
import com.org.hktshop.entity.vo.WechatUserVo;
import com.org.hktshop.properties.WXAuthProperties;
import com.org.hktshop.utils.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Service
public class WechatAuthServiceImpl implements WechatAuthService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WXAuthProperties wXAuthProperties;
    //请求此地址即跳转到二维码登录界面
    private static final String AUTHORIZATION_URL = "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect";
    // 获取用户 openid 和access——toke 的 URL
    private static final String ACCESSTOKE_OPENID_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    private static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";

    private static final String CALLBACK_URL = "https://www.hotking.com/wxRegister"; //回调域名

    /****
     * 請求用戶登錄二維碼路徑
     * @return
     */
    @Override
    public String getWechatAuthorizationUrl() {
        //第一步：引导用户进入授权页面同意授权，获取code
        String encodeurl = "";
        try {
            encodeurl = URLEncoder.encode(CALLBACK_URL, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //授权页面地址
        String url = String.format(AUTHORIZATION_URL, wXAuthProperties.getAppid(), encodeurl, wXAuthProperties.getScope(), System.currentTimeMillis());
        return url;
    }
    /****
     * 請求用戶詳細信息
     * @param wechatAuthVo
     * @return
     */
    @Override
    public WechatUserVo getWechatUser(WechatAuthVo wechatAuthVo) {
        String infoUrl = String.format(USER_INFO_URL, wechatAuthVo.getAccessToken(), wechatAuthVo.getOpenId());
        String jsonStr = HttpUtil.get(infoUrl);
        JSONObject userInfo = JSON.parseObject(jsonStr);
        if(userInfo.getString("errcode")!=null){
            throw new BaseException(userInfo.getString("errmsg"));
        }
        WechatUserVo wechatUserVo = JSON.toJavaObject(userInfo, WechatUserVo.class);
        return wechatUserVo;
    }
    /****
     * 請求用戶登錄 openid
     * @param code
     * @return
     */
    @Override
    public WechatAuthVo getWechatAuthInfo(String code) {
        logger.info("code = {}", code);
        String url = String.format(ACCESSTOKE_OPENID_URL, wXAuthProperties.getAppid(), wXAuthProperties.getSecret(), code);
        String jsonStr = HttpUtil.get(url);
        JSONObject userInfo = JSON.parseObject(jsonStr);
        logger.info("userInfo = {}", userInfo.toString());
        if(userInfo.getString("errcode")!=null){
            throw new BaseException(userInfo.getString("errmsg"));
        }
        String openId = userInfo.getString(CommonConstant.OPEN_ID);
        String accessToken = userInfo.getString(CommonConstant.ACCESS_TOKEN_WECHAT);
        WechatAuthVo auth = new WechatAuthVo();
        auth.setAccessToken(accessToken);
        auth.setOpenId(openId);
        return auth;
    }

}
