package util

import (
	"app.yhyue.com/moapp/jybase/redis"
	"fmt"
	IC "jyBXCore/rpc/init"
	"sync"
)

var (
	PLock *ParticipateLock
)

type ParticipateLock struct {
	sync.Mutex
	UserLock map[string]*sync.Mutex
}

func NewParticipateLock() *ParticipateLock {
	return &ParticipateLock{
		UserLock: make(map[string]*sync.Mutex),
	}
}

func GetParticipateLock(str string) *sync.Mutex {
	PLock.Lock()
	if PLock.UserLock[str] == nil {
		PLock.UserLock[str] = &sync.Mutex{}
	}
	PLock.Unlock()
	return PLock.UserLock[str]
}

// 参标权限判断  权益请求check userId  应传 mongo userId
func IsAllowedParticipate(appId, userId string, newUserId, accountId, entAccountId, entId, entUserId, positionId, positionType int64) (b bool, role int64) {
	powerCheck := IC.Middleground.PowerCheckCenter.Check(appId, userId, newUserId, accountId, entId, positionType, positionId)
	//不是超级订阅 也不是大会员
	if powerCheck.Vip.Status <= 0 && powerCheck.Member.Status <= 0 {
		return
	}
	role = powerCheck.Ent.EntRoleId
	resource := IC.Middleground.ResourceCenter.Haspowers(accountId, entAccountId, entId, entUserId)
	if len(resource.Powers) != 0 {
		for _, r := range resource.Powers {
			//资源中台 cb_zy_code
			if r == IC.C.ResourceCode {
				b = true
				break
			}
		}
	}
	return
}

// 3秒内防止重复提交
func IsAllowedAccess(key string) string {
	redisKey := fmt.Sprintf("participate_isAllowed_%s", key)
	if b, err := redis.Exists("other", redisKey); err != nil && b {
		return "访问频次过快，请稍后再试"
	}
	redis.Put("other", redisKey, key, 3)
	return ""
}
