package gameServerMgr

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"Framework/goroutineMgr"
	. "Framework/managecenterModel"
	"goutil/logUtil"
	"goutil/webUtil"
)

const URL_SUFFIX string = "/API/UserWhiteList.ashx"

var (
	mUserWhiteListMap = make(map[int32]map[string]*WhiteList, 0)
	mHashValue        string
)

// 获取白名单
func GetWhiteListFromManageCenterServer() error {
	//定义参数
	requestParamMap := make(map[string]string, 0)
	requestParamMap["HashValue"] = mHashValue

	//构造url
	url := fmt.Sprintf("%s/%s", mManageCenterServerAPIUrl, URL_SUFFIX)

	//请求url,请求头
	header := webUtil.GetFormHeader()
	transport := webUtil.NewTransport()
	transport.DisableKeepAlives = true
	transport = webUtil.GetTimeoutTransport(transport, 30)

	statusCode, returnBytes, err := webUtil.PostMapData(url, requestParamMap, header, transport)
	//statusCode, returnBytes, err := webUtil.PostMapData(url, requestParamMap, header, nil)
	if err != nil {
		logUtil.ErrorLog(fmt.Sprintf("获取白名单列表出错，url:%s,错误信息为:%s", url, err))
		return err
	}
	if statusCode != 200 {
		logUtil.ErrorLog(fmt.Sprintf("获取白名单列表出错，url:%s,错误码为:%d", url, statusCode))
		return err
	}
	// 解析返回值
	returnObj := new(ReturnObject)
	if err = json.Unmarshal(returnBytes, &returnObj); err != nil {
		logUtil.ErrorLog(fmt.Sprintf("获取白名单列表出错，反序列化返回值出错，错误信息为：%s, str:%s", err, string(returnBytes)))
		return err
	}

	// 判断返回状态是否为成功
	if returnObj.Code != 0 {
		// 数据没有变化，所以没有获取到新的数据，不能算错误。
		if returnObj.Code == 47 || returnObj.Message == "DataNotChanged" {
			return nil
		} else {
			msg := fmt.Sprintf("获取白名单列表出错，返回状态：%d，信息为：%s", returnObj.Code, returnObj.Message)
			logUtil.ErrorLog(msg)
			return errors.New(msg)
		}
	}

	// 解析Data
	var tmpWhiteList []*WhiteList
	if data, ok := returnObj.Data.(string); !ok {
		msg := "获取白名单列表出错，返回的数据不是string类型"
		logUtil.ErrorLog(msg)
		return errors.New(msg)
	} else {
		if err = json.Unmarshal([]byte(data), &tmpWhiteList); err != nil {
			logUtil.ErrorLog(fmt.Sprintf("获取白名单列表出错，反序列化数据出错，错误信息为：%s", err))
			return err
		}
	}

	tmpWhiteListMap := make(map[int32]map[string]*WhiteList, 64)
	for _, item := range tmpWhiteList {
		if _, exist := tmpWhiteListMap[item.PartnerId]; !exist {
			tmpWhiteListMap[item.PartnerId] = make(map[string]*WhiteList, 8)
		}

		tmpWhiteListMap[item.PartnerId][item.UserId] = item
	}

	// 赋值给最终的whiteListMap
	mUserWhiteListMap = tmpWhiteListMap
	mHashValue = returnObj.HashValue

	return nil
}

// 判断用户是否在白名单里面
// partnerId: 合作商ID
// userId: userId
func IsInWhiteList(partnerId int32, userId string) bool {
	subWhiteListMap, exist := mUserWhiteListMap[partnerId]
	if !exist {
		return false
	}

	_, exist = subWhiteListMap[userId]
	return exist
}

// 定时刷新白名单
func StartRefreshWhiteListTread() {
	// 定时刷新数据
	go func() {
		goroutineName := "gameServerMgr.StartRefreshWhiteListTread"
		goroutineMgr.Monitor(goroutineName)
		defer goroutineMgr.ReleaseMonitor(goroutineName)

		for {
			// 每30秒刷新一次
			time.Sleep(30 * time.Second)

			// 刷新白名单
			GetWhiteListFromManageCenterServer()
		}
	}()
}
