package clubmgr

import (
	"World/club"
	"World/common"
	"World/conf"
	"World/db"
	"World/pb"
	pmgr "World/playermgr"
	"World/roommgr"
	"common/logger"
	_ "encoding/json"
	_ "io/ioutil"
	"time"
)

const (
	DaysSeconds               = (60 * 60 * 24)
	goodsid_recharge_clubfund = 17
)

var (
	club_tablename      = "dtb_club"
	bAlreadyCheck  bool = false
)

func Init() {
	logger.Info("start init mysql")
	err := db.InitMysql()
	if err != nil {
		logger.Notic("error init mysql error :%v", err)
		return
	}
	logger.Info("init mysql success!!")

	roommgr.Init()

	t := time.Tick(5 * 60 * time.Second)

	go func() {
		for now := range t {
			if now.Hour() == 23 && !bAlreadyCheck {
				doCheck()
			}

			if now.Hour() == 1 {
				bAlreadyCheck = false
			}
		}
	}()
}

func doCheck() {
	bAlreadyCheck = true

	//	if ClubIds, err := db.GetAllClubs(); err == nil {
	//		for _, clubId := range ClubIds {
	//			if expired, err := db.IsClubLevelExpired(int32(clubId)); expired && err == nil {
	//				db.DoSetClubLevelInfo(int32(clubId), common.Enum_Club_Level_one, 0, 0)
	//			}
	//		}
	//	}

}

func DoGRPC() {
	logger.Info("***DoGRPC***")
	roommgr.DoCommunicate()
}

func IsClubNumFull(uid uint32) (bool, error) {
	full, err := db.IsClubNumFull(uid)

	return full, err
}

func IsCreatedAllianceNumFull(clubId uint32) (bool, error) {
	full, err := db.IsCreatedAllianceNumFull(clubId)
	return full, err
}

func IsJoinedAllianceNumFull(clubId uint32) (bool, error) {
	full, err := db.IsJoinedAllianceNumFull(clubId)
	return full, err
}

func IsClubNameExist(clubName string) (bool, error) {
	result, err := db.IsClubNameExist(clubName)

	return result, err
}

func IsAllianceNameExist(allianceName string) (bool, error) {
	result, err := db.IsAllianceNameExist(allianceName)

	return result, err
}

func IsMyself(cid uint32, clubName string) (bool, error) {
	result, err := db.IsMyself(cid, clubName)

	return result, err
}

func IsAdminNumFull(clubId uint32) (bool, error) {
	full, err := db.IsAdminNumFull(clubId)
	return full, err
}

func AddClub(cd *club.ClubParams) (uint32, error) {
	clubId, err := db.AddClub(cd)
	return clubId, err
}

func AddAlliance(pa *club.AllianceParams) (uint32, error) {
	allianceId, err := db.AddAlliance(pa)
	return allianceId, err
}

func AddClubMember(clubId uint32, userId uint32) error {
	return db.AddClubMember(clubId, userId)
}

func AddAllianceMember(allianceId uint32, CreaterId uint32, clubId uint32) error {
	return db.AddAllianceMember(allianceId, CreaterId, clubId)
}

func ModifyClubNum(createrId uint32, num int) error {
	return db.ModifyClubNum(createrId, num)
}

func DealApplyMsg(cid uint32, uid uint32, msg string) {
	if hasMsg, err := db.HasOldApplyMsg(cid, uid); err == nil && hasMsg {
		db.ModifyApplyAddTime(cid, uid)
	} else {
		db.AddApplyMsg(cid, uid, msg)
	}

}

func DealAllianceApplyMsg(AllianceId uint32, clubId uint32, msg string) {
	if hasMsg, err := db.HasOldAllianceApplyMsg(AllianceId, clubId); err == nil && hasMsg {
		db.ModifyAllianceApplyAddTime(AllianceId, clubId)
	} else {
		db.AddAllianceApplyMsg(AllianceId, clubId, msg)
	}
}

func AddApplyMsg(cid uint32, uid uint32, msg string) {
	db.AddApplyMsg(cid, uid, msg)
}

func AddtPending(noti pb.NoticeJoinClubToMember) {
	db.AddPending(noti)
}

func AddAlliancePending(noti pb.NoticeJoinAllianceToMember, clubAdminId uint32) {
	db.AddAlliancePending(noti, clubAdminId)
}

func AddLeaveallianceNotice(noti pb.NoticeLeaveAlliance, clubAdminId uint32) {
	db.AddLeaveallianceNotice(noti, clubAdminId)
}

func AddPendingMsg(noti *pb.NoticeSendMsg, memberId uint32) {
	db.AddPendingMsg(noti, memberId)
}

func AddMsgContent(noti *pb.NoticeSendMsg) {
	db.AddMsgContent(noti)
}

func IsClubExsit(clubid uint32) (bool, error) {
	cb, ok := db.IsExist(clubid, club_tablename)
	return cb, ok
}

func IsAllianceExsit(AllianceId uint32) (bool, error) {
	cb, ok := db.IsExist(AllianceId, "dtb_alliance")
	return cb, ok
}

func IsPlayerInClub(cid uint32, uid uint32) (bool, error) {
	ok, err := db.IsPlayerInClub(cid, uid)
	return ok, err
}

func IsClubInAlliance(AllianceId uint32, cludId uint32) (bool, error) {
	ok, err := db.IsClubInAlliance(AllianceId, cludId)
	return ok, err
}

func IsPlayerAlreadyApply(cid uint32, uid uint32) (bool, error) {
	ok, err := db.IsPlayerAlreadyApply(cid, uid)
	return ok, err
}

func IsClubAlreadyApply(allianceId uint32, clubId uint32) (bool, error) {
	ok, err := db.IsNewAllianceApplicant(allianceId, clubId)
	return ok, err
}

func IsClubTotalPlayerFull(cid uint32) bool {
	ok, _ := db.IsClubTotalPlayerFull(cid)
	return ok
}

func IsAllianceFull(AllianceId uint32) bool {
	ok, _ := db.IsAllianceFull(AllianceId)
	return ok
}

func IsClubPlayerEmpty(cid uint32) bool {
	ok, _ := db.IsClubPlayerEmpty(cid)
	return ok
}

func IsAllianceMemberEmpty(AllianceId uint32) bool {
	ok, _ := db.IsAllianceMemberEmpty(AllianceId)
	return ok
}

func IsTargetCreater(tid uint32, ClubId uint32) (bool, error) {
	IsCreater, err := db.IsTargetCreater(tid, ClubId)
	return IsCreater, err
}

func IsTargetAllianceCreater(tid uint32, AllianceId uint32) bool {
	ok, _ := db.IsTargetAllianceCreater(tid, AllianceId)
	return ok
}

func IsAllianceCreater(tid uint32) bool {
	ok, _ := db.IsAllianceCreater(tid)
	return ok
}

func GetClubType(ClubId uint32) (int, error) {
	Type, err := db.GetClubType(ClubId)
	return Type, err
}

func HasPrivilege(ClubId uint32, ClubUid uint32) bool /*, error*/ {
	ok := db.HasPrivilege(ClubId, ClubUid)
	return ok
}

func HasAlliancePrivilege(AllianceId uint32, ClubId uint32) bool /*, error*/ {
	ok := db.HasAlliancePrivilege(AllianceId, ClubId)
	return ok
}

func IsUserInClub(clubUid uint32, clubid uint32) (bool, error) {
	ok, err := db.IsUserInClub(clubUid, clubid)
	return ok, err
}

func IsOtherAdminOperated(clubUid uint32, clubid uint32) bool {
	ok, _ := db.IsOtherAdminOperated(clubUid, clubid)
	return ok
}

func IsOtherAllianceAdminOperated(clubUid uint32, clubid uint32) bool {
	ok, _ := db.IsOtherAllianceAdminOperated(clubUid, clubid)
	return ok
}

func IsJackpotExist(cid uint32, blindLevel int) (bool, error) {
	ok, err := db.IsJackpotExist(cid, blindLevel)
	return ok, err
}

//func ModifyClubAdminNum(clubId int32, num int) error {
//	return db.ModifyClubAdminNum(clubId, num)
//}

func ModifyClubCurrentAdminNum(clubId uint32, num int) error {
	return db.ModifyClubCurrentAdminNum(clubId, num)
}

func ModifyClubCurrentMemberNum(clubId uint32, num int) error {
	return db.ModifyClubCurrentMemberNum(clubId, num)
}

func AddClubAdmin(targetId uint32, clubid uint32) error {
	return db.UptoAdmin(targetId, clubid)
}

func DoModifyClubMember(targetId uint32, clubid uint32, actionType int32) common.ErrorType {
	switch actionType {
	case common.Enum_Up_To_Club_Admin: //0为提升管理员
		if db.UptoAdmin(targetId, clubid) == nil {
			db.ModifyClubCurrentAdminNum(clubid, 1)
		}
		break

	case common.Enum_Down_To_Club_Normal: //1为降为普通成员
		if db.DowntoNormal(targetId, clubid) == nil {
			db.ModifyClubCurrentAdminNum(clubid, -1)
		}
		break
	case common.Enum_Remove_Club_Member: //2为删除该成员
		if db.IsAdmin(clubid, targetId) {
			//从管理员表中删除
			db.DowntoNormal(targetId, clubid)
			db.ModifyClubCurrentAdminNum(clubid, -1)
		}
		ModifyClubCurrentMemberNum(clubid, -1)
		db.RemoveMember(targetId, clubid)

		break
	default:
		return common.Error_Invalid_Action_Enum
	}

	return common.Error_OK
}

func DoRemoveAllianceMember(targetId uint32, AllianceId uint32) common.ErrorType {
	err := db.RemoveAllianceMember(targetId, AllianceId)
	if err == nil {
		return common.Error_OK
	}

	return common.Error_OperateDB_Failed
}

func DoRemoveAlliancesNormalMember(targetId uint32) common.ErrorType {
	err := db.RemoveAlliancesNormalMember(targetId)
	if err == nil {
		return common.Error_OK
	}

	return common.Error_OperateDB_Failed
}

func DoModifyClubInfo(param *pb.ModifyClubInfoParams) error {
	err := db.ModifyClubInfo(param)

	return err
}

func GetCurrentClubLevel(clubId uint32) (int32, error) {
	price, err := db.GetCurrentClubLevel(clubId)
	return price, err
}

func GetClubLevelExpireTime(clubId uint32) (uint32, error) {
	expireTime, err := db.GetClubLevelExpireTime(clubId)
	return uint32(expireTime), err
}

func GetRemainTime(clubId uint32) (int, error) {
	var span int
	expireTime, err := db.GetExpireTime(clubId)
	if err == nil && expireTime > 0 {
		now := int(time.Now().Unix())
		if expireTime >= now {
			span = expireTime - now
		}
	}
	return span, err
}

func seconds2Days(seconds int) int {
	return (seconds / DaysSeconds)
}

func IsUserGoldEnough(uid uint32, amount int64) bool {
	ok := db.IsUserGoldEnough(uid, amount)
	return ok
}

func DoGrantClubFundNew(clubId uint32, targetId uint32, amount int64, operatorId uint32) common.ErrorType {
	//扣除操作者金币
	var curGoldNum int64
	var err error
	var goldAfterAdd int64
	if curGoldNum, err = db.GetUserGoldNum(operatorId); err == nil {
		if curGoldNum < amount {
			logger.Warn("DoGrantClubFundNew operator gold not enough uid:%v,amount:%v", operatorId, amount)
			return common.Error_Club_Fund_Not_Enough
		}
		_, goldAfter, err_1 := db.OperateRequesterGold(operatorId, amount, db.Subtract)
		if err_1 != nil {
			logger.Warn("DoGrantClubFundNew Subtract gold failed uid:%v,err:%v", operatorId, err_1)
			return common.Error_Club_Other
		}

		player, err := pmgr.GetPlayerFromMap(operatorId)
		if err == nil {
			common.SendGoldNumNotify(player, 0, uint32(operatorId), int64(goldAfter), int64(-amount))
		} else {
			logger.Notic("Player not found uid:%v", operatorId)
		}
	}
	// 发放俱乐部基金
	goldAfterAdd, err = db.AddTargetFund(clubId, targetId, amount)
	if err == nil {
		//发放俱乐部基金成功，入库记录
		db.RecordAddTargetFund(clubId, targetId, amount, operatorId)

		player, err := pmgr.GetPlayerFromMap(targetId)
		if err == nil && player != nil {
			common.SendGoldNumNotify(player, 0, uint32(targetId), int64(goldAfterAdd), int64(amount))
		} else {
			// todo  存入数据库
			//logger.Notic("Player not found uid:%v", targetId)
			db.RecordClubGrantFundNotify(clubId, targetId, amount, operatorId, goldAfterAdd)
		}
	} else {
		return common.Error_DataBase_Failed
	}

	return common.Error_OK
}

func DoGrantClubFund(clubId uint32, targetId uint32, amount int32) common.ErrorType {
	// 扣除俱乐部基金
	/*db.OperateClubFund(clubId, amount, db.Subtract)

	// 发放俱乐部基金
	err := db.AddTargetFund(clubId, targetId, amount)
	if err == nil {
		//发放俱乐部基金成功，入库记录
		db.RecordAddTargetFund(clubId, targetId, amount)
	} else {
		return common.Error_DataBase_Failed
	}*/

	return common.Error_OK
}

func DoInjectJackpotAmount(uid uint32, clubId uint32, blindLevel int32, amount int64) (int64, error) {
	var cur_amount int64 = 0
	var err error = nil
	var goldAfter int64 = 0
	// 扣除俱乐部基金
	_, goldAfter, err = db.OperateRequesterGold(uid, amount, db.Subtract)
	logger.Info("DoInjectJackpotAmount err:%v clubId:%v amount:%v Subtract", err, clubId, amount)
	if err == nil {
		// 向jackpot注入基金
		isExist, err := db.IsJackpotExist(clubId, int(blindLevel))
		if err == nil {
			if !isExist {
				blind := conf.GetBlindByIndex(uint32(blindLevel))
				err = db.AddJackpot(clubId, int(blindLevel), int(blind.Scale), int(blind.DrawinAmout))
			}
		}
		cur_amount, err = db.AddJackpotAmount(clubId, int(blindLevel), amount)
		logger.Info("AddJackpotAmount err:%v clubId:%v blindLevel:%V amount:%v Subtract", err, clubId, blindLevel, amount)

		player, err := pmgr.GetPlayerFromMap(uid)
		if err == nil {
			common.SendGoldNumNotify(player, 0, uint32(uid), int64(goldAfter), int64(-amount))
		} else {
			logger.Notic("Player not found uid:%v", uid)
		}
	}

	return cur_amount, err
}

func DoNonCreaterLeaveClub(clubId uint32, clubDid uint32) common.ErrorType {
	if db.IsAdmin(clubId, clubDid) {
		//从管理员表中删除
		db.DowntoNormal(clubDid, clubId)
		db.ModifyClubCurrentAdminNum(clubId, -1)
	}
	ModifyClubCurrentMemberNum(clubId, -1)

	//从成员表中删除
	db.RemoveMember(clubDid, clubId)
	return common.Error_OK
}

func DoNonCreaterLeaveAlliance(AllianceId uint32, clubId uint32) common.ErrorType {
	//从联盟成员表中删除
	db.RemoveAllianceMember(clubId, AllianceId)
	return common.Error_OK
}

func DoCreaterLeaveClub(clubId uint32, clubDid uint32) error {
	// 从dtb_club中删除
	var err error
	if err = db.DeleteFromClub(clubId); err == nil {
		err = db.RemoveMember(clubDid, clubId)
	}

	return err
}

func DoCreaterLeaveAlliance(AllianceId uint32, clubId uint32) common.ErrorType {
	// 从dtb_alliance中删除
	if err := db.DeleteFromAlliance(AllianceId); err != nil {
		return common.Error_OperateDB_Failed
	}

	if err := db.RemoveAllianceMember(clubId, AllianceId); err != nil {
		return common.Error_OperateDB_Failed
	}

	return common.Error_OK
}

func GetAttendedClubs(uid uint32) ([]uint32, error) {
	clubIds, err := db.GetAttendedClubs(uid)
	return clubIds, err
}

func GetCreatedClubs(uid uint32) ([]uint32, error) {
	clubIds, err := db.GetCreatedClubs(uid)
	if err != nil {
		return clubIds, err
	}

	return clubIds, err
}

func GetAdminClubs(uid uint32) ([]uint32, error) {
	clubIds, err := db.GetAdminClubs(uid)
	if err != nil {
		return clubIds, err
	}

	return clubIds, err
}

func GetAdminAllianceIds(clubIds []uint32) ([]uint32, error) {
	var aids []uint32
	var err error
	for i := 0; i < len(clubIds); i++ {
		AllianceIds, e := db.GetAdminAllianceIds(clubIds[i])
		if e == nil {
			for j := 0; j < len(AllianceIds); j++ {
				aids = append(aids, AllianceIds[j])
			}
		} else {
			err = e
			break
		}
	}

	return aids, err
}

func GetAllianceIds(clubId uint32) ([]uint32, error) {
	aids, err := db.GetAllianceIds(clubId)
	return aids, err
}

func GetAdminAlliances(clubId uint32) ([]uint32, error) {
	clubIds, err := db.GetAdminClubs(clubId)
	return clubIds, err
}

func GetPlublicClubs(uid uint32) ([]uint32, error) {
	clubIds, err := db.GetPlublicClubs(uid)
	return clubIds, err
}

func GetClubSnapshotList(clubIds []uint32, PlayerID uint32) ([]*pb.ClubSnapshotListParams, error) {
	var list []*pb.ClubSnapshotListParams
	var clubinfo *pb.ClubSnapshotListParams

	var err error = nil
	for i := 0; i < len(clubIds); i++ {
		clubinfo, err = db.GetClubSnapshotInfo(clubIds[i], PlayerID)
		if (err == nil) && (clubinfo != nil) {
			list = append(list, clubinfo)
		}
	}

	return list, err
}

func GetAllianceList(AllianceIds []uint32, clubId uint32) ([]*pb.AllianceListParams, error) {
	var list []*pb.AllianceListParams
	var AllianceInfo *pb.AllianceListParams

	var err error = nil
	for i := 0; i < len(AllianceIds); i++ {
		AllianceInfo, err = db.GetAllianceInfo4List(AllianceIds[i], clubId)
		if (err == nil) && (AllianceInfo != nil) {
			list = append(list, AllianceInfo)
		}
	}

	return list, err
}

func GetClubSnapshotInfo(clubId uint32, playId uint32) (*pb.ClubSnapshotListParams, error) {
	clubinfo, err := db.GetClubSnapshotInfo(clubId, playId)

	return clubinfo, err
}

func GetAllianceInfo(AllianceId uint32) (*pb.NoticeSearchAlliance, error) {
	info, err := db.GetAllianceInfo(AllianceId)

	return info, err
}

//func GetSubCreaterInfo(clubId int) (*pb.NoticeClubCreaterInfo, error) {
//	var clubinfo *pb.NoticeClubCreaterInfo = nil
//	var err error = nil
//	var createrId int = 0
//	if createrId, err = db.GetClubCreaterId(clubId); err == nil && createrId > 0 {
//		clubinfo, err = db.GetSubCreaterInfo(createrId)
//	}

//	return clubinfo, err
//}

//本应该用上面的函数，应客户端未能更新而暂用下面函数
func GetSubCreaterInfo(createrId uint32) (*pb.NoticeClubCreaterInfo, error) {
	clubinfo, err := db.GetSubCreaterInfo(createrId)
	return clubinfo, err
}

func GetApplyInfoList(clubIds []uint32) ([]*pb.JoinClubParams, error) {
	var list []*pb.JoinClubParams
	for i := 0; i < len(clubIds); i++ {
		applyInfos, err := db.GetApplyInfoList(clubIds[i])
		if (err == nil) && (applyInfos != nil) {
			for j, _ := range applyInfos {
				list = append(list, applyInfos[j])
			}
		}
	}

	return list, nil
}

func GetApplyAllianceList(allianceIds []uint32) ([]*pb.RequestJoinAlliance, error) {
	var list []*pb.RequestJoinAlliance
	for i := 0; i < len(allianceIds); i++ {
		applyInfos, err := db.GetApplyAllianceList(allianceIds[i])
		if (err == nil) && (applyInfos != nil) {
			for j, _ := range applyInfos {
				list = append(list, applyInfos[j])
			}
		}
	}

	return list, nil
}

func GetPendingInfoList(uid uint32) ([]*pb.NoticeJoinClubToMember, error) {
	list, err := db.GetPendingInfoList(uid)
	return list, err
}

func GetAlliancePendingInfoList(uid uint32) ([]*pb.NoticeJoinAllianceToMember, error) {
	list, err := db.GetAlliancePendingInfoList(uid)
	return list, err
}

func GetLeaveallianceList(uid uint32) ([]*pb.NoticeLeaveAlliance, error) {
	list, err := db.GetLeaveallianceList(uid)
	return list, err
}

func ModifyApplyCheckTime(clubId uint32, uid uint32) error {
	err := db.ModifyApplyCheckTime(clubId, uid)
	return err
}

func ModifyAllianceApplyCheckTime(allianceId uint32, clubId uint32) error {
	err := db.ModifyAllianceApplyCheckTime(allianceId, clubId)
	return err
}

func DeleteApplyInfo(clubId uint32, uid uint32) error {
	err := db.DeleteApplyInfo(clubId, uid)
	return err
}

func DeleteAllianceApplyInfo(allianceId uint32, clubId uint32) error {
	err := db.DeleteAllianceApplyInfo(allianceId, clubId)
	return err
}

func DeletePendingList(uid uint32, clubId uint32) error {
	err := db.DeletePending(uid, clubId)
	if err != nil {
		return err
	}

	return err
}

func DeleteAlliancePendingList(uid uint32, allianceId uint32) error {
	err := db.DeleteAlliancePendingList(uid, allianceId)
	if err != nil {
		return err
	}

	return err
}

func GetClubMemberSnapshotList(clubId uint32) ([]*pb.ClubMemberSnapshot, error) {
	//	log.Printf("GetClubMemberSnapshotList")
	var notice pb.NoticeClubMemberSnapshotList

	var Type int = 0
	var e error = nil
	if Type, e = GetClubType(clubId); e != nil {
		return nil, e
	}

	//找到俱乐部成员id集合
	ids, err := db.GetClubMemberList(clubId)
	//根据俱乐部id获取成员快照

	ids = common.RemoveDuplicates(ids)

	var snapshot *pb.ClubMemberSnapshot
	for i := 0; i < len(ids); i++ {
		if Type == common.Enum_Club_Public && i >= 9 { //公共俱乐部（新手训练营只传10条记录）
			break
		}
		snapshot, err = db.GetClubMemberSnapshot(ids[i], clubId)
		if err == nil && snapshot != nil {

			player, err := pmgr.GetPlayerFromMap(ids[i])
			if nil == err && player != nil && player.Conn != nil {
				snapshot.IsOnline = true
			} else {
				snapshot.IsOnline = false
			}

			notice.Snapshots = append(notice.Snapshots, snapshot)
		}
	}

	return notice.Snapshots, err
}

func GetClubAdmins(clubId uint32) ([]uint32, error) {
	adminIds, err := db.GetClubAdmins(clubId)
	return adminIds, err
}

func GetUserClubIds(playerId uint32) ([]uint32, error) {
	Ids, err := db.GetUserClubIds(playerId)
	return Ids, err
}

func GetAllianceAdmins(AllianceId uint32) ([]uint32, error) {
	var adminIds []uint32
	allianceCreater, err := db.GetAllianceCreater(AllianceId)
	if err != nil {
		return adminIds, err
	}
	adminIds, _ = db.GetClubAdmins(allianceCreater)
	return adminIds, err
}

func GetSubUserInfo(PlayerId uint32) (*club.SubUserInfo, error) {
	SubUserInfo, err := db.GetSubUserInfo(PlayerId)
	return SubUserInfo, err
}

func GetClubLevelInfo(typeId int32) (*club.ClubLevelInfo, error) {
	Info, err := db.GetClubLevelInfo(int(typeId))
	return Info, err
}

func GetClubName(clubId uint32) (string, error) {
	clubName, _, err := db.GetClubInfo(clubId)
	return clubName, err
}

func GetClubInfo(clubId uint32) (string, uint32, error) {
	clubName, createrId, err := db.GetClubInfo(clubId)
	return clubName, createrId, err
}

func GetClubMemberList(clubId uint32) ([]uint32, error) {
	ids, err := db.GetClubMemberList(clubId)
	return ids, err
}

func GetUserInfo(PlayerId uint32) (*club.UserInfo, error) {
	UserInfo, err := db.GetUserInfo(PlayerId)

	return UserInfo, err
}

func GetAllianceName(AllianceId uint32) (string, error) {
	name, err := db.GetAllianceName(AllianceId)

	return name, err
}

func GetAllianceCreaterId(AllianceId uint32) (uint32, error) {
	CreaterId, err := db.GetAllianceCreaterId(AllianceId)
	return CreaterId, err
}

func SetJackpot(clubId uint32, blindLevel int32, profitScale int64, drawinAmout int64) error {
	isExist, err := db.IsJackpotExist(clubId, int(blindLevel))
	if err == nil {
		if !isExist {
			err = db.AddJackpot(clubId, int(blindLevel), int(profitScale), int(drawinAmout))
		} else {
			//设置（update）
			err = db.UpdateJackpot(clubId, int(blindLevel), int(profitScale), int(drawinAmout))
		}
	}

	return err
}

func GetJackpotList(clubId uint32) ([]*pb.Jackpot, error) {
	list, err := db.GetJackpotList(clubId)
	if err != nil {
		return nil, err
	}

	return list, err
}

func GetJackpotAwardList(clubId uint32, blindLevel int) ([]*pb.AwardInfo, error) {
	list, err := db.GetJackpotAwardList(clubId, blindLevel)
	return list, err
}

func GetLuckyJackpotAward(clubId uint32, blindLevel int) (*pb.AwardInfo, error) {
	Info, err := db.GetLuckyJackpotAward(clubId, blindLevel)
	return Info, err
}

func GetAwardTypeList(clubId uint32) ([]*pb.AwardType, error) {
	list, err := db.GetAwardTypeList(clubId)
	if err != nil {
		return nil, err
	}

	return list, err
}

func GetJackpotInfoList(clubId uint32) ([]*pb.JackpotInfo, error) {
	list, err := db.GetJackpotInfoList(clubId)
	if err != nil {
		return nil, err
	}

	return list, err
}

func GetJackpotInfo(clubId uint32, blindLevel int) (*pb.JackpotInfo, error) {
	jackpotInfo, err := db.GetJackpotInfo(clubId, blindLevel)
	return jackpotInfo, err
}

func SetJackpotAwardType(clubId uint32, handLevel int32, percent int32) error {
	isExist, err := db.IsAwardtypeExist(clubId, handLevel)
	if err == nil {
		if !isExist {
			err = db.AddJackpotAwardtype(clubId, int(handLevel), int(percent))
		} else {
			err = db.UpdateJackpotAwardtype(clubId, int(handLevel), int(percent))
		}
	}

	return err
}

func GetAward2ClubPercent(clubId uint32) (int, bool, error) {
	percent, bExist, err := db.GetAward2ClubPercent(clubId)
	return percent, bExist, err
}

func SetAward2ClubPercent(clubId uint32, percent int32) error {
	isExist, err := db.IsAward2ClubPercentExist(clubId)
	if err == nil {
		if !isExist {
			err = db.AddAward2ClubPercent(clubId, int(percent))
		} else {
			err = db.UpdateAward2ClubPercent(clubId, int(percent))
		}
	}

	return err
}

func GetJackpotClubInfo(clubId uint32) (string, string, string, error) {
	ClubName, ClubAvatar, ClubArea, err := db.GetJackpotClubInfo(clubId)

	return ClubName, ClubAvatar, ClubArea, err
}

func GetClubOpenedJackpots(clubId uint32) ([]int, error) {
	JackpotIds, err := db.GetClubOpenedJackpots(clubId)

	return JackpotIds, err
}

func GetClubOpenedLevels(clubId uint32) ([]int, error) {
	levels, err := db.GetClubOpenedJackpots(clubId)

	return levels, err
}

func DeleteSpecialBlindlevels(clubId uint32, blindLevel int) error {
	err := db.DeleteSpecialBlindlevels(clubId, blindLevel)

	return err
}

func GetJackpotAmount(clubId uint32, blindLevel int) (int64, error) {
	amount, err := db.GetJackpotAmount(clubId, blindLevel)

	return amount, err
}

func DeleteLeaveallianceNotice(clubAdminId uint32) error {
	err := db.DeleteLeaveallianceNotice(clubAdminId)
	return err
}

func PlayerHasAlliancePrivilege(uid uint32, allianceId uint32) bool {
	var bExist bool = false
	if allianceCreater, err := db.GetAllianceCreater(allianceId); err == nil {
		var adminIds []uint32
		if adminIds, err = db.GetClubAdmins(allianceCreater); err == nil {
			if common.IsIdExist(adminIds, uid) {
				bExist = true
			}
		}
	}

	return bExist
}

func ClearAllianceCurBuyinLimit(allianceId uint32, clubId uint32) bool {
	var OK bool = false
	if clubId == 0 { //clubid为-1，清除联盟下所有俱乐部的额度上限
		//获取该联盟所有成员
		if clubIds, _, err := db.GetAllianceMemberList(allianceId); err == nil {
			for _, cId := range clubIds {
				if err = db.ModifyAllianceCurBuyinLimit(allianceId, cId, 0); err == nil {
					OK = true
				} else {
					OK = false
				}
			}
		}
	} else {
		if e := db.ModifyAllianceCurBuyinLimit(allianceId, clubId, 0); e == nil {
			OK = true
		} else {
			OK = false
		}
	}
	return OK
}

func SetAllianceMaxBuyinLimit(allianceId uint32, clubId uint32, amount int) bool {
	var OK bool = false
	if e := db.ModifyAllianceMaxBuyinLimit(allianceId, clubId, amount); e == nil {
		OK = true
	} else {
		OK = false
	}
	return OK
}

func SetAllianceControlBuyin(allianceId uint32, clubId uint32, ControlBuyin bool) bool {
	var OK bool = false
	if e := db.ModifyAllianceControlBuyin(allianceId, clubId, ControlBuyin); e == nil {
		OK = true
	} else {
		OK = false
	}
	return OK
}

func InsertClubInvitationCode(clubId uint32, code string) error {
	err := db.InsertClubInvitationCode(clubId, code)
	return err
}

func SetAllianceInvitationCode(allianceId uint32, code string) error {
	return db.SetAllianceInvitationCode(allianceId, code)
}
