package third

import (
	"fmt"
	jsoniter "github.com/json-iterator/go"
	mhayaHttp "github.com/mhaya/extend/http"
	"github.com/mhaya/game/game_cluster/internal/data"
	mhayaLogger "github.com/mhaya/logger"
)

type GetIfChannelResp struct {
	//Result struct {
	//	Status string `json:"status"`
	//} `json:"result"`
	Ok     bool                   `json:"ok"`
	Result map[string]interface{} `json:"result"`
}

// 判断是否是VIP
func GetIfPremium(openid int64) int32 {
	ret := data.SdkConfig.Get(2)
	params := map[string]string{}
	url := fmt.Sprintf("%v%v/getChatMember?chat_id=%v&user_id=%v", ret.Params.AppUrl, ret.Params.BotToken, ret.Params.ChatIDName, openid)
	rs, _, err := mhayaHttp.GET(url, params)
	if err != nil {
		mhayaLogger.Warnf("third.GetIfChannel 验证频道失败  url = %v, bottoken = %v, ChatIDName = %v, userID = %v",
			ret.Params.AppUrl, ret.Params.BotToken, ret.Params.ChatIDName, openid,
			err.Error())
		return 0
	}
	var resp GetIfChannelResp
	err = jsoniter.Unmarshal(rs, &resp)
	if err != nil {
		mhayaLogger.Warnf("third.GetIfChannel 验证频道失败  url = %v, bottoken = %v, ChatIDName = %v, userID = %v",
			ret.Params.AppUrl, ret.Params.BotToken, ret.Params.ChatIDName, openid,
			err.Error())
		return 0
	}
	if !resp.Ok {
		mhayaLogger.Warnf("third.GetIfChannel 验证频道失败  url = %v, bottoken = %v, ChatIDName = %v, userID = %v",
			ret.Params.AppUrl, ret.Params.BotToken, ret.Params.ChatIDName, openid,
			resp.Result["description"])
		return 0
	}

	isPremium, ok := resp.Result["is_premium"].(bool)
	if !ok {
		mhayaLogger.Warnf("Warning: 'is_premium' field not found in member info")
		return 0
	}
	if isPremium {
		return 1
	}
	return 0
}

// 判断用户是否是成员
func GetIfChannel(openid int64) int32 {
	ret := data.SdkConfig.Get(2)
	url := fmt.Sprintf("%v%v/getChatMember?chat_id=%v&user_id=%v", ret.Params.AppUrl, ret.Params.BotToken, ret.Params.ChatIDName, openid)
	mhayaLogger.Infof("getChatMember url = %v", url)
	rs, _, err := mhayaHttp.GET(url, nil)
	if err != nil {
		mhayaLogger.Warnf("third.GetIfChannel 验证频道失败  url = %v, bottoken = %v, ChatIDName = %v, userID = %v",
			ret.Params.AppUrl, ret.Params.BotToken, ret.Params.ChatIDName, openid,
			err.Error())
		return 0
	}
	var resp GetIfChannelResp
	err = jsoniter.Unmarshal(rs, &resp)
	if err != nil {
		mhayaLogger.Warnf("third.GetIfChannel 验证频道失败  url = %v, bottoken = %v, ChatIDName = %v, userID = %v",
			ret.Params.AppUrl, ret.Params.BotToken, ret.Params.ChatIDName, openid,
			err.Error())
		return 0
	}
	ok := resp.Ok
	if !ok {
		mhayaLogger.Warnf("Warning: 'member' field not found in member info")
		return 0
	}
	if ok {
		isPremium, ok := resp.Result["status"].(string)
		if !ok {
			return 0
		}
		if isPremium == "member" {
			return 1
		}
	}
	return 0
}
