package com.yifu.cloud.plus.v1.yifu.auth.util.weixin.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yifu.cloud.plus.v1.yifu.auth.util.AbstractLoginService;
import com.yifu.cloud.plus.v1.yifu.auth.util.LoginResult;
import com.yifu.cloud.plus.v1.yifu.auth.util.weixin.WeixinLoginConstants;
import com.yifu.cloud.plus.v1.yifu.auth.util.weixin.WeixinLoignProperties;
import com.yifu.cloud.plus.v1.yifu.auth.util.weixin.model.WeixinAccessToken;
import com.yifu.cloud.plus.v1.yifu.auth.util.weixin.model.WeixinError;
import com.yifu.cloud.plus.v1.yifu.auth.util.weixin.model.WeixinUserInfo;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 微信登录服务
 */
@Service
public class WeixinLoginService extends AbstractLoginService<WeixinLoignProperties> {

	private static final Logger logger = LoggerFactory.getLogger(WeixinLoginService.class);

	public LoginResult getAccessToken(String code) {
		StringBuilder uri = new StringBuilder();
		uri.append(WeixinLoginConstants.HOST_API + WeixinLoginConstants.ACCESS_TOKEN + "?appid=");
		uri.append(properties.getAppid());
		uri.append("&secret=").append(properties.getAppsecret());
		uri.append("&code=" + code).append("&grant_type=authorization_code");
		try {
			String url = uri.toString();
			String result = restTemplate.getForObject(url, String.class);
			JSONObject json = JSONUtil.parseObj(result);
			if(json.getStr("access_token") != null){
				WeixinAccessToken accessToken = new WeixinAccessToken();
				accessToken.setAccess_token(json.getStr("access_token"));
				accessToken.setOpenid(json.getStr("open_id"));
				accessToken.setExpires_in(json.getLong("expires_in"));
				accessToken.setRefresh_token(json.getStr("refresh_token"));
				accessToken.setScope(json.getStr("scope"));
				return accessToken;
			}else{
				WeixinError error = new WeixinError();
				error.setErrcode(json.getStr("errcode"));
				error.setErrmsg(json.getStr("errmsg"));
				return error;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	public LoginResult getAccessToken(String code,String appid ,String secret) {
		StringBuilder uri = new StringBuilder();
		uri.append(WeixinLoginConstants.HOST_API + WeixinLoginConstants.ACCESS_TOKEN + "?appid=");
		if (Common.isNotNull(appid) && Common.isNotNull(secret)){
			uri.append(appid);
			uri.append("&secret=").append(secret);
		}else {
			uri.append(properties.getAppid());
			uri.append("&secret=").append(properties.getAppsecret());
		}
		uri.append("&code=" + code).append("&grant_type=authorization_code");
		try {
			String url = uri.toString();
			String result = restTemplate.getForObject(url, String.class);
			JSONObject json = JSONUtil.parseObj(result);
			if(json.getStr("access_token") != null){
				WeixinAccessToken accessToken = new WeixinAccessToken();
				accessToken.setAccess_token(json.getStr("access_token"));
				accessToken.setOpenid(json.getStr("open_id"));
				accessToken.setExpires_in(json.getLong("expires_in"));
				accessToken.setRefresh_token(json.getStr("refresh_token"));
				accessToken.setScope(json.getStr("scope"));
				return accessToken;
			}else{
				WeixinError error = new WeixinError();
				error.setErrcode(json.getStr("errcode"));
				error.setErrmsg(json.getStr("errmsg"));
				return error;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	public LoginResult getWxUserInfo(WeixinAccessToken accessToken) {
		StringBuilder uri = new StringBuilder();
		uri.append(WeixinLoginConstants.HOST_API + WeixinLoginConstants.USER_INFO + "?access_token=");
		uri.append(accessToken.getAccess_token());
		uri.append("&openid=" + accessToken.getOpenid());
		uri.append("&lang=zh_CN");
		try {
			String result = restTemplate.getForObject(uri.toString(), String.class);
			WeixinUserInfo userInfo = JSONUtil.toBean(result, WeixinUserInfo.class);
			if(userInfo != null && null != userInfo.getOpenid()){
				return userInfo;
			}else{
				WeixinError error = JSONUtil.toBean(result, WeixinError.class);
				return error;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	@Override
	public String loadAuthPage(String state) {
		return null;
	}
}
