package managecenterMgr

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

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

var (
	whiteListMap  = make(map[int32]map[string]*WhiteList, 64)
	whiteListHash string
)

// 重新加载白名单
func reloadWhiteList(isInit bool) error {
	//logUtil.DebugLog("开始刷新白名单列表")

	url := getManageCenterUrl("/API/UserWhiteList.ashx")

	// 定义请求参数
	postDict := make(map[string]string)
	postDict["HashValue"] = whiteListHash

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

	statusCode, returnBytes, err := webUtil.PostMapData(url, postDict, header, transport)
	//statusCode, returnBytes, err := webUtil.PostMapData(url, postDict, 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" {
			//如果本地集合为空，且数据又没变化时，重新初始化一下本地hash值
			if len(whiteListMap) == 0 {
				whiteListHash = ""
			}
			return nil
		} else {
			msg := fmt.Sprintf("获取白名单列表出错，返回状态：%d，信息为：%s", returnObj.Code, returnObj.Message)
			logUtil.ErrorLog(msg)
			return errors.New(msg)
		}
	}

	// 解析Data
	tmpWhiteList := make([]*WhiteList, 0, 128)
	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
		}
	}

	//logUtil.DebugLog(fmt.Sprintf("刷新白名单信息结束，白名单数量:%d", len(tmpWhiteList)))

	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
	whiteListMap = tmpWhiteListMap
	whiteListHash = returnObj.HashValue

	//通知变更
	mcDataChangeCallBack(managecenterModel.UserWhiteListData, isInit)

	return nil
}

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

	_, exist = subWhiteListMap[userId]
	return exist
}
