package wxuser

import (
	configYaml "common/configsYaml"
	"common/resultStatus"
	"encoding/json"
	"fmt"
	"goutil/logUtilPlus"
	"goutil/webUtil"
)

const (
	Url = "https://api.weixin.qq.com/sns/"
)

type WechatsdkService struct {
}

// 通过code来换取assesstoken
func (w *WechatsdkService) GetAccessToken(code string, severId int32) (resultStatus.ResultStatus, int64) {
	weburl := fmt.Sprintf("%s%s", Url, "oauth2/access_token") //"https://api.weixin.qq.com/sns/oauth2/access_token"
	data := make(map[string]string)
	data["appid"] = configYaml.GetWxconfig().AppId
	data["secret"] = configYaml.GetWxconfig().AppSecret
	data["code"] = code
	data["grant_type"] = "authorization_code"
	status, resp, err := webUtil.GetWebData2(weburl, data, nil, nil)
	if status != 200 || err != nil {
		return resultStatus.RequestError, 0
	}

	if len(resp) == 0 {
		logUtilPlus.ErrorLog("The result is empty, but we expect not empty")
		return resultStatus.EmptyResp, 0
	}
	logUtilPlus.ErrorLog("resp=%s", string(resp))
	tokens := &WechatTokens{}
	if err := json.Unmarshal(resp, tokens); err != nil {
		logUtilPlus.ErrorLog("Unmarshal is error, err:%s", err)
		return resultStatus.UnmarshalError, 0
	}
	if tokens.Errcode != 0 || tokens.Errmsg != "" {
		logUtilPlus.ErrorLog("errcode:%d, msg:%s,", tokens.Errcode, tokens.Errmsg)
		return resultStatus.RequestError, 0
	}
	Uid := CreatUid(tokens.OpenId, 1)
	go func() {
		if userInfo, _ := GetUserByOpenId(tokens.OpenId); userInfo == nil {
			w.GetUserInfo(tokens.AccessToken, tokens.OpenId)
		}
	}()
	go RecordLoginIn(Uid, severId)
	return resultStatus.Success, Uid
}

// 换取用户信息
func (w *WechatsdkService) GetUserInfo(accessToken, openid string) {
	weburl := fmt.Sprintf("%s%s", Url, "userinfo") //"https://api.weixin.qq.com/sns/userinfo"
	data := make(map[string]string)
	data["appid"] = configYaml.GetWxconfig().AppId
	data["access_token"] = accessToken
	data["openid"] = openid
	status, resp, err := webUtil.GetWebData2(weburl, data, nil, nil)
	if status != 200 || err != nil {
		logUtilPlus.ErrorLog("Wrongstatus. status:%d, err:%s", status, err)
	}
	if len(resp) == 0 {
		logUtilPlus.ErrorLog("The result is empty, but we expect not empty")
	}
	var userInfo *WxUserInfo
	if err := json.Unmarshal(resp, userInfo); err != nil {
		logUtilPlus.ErrorLog("Unmarshal is error, err:%s", err)
		return
	}
	AddUser(userInfo)
}

var wechatsdkservice *WechatsdkService

func GetWechatsdkService() *WechatsdkService {
	return wechatsdkservice
}
