package game

import (
	"time"

	"World/club"
	"World/clubmgr"
	"World/roommgr"

	"World/common"
	"World/conf"
	"World/db"

	pb "World/pb"
	pmgr "World/playermgr"
	"net"

	"encoding/json"

	"World/utils"
	stat "common/statistic"
	"strings"

	"World/mail"
	"World/resume"
	"common/logger"
)

func BuildClubParams(uid uint32, params pb.ClubParams) *club.ClubParams {
	pa := new(club.ClubParams)

	pa.Creater_id = int(uid)
	pa.ClubName = params.ClubName
	pa.ClubArea = params.ClubArea
	pa.ClubIcon = params.ClubIcon
	pa.ClubImage = params.ClubIcon

	pa.ClubLevel = common.Enum_Club_Level_five
	pa.CurrentMembers = 1

	Info, err := db.GetClubLevelInfo(common.Enum_Club_Level_five)
	if (err == nil) && (Info != nil) {
		pa.MemberMax = Info.MembersMax
		pa.AdminsMax = Info.AdminsMax

		pa.CreatedAllianceMax = Info.CreatedAllianceMax
		pa.JoinedAllianceMax = Info.JoinedAllianceMax
	}

	return pa
}

func BuildAllianceParams(req *pb.RequestCreateAlliance) *club.AllianceParams {
	pa := new(club.AllianceParams)

	pa.Name = req.AllianceName
	pa.ClubId = int(req.ClubId)

	pa.MemberMax = conf.GetAllianceClubNumMax()

	return pa
}

func CreateClubHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestCreateClub) {
	logger.Info("****CreateClubHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil
	var er error = nil

	for {
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//		full, err := clubmgr.IsClubNumFull(header.PlayerID)
		//		if err != nil {
		//			err_num = common.Error_OperateDB_Failed
		//			logger.Notic("IsClubNumFull uid:%v failed:%v", header.PlayerID, err_num)
		//			break
		//		}

		//		if full {
		//			err_num = common.Error_Too_Many_Club_To_CreateClub
		//			logger.Notic("IsClubNumFull uid:%v failed:%v", header.PlayerID, err_num)
		//			break
		//		}

		name_exist, err := clubmgr.IsClubNameExist(req.Param.ClubName)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("IsClubNameExist uid:%v failed:%v ClubName:%v", header.PlayerID, err_num, req.Param.ClubName)
			break
		}

		if name_exist {
			err_num = common.Error_Club_Name_Already_Exist
			logger.Notic("IsClubNameExist uid:%v failed:%v ClubName:%v", header.PlayerID, err_num, req.Param.ClubName)
			break
		}

		//建立俱乐部数据结构
		clubInfo := BuildClubParams(header.PlayerID, *req.Param)

		clubId, err := clubmgr.AddClub(clubInfo) //插入俱乐部时已设置current_members值
		if err != nil {
			err_num = common.Error_CreateClub_failure
			logger.Notic("AddClub uid:%v failed:%v clubInfo:%+v", header.PlayerID, err_num, clubInfo)
			break
		}

		err = clubmgr.AddClubMember(clubId, header.PlayerID)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("AddClubMember uid:%v failed:%v clubId:%v", header.PlayerID, err_num, clubId)
			break
		}

		err = clubmgr.ModifyClubNum(header.PlayerID, 1)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("ModifyClubNum uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		err = clubmgr.AddClubAdmin(header.PlayerID, clubId)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("AddClubAdmin uid:%v failed:%v clubId:%v", header.PlayerID, err_num, clubId)
			break
		}

		err = clubmgr.ModifyClubCurrentAdminNum(clubId, 1)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("ModifyClubAdminNum uid:%v failed:%v clubId:%v", header.PlayerID, err_num, clubId)
			break
		}

		err = clubmgr.InsertClubInvitationCode(clubId, common.IdToCode(clubId))
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("InsertClubInvitationCode uid:%v failed:%v clubId:%v", header.PlayerID, err_num, clubId)
		}

		break
	}

	logger.Info("handle create club result uid:%v err_num:%v", header.PlayerID, err_num)
	//返回响应
	var resp pb.ResponseCreateClub
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_CreateClub_Response, &resp)
}

func LeaveClubHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestLeaveClub) {
	logger.Info("****LeaveClubHandler header :%+v request:%+v", header, req)
	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//普通成员和管理员请求退出可以直接退出
		if IsCreater, err := clubmgr.IsTargetCreater(req.Param.ClubDid, req.Param.ClubId); err == nil {
			if !IsCreater {
				clubmgr.DoNonCreaterLeaveClub(req.Param.ClubId, req.Param.ClubDid)
				break
			}

		} else {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("IsTargetCreater uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//俱乐部是否为空
		if !clubmgr.IsClubPlayerEmpty(req.Param.ClubId) {
			err_num = common.Error_Club_Member_Not_Empty
			logger.Notic("IsClubPlayerEmpty uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		games := roommgr.GetClubGameInfo(req.Param.ClubId)
		var bExist bool = false
		if len(games) > 0 {
			for _, game := range games {
				if game.ClubId == req.Param.ClubId {
					bExist = true
					break
				}
			}
			if bExist {
				err_num = common.Error_DestroyClub_while_BoardIsRunning
				logger.Notic("GetClubGameInfo uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.Param.ClubId)
				break
			}
		}

		if isCreater := clubmgr.IsAllianceCreater(req.Param.ClubId); isCreater {
			err_num = common.Error_IsAlliance_Creater
			logger.Notic("IsAllianceCreater uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.Param.ClubId)
			break
		}

		//俱乐部基金为空则退出俱乐部
		if err := clubmgr.DoCreaterLeaveClub(req.Param.ClubId, req.Param.ClubDid); err == nil {
			clubmgr.ModifyClubNum(req.Param.ClubDid, -1)
		} else {
			err_num = common.Error_OperateDB_Failed
			logger.Info("LeaveClubHandler result uid:%v err_num:%v", header.PlayerID, err_num)
			break
		}

		clubmgr.DoRemoveAlliancesNormalMember(req.Param.ClubId)

		break

	}

	logger.Info("LeaveClubHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseLeaveClub
	resp.Error = int32(err_num)
	if resp.Error == common.Error_OK {
		clubmgr.ModifyClubCurrentMemberNum(req.Param.ClubId, -1)
	}

	SendMessage(player, conn, header, pb.MSGID_MsgID_LeaveClub_Response, &resp)
}

func FilterIDs(firs []uint32, secs []uint32) []uint32 {
	for _, sec := range secs {
		if !common.IsIdExist(firs, sec) {
			firs = append(firs, sec)
		}
	}

	return firs
}

func ClubSnapshotListHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestClubSnapshotList) {
	clublist_begin_ts := time.Now().Unix()
	logger.Debug("create_begin_ts header:%+v uid:%v ts:%v", header, header.PlayerID, clublist_begin_ts)

	logger.Info("****ClubSnapshotListHandler :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var clubIds []uint32
	var publicIds []uint32
	var err error = nil
	var list []*pb.ClubSnapshotListParams
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("ClubSnapshotListHandler-get player uid: %v failed: %v", header.PlayerID, err_num)
			break
		}
		logger.Debug("GetPlayerFromMap uid:%v ts:%v", header.PlayerID, time.Now().Unix()-clublist_begin_ts)

		clubIds, err = clubmgr.GetAttendedClubs(header.PlayerID)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("GetAttendedClubs player uid: %v failed: %v", header.PlayerID, err_num)
			break
		}
		logger.Debug("GetAttendedClubs uid:%v ts:%v", header.PlayerID, time.Now().Unix()-clublist_begin_ts)

		clubIds = common.RemoveDuplicates(clubIds)
		logger.Info("ClubSnapshotListHandler uid:%v clubIds:%v", header.PlayerID, clubIds)
		logger.Debug("RemoveDuplicates uid:%v ts:%v", header.PlayerID, time.Now().Unix()-clublist_begin_ts)
		//暂且屏蔽公共俱乐部功能。2018-1-26（胡）
		//		publicIds, err = clubmgr.GetPlublicClubs(int(header.PlayerID))
		//		if err != nil {
		//			err_num = common.Error_OperateDB_Failed
		//			logger.Notic("GetPlublicClubs player uid: %v failed: %v", header.PlayerID, err_num)
		//			break
		//		}
		//		logger.Debug("GetPlublicClubs uid:%v ts:%v", header.PlayerID, time.Now().Unix()-clublist_begin_ts)

		logger.Info("ClubSnapshotListHandler uid:%v publicIds:%v", header.PlayerID, publicIds)

		clubIds = FilterIDs(clubIds, publicIds)

		logger.Debug("FilterIDs uid:%v ts:%v", header.PlayerID, time.Now().Unix()-clublist_begin_ts)
		logger.Info("ClubSnapshotListHandler uid:%v clubIds:%v", header.PlayerID, clubIds)

		// 获取俱乐部快照列表
		list, err = clubmgr.GetClubSnapshotList(clubIds, header.PlayerID)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("GetClubSnapshotList player uid: %v failed: %v", header.PlayerID, err_num)
			break
		}
		logger.Debug("GetClubSnapshotList uid:%v ts:%v", header.PlayerID, time.Now().Unix()-clublist_begin_ts)

		logger.Info("ClubSnapshotListHandler uid:%v list:%v", header.PlayerID, list)

		break

	}

	logger.Info("ClubSnapshotListHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseClubSnapshotList
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_ClubSnapshotList_Response, &resp)

	if err_num == common.Error_OK {
		var noti pb.NoticeClubSnapshotList
		noti.List = append(noti.List, list...)
		SendMessage(player, conn, header, pb.MSGID_MsgID_ClubSnapshotList_Notice, &noti)
		logger.Info("ClubSnapshotListHandler uid:%v err_num:%v list:%v", header.PlayerID, err_num, noti.List)
		logger.Debug("send MSGID_MsgID_ClubSnapshotList_Notice uid:%v ts:%v", header.PlayerID, time.Now().Unix()-clublist_begin_ts)
	}
}

func SearchClubInfoHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestSearchClubInfo) {
	logger.Info("****SearchClubInfoHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var err error = nil
	var info *pb.ClubSnapshotListParams
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		// 获取俱乐部信息
		if info, err = clubmgr.GetClubSnapshotInfo(req.ClubId, 0); err != nil || (info == nil) {
			err_num = common.Error_ClubID_Not_Found
			logger.Notic("GetClubSnapshotInfo player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		break
	}

	logger.Info("SearchClubInfoHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseSearchClubInfo
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_SearchClubInfo_Response, &resp)

	if err_num == common.Error_OK {
		var noti pb.NoticeSearchClubInfo
		noti.Snapshots = info
		SendMessage(player, conn, header, pb.MSGID_MsgID_SearchClubInfo_Notice, &noti)
		logger.Info("SearchClubInfoHandler result uid:%v err_num:%v noti:%+v", header.PlayerID, err_num, noti)
	}
}

func ClubCreaterInfoHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestClubCreaterInfo) {
	logger.Info("****ClubCreaterInfoHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType
	err_num = common.Error_OK
	var err error = nil
	var info *pb.NoticeClubCreaterInfo
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		if info, err = clubmgr.GetSubCreaterInfo(req.ClubId); err != nil || info == nil {
			err_num = common.Error_Club_Other
			logger.Notic("GetSubCreaterInfo uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		break
	}

	logger.Info("ClubCreaterInfoHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseClubCreaterInfo
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_ClubCreaterInfo_Response, &resp)

	if err_num == common.Error_OK {
		SendMessage(player, conn, header, pb.MSGID_MsgID_ClubCreaterInfo_Notice, info)
		logger.Notic("SendMessage MSGID_MsgID_ClubCreaterInfo_Notice uid:%v", header.PlayerID)
	}
}

func ClubCurrentBoardHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestClubCurrentBoard) {
	logger.Info("****ClubCurrentBoardHandler header :%+v request:%+v", header, req)
	board_begin_ts := time.Now().Unix()
	logger.Debug("ClubCurrentBoardHandler begin uid:%v ts:%v", header.PlayerID, board_begin_ts)

	var err_num common.ErrorType = common.Error_OK
	var clubIds []uint32
	var err error = nil
	var list []*pb.ClubGameSnapshot
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Info("ClubCurrentBoardHandler player uid: %v failed: %v", header.PlayerID, err_num)
			break
		}
		logger.Debug("GetPlayerFromMap uid:%v ts:%v", header.PlayerID, time.Now().Unix()-board_begin_ts)

		//请求者所有参与的俱乐部
		if clubIds, err = clubmgr.GetAttendedClubs(header.PlayerID); err != nil {
			err_num = common.Error_Club_Other
			logger.Info("ClubCurrentBoardHandler-GetAttendedClubs uid:%v failed: %v", header.PlayerID, err)
			break
		}
		logger.Debug("GetAttendedClubs uid:%v ts:%v", header.PlayerID, time.Now().Unix()-board_begin_ts)

		clubIds = common.RemoveDuplicates(clubIds)
		logger.Info("AttendedClubs clubIds:%v uid:%v seq:%v", clubIds, header.PlayerID, player.ConnSeq)
		logger.Debug("RemoveDuplicates uid:%v ts:%v", header.PlayerID, time.Now().Unix()-board_begin_ts)

		//1.获取联盟相关的俱乐部id集合
		var cIds []uint32
		userClubIds, _ := clubmgr.GetUserClubIds(header.PlayerID)
		for _, vv := range roommgr.GetAllianceClubIds().Items() {
			allianceCids, _ := vv.(*roommgr.AllianceClubIds)
			for i := 0; i < len(allianceCids.Ids); i++ {
				for j := 0; j < len(userClubIds); j++ {
					if allianceCids.Ids[i] == userClubIds[j] {
						if !common.IsIdExist(cIds, userClubIds[j]) {
							cIds = append(cIds, userClubIds[j])
						}
					}
				}
			}
		}
		logger.Debug("GetUserClubIds uid:%v ts:%v", header.PlayerID, time.Now().Unix()-board_begin_ts)

		logger.Info("3 allianceCids-cIds:%v  uid:%v seq:%v", cIds, header.PlayerID, player.ConnSeq)

		clubIds = append(clubIds, cIds...)

		clubIds = common.RemoveDuplicates(clubIds)
		logger.Debug("RemoveDuplicates uid:%v ts:%v", header.PlayerID, time.Now().Unix()-board_begin_ts)

		logger.Info("4 allianceCids-clubIds:%v  uid:%v seq:%v", clubIds, header.PlayerID, player.ConnSeq)

		//俱乐部相关牌局
		list = roommgr.GetClubBoard(clubIds)

		logger.Debug("GetClubBoard uid:%v ts:%v", header.PlayerID, time.Now().Unix()-board_begin_ts)
		logger.Info("ClubCurrentBoardHandler-list:%v", list)

		//用户参加过的非俱乐部创建的牌
		notClubList := roommgr.GetNotClubBoard(int(header.PlayerID))
		for _, info := range notClubList {
			list = append(list, info)
		}
		logger.Debug("GetNotClubBoard uid:%v ts:%v", header.PlayerID, time.Now().Unix()-board_begin_ts)
		logger.Info("6 allianceCids-clubIds:%v  uid:%v seq:%v", clubIds, header.PlayerID, player.ConnSeq)

		break

	}

	logger.Info("ClubCurrentBoardHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseClubCurrentBoard
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_ClubCurrentBoard_Response, &resp)

	if err_num == common.Error_OK {
		var noti pb.NoticeClubCurrentBoard
		noti.List = append(noti.List, list...)
		SendMessage(player, conn, header, pb.MSGID_MsgID_ClubCurrentBoard_Notice, &noti)
		logger.Debug("send MSGID_MsgID_ClubCurrentBoard_Notice uid:%v ts:%v", header.PlayerID, time.Now().Unix()-board_begin_ts)
		logger.Info("7 MSGID_MsgID_ClubCurrentBoard_Notice uid:%v  noti.List:%v", player.UID, noti.List)
	}
}

func ClubMemberSnapshotListHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestClubMemberSnapshotList) {
	logger.Info("****ClubMemberSnapshotListHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK

	var noti pb.NoticeClubMemberSnapshotList
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//请求者不是俱乐部创建者且不在俱乐部中
		var isCreater bool = false
		if isCreater, er = clubmgr.IsTargetCreater(req.Param.ClubUid, req.Param.ClubId); er != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("IsTargetCreater uid:%v failed:%v ClubUid:%v ClubId:%v", header.PlayerID, err_num, req.Param.ClubUid, req.Param.ClubId)
			break
		}

		var isInClub bool = false
		if isInClub, er = clubmgr.IsUserInClub(req.Param.ClubUid, req.Param.ClubId); er != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("IsTargetCreater uid:%v failed:%v ClubUid:%v ClubId:%v", header.PlayerID, err_num, req.Param.ClubUid, req.Param.ClubId)
			break
		}

		if !isCreater && !isInClub {
			err_num = common.Error_Player_Not_In_Club
			logger.Notic("IsTargetCreater uid:%v failed:%v ClubUid:%v ClubId:%v", header.PlayerID, err_num, req.Param.ClubUid, req.Param.ClubId)
			break
		}

		// 获取俱乐部成员快照列表
		noti.Snapshots, _ = clubmgr.GetClubMemberSnapshotList(req.Param.ClubId)

		break
	}

	logger.Info("ClubMemberSnapshotListHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseClubMemberSnapshotList
	resp.Error = int32(err_num)
	SendMessage(player, conn, header, pb.MSGID_MsgID_ClubMemberSnapshotList_Response, &resp)

	if err_num == common.Error_OK {
		common.SendNoti(player, header.RoomID, header.PlayerID, pb.MSGID_MsgID_ClubMemberSnapshotList_Notice, &noti)
		logger.Info("ClubMemberSnapshotListHandler result uid:%v noti:%+v", header.PlayerID, noti)
	}
}

func ModifyClubMemberHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestModifyClubMember) {
	logger.Info("****ModifyClubMemberHandler header :%+v request:%+v", header, req)
	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("GetPlayerFromMap get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		if req.Param == nil {
			err_num = common.Error_Club_Other
			logger.Notic("req.Param is nil player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//被操作者是俱乐部的创建者则退出
		if IsCreater, err := clubmgr.IsTargetCreater(req.Param.TargetId, req.Param.ClubId); err == nil {
			if IsCreater {
				err_num = common.Error_Club_Other
				logger.Notic("IsTargetCreater TargetId:%v ClubId:%v err_num:%v uid:%v", req.Param.TargetId, req.Param.ClubId, err_num, header.PlayerID)
				break
			}
		} else {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("IsTargetCreater TargetId:%v ClubId:%v err_num:%v uid:%v", req.Param.TargetId, req.Param.ClubId, err_num, header.PlayerID)
			break
		}

		//请求者不是管理员也不是创建者则退出
		if !clubmgr.HasPrivilege(req.Param.ClubId, req.Param.ClubUid) {
			err_num = common.Error_Club_Privilege_Not_Enough
			logger.Notic("HasPrivilege ClubId:%v ClubUid:%v err_num:%v uid:%v", req.Param.ClubId, req.Param.ClubUid, err_num, header.PlayerID)
			break
		}

		//被操作者不在俱乐部中则退出 OK
		var bInClub bool = false
		if bInClub, er = clubmgr.IsUserInClub(req.Param.TargetId, req.Param.ClubId); er != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("IsUserInClub ClubId:%v TargetId:%v err_num:%v uid:%v", req.Param.ClubId, req.Param.TargetId, err_num, header.PlayerID)
			break
		} else {
			if !bInClub {
				err_num = common.Error_Player_Not_In_Club
				logger.Notic("IsUserInClub TargetId:%v club:%v bInClub:%v err_num:%v uid:%v", req.Param.TargetId, req.Param.ClubId, bInClub, err_num, header.PlayerID)
				break
			}
		}

		if req.Param.ActionType == common.Enum_Up_To_Club_Admin {
			//检查管理员数量
			full, err := clubmgr.IsAdminNumFull(req.Param.ClubId)
			if err != nil {
				err_num = common.Error_OperateDB_Failed
				logger.Notic("IsAdminNumFull uid:%v failed: %v", header.PlayerID, err_num)
				break
			}

			if full {
				err_num = common.Error_Club_Admin_Full
				logger.Notic("IsAdminNumFull uid:%v failed: %v", header.PlayerID, err_num)
				break
			}
		}

		//做修改操作
		err_num = clubmgr.DoModifyClubMember(req.Param.TargetId, req.Param.ClubId, req.Param.ActionType)
		if err_num != common.Error_OK {
			logger.Notic("DoModifyClubMember uid:%v failed: %v TargetId:%v ClubId:%v ActionType:%v", header.PlayerID, err_num, req.Param.TargetId, req.Param.ClubId, req.Param.ActionType)
			break
		}

		break
	}

	logger.Info("ModifyClubMemberHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseModifyClubMember
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_ModifyClubMember_Response, &resp)

	var noti pb.NoticeModifyClubMember
	if resp.Error == common.Error_OK {
		noti.ClubId = req.Param.ClubId
		noti.ActionType = req.Param.ActionType
		noti.TargetPlayerId = req.Param.TargetId

		//获取俱乐部名称
		if clubName, err := clubmgr.GetClubName(noti.ClubId); err == nil {
			noti.ClubName = clubName
		}

		memberIds, _ := clubmgr.GetClubMemberList(req.Param.ClubId)
		if len(memberIds) > 0 {
			for _, memberId := range memberIds {
				player, err := pmgr.GetPlayerFromMap(memberId)
				if nil == err && player != nil && player.Conn != nil {
					if userInfo, err := clubmgr.GetSubUserInfo(req.Param.TargetId); err == nil {
						if userInfo != nil {
							noti.TargetPlayerName = userInfo.Name
						}
					}

					common.SendNoti(player, header.RoomID, uint32(memberId), pb.MSGID_MsgID_ModifyClubMember_Notice, &noti)
					logger.Info("SendNoti MSGID_MsgID_ModifyClubMember_Notice uid:%v memberid:%v noti:%+v", player.UID, memberId, noti)
				}
			}
		}

		if req.Param.ActionType == common.Enum_Remove_Club_Member { //删除的成员，成员表中不存在，补充发送。
			player, err := pmgr.GetPlayerFromMap(req.Param.TargetId)
			if nil == err && player != nil && player.Conn != nil {
				if userInfo, err := clubmgr.GetSubUserInfo(req.Param.TargetId); err == nil {
					if userInfo != nil {
						noti.TargetPlayerName = userInfo.Name
					}
				}
				common.SendNoti(player, header.RoomID, uint32(req.Param.TargetId), pb.MSGID_MsgID_ModifyClubMember_Notice, &noti)
				logger.Info("SendNoti MSGID_MsgID_ModifyClubMember_Notice uid:%v TargetId:%v noti:%+v", player.UID, req.Param.TargetId, noti)
			}
		}
	}
}

func ModifyClubInfoHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestModifyClubInfo) {
	logger.Info("****ModifyClubInfoHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//请求者不是管理员也不是创建者则退出
		if !clubmgr.HasPrivilege(req.Param.ClubId, req.Param.ClubUid) {
			err_num = common.Error_Club_Privilege_Not_Enough
			logger.Notic("HasPrivilege uid:%v failed:%v ClubId:%v ClubUid:%v", header.PlayerID, err_num, req.Param.ClubId, req.Param.ClubUid)
			break
		}

		//check club name
		if bExist, _ := clubmgr.IsClubNameExist(req.Param.ClubName); bExist {
			if bMyself, _ := clubmgr.IsMyself(req.Param.ClubId, req.Param.ClubName); !bMyself {
				err_num = common.Error_Club_Name_Already_Exist
				logger.Notic("IsClubNameExist uid:%v failed:%v ClubId:%v ClubName:%v", header.PlayerID, err_num, req.Param.ClubId, req.Param.ClubName)
				break
			}
		}

		//做修改操作
		err := clubmgr.DoModifyClubInfo(req.Param)
		if err != nil {
			err_num = common.Error_Club_Other
			logger.Notic("DoModifyClubInfo uid:%v failed:%v req.Param:%+v", header.PlayerID, err_num, req.Param)
			break
		}

		break
	}

	logger.Info("ModifyClubInfoHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseModifyClubInfo
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_ModifyClubInfo_Response, &resp)
}

func JoinClubHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestJoinClub) {

	logger.Info("****JoinClubHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK

	var adminIds []uint32
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//club exist?
		if bClubExsit, err := clubmgr.IsClubExsit(req.ClubId); err == nil {
			if !bClubExsit {
				err_num = common.Error_ClubID_Not_Found
				logger.Notic("IsClubExsit uid:%v failed:%v", header.PlayerID, err_num)
				break
			}
		} else {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("IsClubExsit uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		if exist, _ := clubmgr.IsPlayerInClub(req.ClubId, header.PlayerID); exist {
			err_num = common.Error_Already_In_Club
			logger.Notic("IsPlayerInClub uid:%v clubid:%v err_num:%v", header.PlayerID, req.ClubId, err_num)
			break
		}

		if exist, _ := clubmgr.IsPlayerAlreadyApply(req.ClubId, header.PlayerID); exist { //Must modify if we have chance
			err_num = common.Error_Already_Apply_Club
			logger.Notic("IsPlayerAlreadyApply uid:%v clubid:%v err_num:%v", header.PlayerID, req.ClubId, err_num)
			break
		}

		//公共俱乐部
		var Type int
		var err error = nil
		if Type, err = clubmgr.GetClubType(req.ClubId); err == nil && Type == common.Enum_Club_Public {
			clubmgr.AddClubMember(req.ClubId, header.PlayerID)
			clubmgr.ModifyClubCurrentMemberNum(req.ClubId, 1)
			break
		}

		if len(req.InvitationCode) != 0 {
			club_id := common.CodeToId(req.InvitationCode)
			if clubmgr.IsClubTotalPlayerFull(club_id) {
				err_num = common.Error_Club_FULL
				logger.Notic("IsClubTotalPlayerFull uid:%v clubid:%v err_num:%v", header.PlayerID, req.ClubId, err_num)
			} else {
				clubmgr.AddClubMember(club_id, header.PlayerID)
				clubmgr.ModifyClubCurrentMemberNum(club_id, 1)
			}
			break
		}

		if Type != common.Enum_Club_Public {
			if clubmgr.IsClubTotalPlayerFull(req.ClubId) {
				err_num = common.Error_Club_FULL
				logger.Notic("IsClubTotalPlayerFull uid:%v clubid:%v err_num:%v", header.PlayerID, req.ClubId, err_num)
				break
			}
		}

		// 给在线俱乐部管理员
		var noti pb.NoticeJoinClub
		noti.ClubId = req.ClubId
		noti.ClubUid = req.ClubUid
		noti.ClubMessage = req.ClubMessage

		//获取俱乐部名称
		if clubName, err := clubmgr.GetClubName(noti.ClubId); err == nil {
			noti.ClubName = clubName
		}

		if subUserInfo, err := clubmgr.GetSubUserInfo(header.PlayerID); err == nil {
			if subUserInfo != nil {
				noti.ApplicantName = subUserInfo.Name
				noti.ApplicantThumb = subUserInfo.Thumb
			}
		}

		adminIds, _ = clubmgr.GetClubAdmins(req.ClubId)
		if len(adminIds) != 0 {
			for _, adminId := range adminIds {
				people, err := pmgr.GetPlayerFromMap(adminId)
				if nil == err && people.Conn != nil {
					common.SendNoti(people, header.RoomID, uint32(adminId), pb.MSGID_MsgID_JoinClub_Notice, &noti)
					logger.Notic("send MSGID_MsgID_JoinClub_Notice uid:%v noti:%+v", header.PlayerID, noti)
				}
			}

			clubmgr.DealApplyMsg(req.ClubId, req.ClubUid, req.ClubMessage)
		}

		break
	}

	logger.Info("JoinClubHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseJoinClubToMember
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_JoinClub_Response_To_Member, &resp)
}

func JoinClubReplyHandler(conn net.Conn, header pb.MessageHeader, req *pb.ReplyJoinClub) {
	logger.Info("****JoinClubReplyHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//被操作者在线，则直接把结果发给被操作者;不在线，则把待发送信息存库
		var noti pb.NoticeJoinClubToMember
		noti.Result = req.Result //todo fix
		noti.ClubId = req.ClubId
		noti.Uid = req.Uid
		noti.Reason = req.Reason

		//获取俱乐部名称
		if clubName, err := clubmgr.GetClubName(noti.ClubId); err == nil {
			noti.ClubName = clubName
		}

		if clubmgr.IsOtherAdminOperated(noti.ClubId, noti.Uid) {
			err_num = common.Error_OtherAdmin_Already_Operated
			var resp pb.ResponseJoinClubToAdmin
			resp.Error = int32(err_num)
			SendMessage(player, conn, header, pb.MSGID_MsgID_JoinClub_Response_To_Admin, &resp)

			logger.Info("IsOtherAdminOperated uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		if exist, _ := clubmgr.IsPlayerInClub(req.ClubId, noti.Uid); exist {
			err_num = common.Error_Already_In_Club
			logger.Info("IsPlayerInClub uid:%v failed:%v ClubId:%v ", header.PlayerID, err_num, req.ClubId)
			break
		}

		if req.Result == common.Enum_Apply_Club_Agree {
			clubmgr.AddClubMember(noti.ClubId, noti.Uid)
			clubmgr.ModifyClubCurrentMemberNum(noti.ClubId, 1)
			//clubmgr.DeleteApplyInfo(int(noti.ClubId), int(noti.Uid))
		}

		clubmgr.ModifyApplyCheckTime(noti.ClubId, noti.Uid)

		player, er := pmgr.GetPlayerFromMap(req.Uid)
		if er == nil {
			common.SendNoti(player, header.RoomID, header.PlayerID, pb.MSGID_MsgID_JoinClub_Notice_To_Member, &noti)
			logger.Info("SendNoti MsgID_JoinClub_Notice_To_Member uid:%v er:%v", header.PlayerID, er)
		} else {
			clubmgr.AddtPending(noti)
			logger.Info("AddtPending uid:%v er:%v", header.PlayerID, er)
		}

		//删除待审批消息
		//clubmgr.DeleteApplyInfo(int(noti.ClubId), int(noti.Uid))
		break
	}
}

func LoginHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestLogon) {
	logger.Info("****login req header:%+v body:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK

	var adminClubIds []uint32
	var adminAllianceIds []uint32
	var createdClubIds []uint32
	var applyInfoList []*pb.JoinClubParams
	var applyAllianceList []*pb.RequestJoinAlliance
	var pendingInfoList []*pb.NoticeJoinClubToMember
	var alliancePendingInfoList []*pb.NoticeJoinAllianceToMember
	var notifyClubGrantFundList []*db.NotifyClubGrantFundInfo
	//var mailList []*mail.MailInfo
	//var UserLastFetchMailTime uint32

	//var chatMsgList []*club.NoticeSendMsg
	var leaveallianceList []*pb.NoticeLeaveAlliance

	var player *common.GamePlayer

	logger.Info("LoginHandler 1 uid:%v seq:%v", header.PlayerID, header.Seq)

	for {
		logger.Info("LoginHandler 2 version check, uid=%v user version:%v lastest version:%v seq:%v", header.PlayerID, req.Version, conf.GetLastestVersion(), header.Seq)
		if req.Version != conf.GetLastestVersion() {
			err_num = common.Error_Version_Not_Lastest
			logger.Notic("version not lastest, uid=%v user version:%v lastest version:%v seq:%v", header.PlayerID, req.Version, conf.GetLastestVersion(), header.Seq)
			break
		}

		//check token
		//tk, err := db.LoadPlayerTokenFromDB(int(header.PlayerID))
		tk, err := resume.LoadPlayerTokenFromRedis(int(header.PlayerID))
		if err != nil {
			err_num = common.Error_Load_Player_Token_Failed
			logger.Notic("player uid:%v load token failed:%v seq:%v ", header.PlayerID, err_num, header.Seq)
			break
		}

		logger.Info("LoginHandler 3 player uid:%v user token:%v db token:%v seq:%v", header.PlayerID, req.Token, tk, header.Seq)

		if tk != req.Token {
			if conf.IsTest() == false {
				err_num = common.Error_Check_Token_Failed
				logger.Notic("player uid:%v check token failed:%v user token:%v db token:%v seq:%v", header.PlayerID, err_num, req.Token, tk, header.Seq)
				break
			}
		}

		logger.Info("LoginHandler 4 before get player uid:%v seq:%v", header.PlayerID, header.Seq)
		player, err_num = pmgr.GetPlayer(header.PlayerID)
		if err_num != common.Error_OK {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v seq:%v", header.PlayerID, err_num, header.Seq)
			break
		}
		player.ConningSeq = header.Seq

		//update conn into player
		player.UpdateConn(conn)

		//1.此登录玩家管理的clublids
		//1.a登录者创建的俱乐部（id集合）
		logger.Info("LoginHandler 5 before get create club uid:%v seq:%v", header.PlayerID, header.Seq)
		if createdClubIds, err = clubmgr.GetCreatedClubs(header.PlayerID); err != nil {
			err_num = common.Error_Club_Other
			logger.Notic("player uid:%v GetCreatedClubs:%v seq:%v", header.PlayerID, err_num, header.Seq)
			break
		}

		//1.b登录者不是创建者而是管理员（id集合）
		logger.Info("LoginHandler 6 before get admin club uid:%v seq:%v", header.PlayerID, header.Seq)
		if adminClubIds, err = clubmgr.GetAdminClubs(header.PlayerID); err != nil {
			err_num = common.Error_Club_Other
			logger.Notic("player uid:%v GetAdminClubs:%v seq:%v", header.PlayerID, err_num, header.Seq)
			break
		}

		//合并登录者相关的所有俱乐部id
		adminClubIds = FilterIDs(adminClubIds, createdClubIds)

		logger.Info("LoginHandler 7 before get admin alliances  uid:%v seq:%v", header.PlayerID, header.Seq)
		//A.获取联盟id集合
		if adminAllianceIds, err = clubmgr.GetAdminAllianceIds(adminClubIds); err != nil {
			err_num = common.Error_Club_Other
			logger.Notic("player uid:%v GetAdminAllianceIds:%v ", header.PlayerID, err_num)
			break
		}

		//2.取出待审批的信息列表
		logger.Info("LoginHandler 8 before get apply info  uid:%v seq:%v", header.PlayerID, header.Seq)
		if applyInfoList, err = clubmgr.GetApplyInfoList(adminClubIds); err != nil {
			err_num = common.Error_Club_Other
			logger.Notic("player uid:%v GetApplyInfoList:%v ", header.PlayerID, err_num)
			break
		}

		//B1.取出联盟待审批的信息列表
		logger.Info("LoginHandler 9 before get apply allinace  uid:%v seq:%v", header.PlayerID, header.Seq)
		if applyAllianceList, err = clubmgr.GetApplyAllianceList(adminAllianceIds); err != nil {
			err_num = common.Error_Club_Other
			logger.Notic("player uid:%v GetApplyAllianceList:%v ", header.PlayerID, err_num)
			break
		}

		//取出待通知信息列表
		logger.Info("LoginHandler 10 before get pending info  uid:%v seq:%v", header.PlayerID, header.Seq)
		if pendingInfoList, err = clubmgr.GetPendingInfoList(header.PlayerID); err != nil {
			err_num = common.Error_Club_Other
			logger.Notic("player uid:%v GetPendingInfoList:%v ", header.PlayerID, err_num)
			break
		}

		//B2.取出联盟待通知信息列表
		logger.Info("LoginHandler 11 before get alliance pending info  uid:%v seq:%v", header.PlayerID, header.Seq)
		if alliancePendingInfoList, err = clubmgr.GetAlliancePendingInfoList(header.PlayerID); err != nil {
			err_num = common.Error_Club_Other
			logger.Notic("player uid:%v GetAlliancePendingInfoList:%v ", header.PlayerID, err_num)
			break
		}

		//取出联盟管理员待通知信息列表
		logger.Info("LoginHandler 12 before get leave alliance info  uid:%v seq:%v", header.PlayerID, header.Seq)
		if leaveallianceList, err = clubmgr.GetLeaveallianceList(header.PlayerID); err != nil {
			err_num = common.Error_Club_Other
			logger.Notic("player uid:%v GetLeaveallianceList:%v ", header.PlayerID, err_num)
			break
		}

		//取出玩家转账等待通知的信息列表
		logger.Info("LoginHandler 13 before get notify clubGrant info  uid:%v seq:%v", header.PlayerID, header.Seq)
		if notifyClubGrantFundList, err = db.GetNotifyClubGrantFundInfo(header.PlayerID); err != nil {
			err_num = common.Error_Club_Other
			logger.Notic("player uid:%v GetNotifyClubGrantFundInfo:%v ", header.PlayerID, err_num)
			break
		}

		/*
			//取出玩家最后一次点击邮件时间
			logger.Info("LoginHandler 13.1 before get userlastfetchmailtime  uid:%v seq:%v", header.PlayerID, header.Seq)
			if UserLastFetchMailTime, err = mail.LoadUserFetchSysMailTime(header.PlayerID); err != nil {
				err_num = common.Error_Club_Other
				logger.Notic("player uid:%v mail.LoadUserFetchSysMailTime:%v ", header.PlayerID, err_num)
				break
			}

			//取出玩家个人邮件列表 并且加载系统邮件
			logger.Info("LoginHandler 13.2 before get mail info  uid:%v seq:%v", header.PlayerID, header.Seq)
			if mailList, err = mail.HandleAndGetUserMail(header.PlayerID, UserLastFetchMailTime); err != nil {
				err_num = common.Error_Club_Other
				logger.Notic("player uid:%v mail.HandleAndGetUserMail:%v ", header.PlayerID, err_num)
				break
			}
		*/

		utils.SendEventReport(header.PlayerID, 0, stat.Event_Type_WorldLogin, 0, 0, 0, "")

		player.ConnSeq = header.Seq
		break
	}
	if player != nil {
		player.ConningSeq = 0
	}
	logger.Info("LoginHandler 14   uid:%v seq:%v", header.PlayerID, header.Seq)

	if err_num == common.Error_OK {
		vv := common.PlayerMap.Get(uint32(header.PlayerID))
		if vv == nil {
			logger.Info("add player map uid:%d seq:%v", header.PlayerID, header.Seq)
			common.PlayerMap.Set(header.PlayerID, 1)
			go ConnWriter(player)
		}
	}

	logger.Info("LoginHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseLogon
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_Logon_Response, &resp)
	if err_num != common.Error_OK {
		return
	}
	//3.循环发待审批消息
	var noti pb.NoticeJoinClub
	for _, applyInfo := range applyInfoList {
		if applyInfo != nil {
			noti.ClubId = applyInfo.ClubId
			noti.ClubUid = applyInfo.ClubUid
			noti.ClubMessage = applyInfo.ClubMessage

			//获取俱乐部名称
			if clubName, err := clubmgr.GetClubName(noti.ClubId); err == nil {
				noti.ClubName = clubName
			}

			//从用户表取头像和昵称
			if subUserInfo, err := clubmgr.GetSubUserInfo(noti.ClubUid); err == nil {
				if subUserInfo != nil {
					noti.ApplicantName = subUserInfo.Name
					noti.ApplicantThumb = subUserInfo.Thumb
				}
			}

			common.SendNoti(player, header.RoomID, header.PlayerID, pb.MSGID_MsgID_JoinClub_Notice, &noti)
		}
	}
	logger.Info("LoginHandler 15   uid:%v seq:%v", header.PlayerID, header.Seq)

	//C.循环发联盟待审批消息
	var noti2 pb.NoticeJoinAlliance
	for _, allianceInfo := range applyAllianceList {
		if allianceInfo != nil {
			noti2.AllianceId = allianceInfo.AllianceId
			noti2.ClubId = allianceInfo.ClubId
			noti2.Message = allianceInfo.Message

			//获取俱乐部名称
			if name, err := clubmgr.GetAllianceName(noti2.AllianceId); err == nil {
				noti2.AllianceName = name
			}

			//获取俱乐部名称
			if name, err := clubmgr.GetClubName(noti2.ClubId); err == nil {
				noti2.ClubName = name
			}

			common.SendNoti(player, header.RoomID, header.PlayerID, pb.MSGID_MsgID_JoinAlliance_Notice_To_Admin, &noti2)
		}
	}
	logger.Info("LoginHandler 16   uid:%v seq:%v", header.PlayerID, header.Seq)

	//被操作者登录后，把t_club_pending_message相关的消息发个被操作者
	var notice pb.NoticeJoinClubToMember
	for _, pendingInfo := range pendingInfoList {
		notice.ClubId = pendingInfo.ClubId
		notice.Uid = pendingInfo.Uid
		notice.Result = pendingInfo.Result
		notice.Reason = pendingInfo.Reason
		//获取俱乐部名称
		if clubName, err := clubmgr.GetClubName(notice.ClubId); err == nil {
			notice.ClubName = clubName
		}
		common.SendNoti(player, header.RoomID, header.PlayerID, pb.MSGID_MsgID_JoinClub_Notice_To_Member, &notice)
	}
	logger.Info("LoginHandler 17   uid:%v seq:%v", header.PlayerID, header.Seq)

	//删除pending的消息
	clubmgr.DeletePendingList(notice.Uid, notice.ClubId)
	logger.Info("LoginHandler 18   uid:%v seq:%v", header.PlayerID, header.Seq)

	//向申请加入联盟的俱乐部管理员发送申请结果
	var allianceNoti pb.NoticeJoinAllianceToMember
	for _, alliancePendingInfo := range alliancePendingInfoList {
		allianceNoti.Result = alliancePendingInfo.Result
		allianceNoti.AllianceId = alliancePendingInfo.AllianceId
		allianceNoti.ClubId = alliancePendingInfo.ClubId
		allianceNoti.Reason = alliancePendingInfo.Reason
		allianceNoti.AllianceName = alliancePendingInfo.AllianceName
		allianceNoti.ClubAdminId = alliancePendingInfo.ClubAdminId
		common.SendNoti(player, header.RoomID, uint32(allianceNoti.ClubAdminId), pb.MSGID_MsgID_JoinAlliance_Notice_To_Member, &allianceNoti)
		//删除pending的消息
		clubmgr.DeleteAlliancePendingList(allianceNoti.ClubAdminId, allianceNoti.AllianceId)
	}

	logger.Info("LoginHandler 19   uid:%v seq:%v", header.PlayerID, header.Seq)
	//联盟管理员登录后，把t_leavealliance_notice联盟管理员
	for _, leaveallianceInfo := range leaveallianceList {
		common.SendNoti(player, header.RoomID, header.PlayerID, pb.MSGID_MsgID_LeaveAlliance_Notice, leaveallianceInfo)
		//删除通知联盟管理员的消息
		clubmgr.DeleteLeaveallianceNotice(header.PlayerID)
	}
	logger.Info("LoginHandler 20   uid:%v seq:%v", header.PlayerID, header.Seq)

	for _, notifyInfo := range notifyClubGrantFundList {
		var noti pb.ClubGrantFundNotice
		noti.Error = 1
		noti.OpPlayerId = notifyInfo.OperatorId
		noti.Clubid = notifyInfo.ClubId
		noti.Targetid = notifyInfo.TargetId
		noti.Amount = notifyInfo.Amount
		common.SendNoti(player, uint32(0), notifyInfo.TargetId, pb.MSGID_MsgID_ClubGrantFund_Notice, &noti)
	}
	db.DelNotifyClubGrantFundInfo(header.PlayerID)
	logger.Info("LoginHandler 21   uid:%v seq:%v", header.PlayerID, header.Seq)

	if len(req.InvitationCode) != 0 {
		var reqest pb.RequestJoinClub
		reqest.ClubUid = header.PlayerID
		reqest.InvitationCode = req.InvitationCode

		JoinClub(&reqest)
	}
}

func ConnCloseHandler(conn net.Conn, header pb.MessageHeader, req *pb.NoticeConnectionClose) {
	logger.Info("ConnCloseHandler-connection req:%+v", req)
	player, er := pmgr.GetPlayerFromMap(header.PlayerID)
	if er != nil {
		return
	}
	if player.ConnSeq != header.Seq || (player.ConningSeq > 0 && (player.ConningSeq != header.Seq)) {
		logger.Info("conn close, but seq not match, player valid connseq:%v closing seq:%d conning seq:%v for uid:%v",
			player.ConnSeq, header.Seq, player.ConningSeq, header.PlayerID)
		return
	}
	if player.OutDone != nil {
		logger.Info("conn close, outdone channel close for uid:%v", header.PlayerID)
		close(player.OutDone)
		player.OutDone = nil
	}

	pmgr.RemovePlayer(int(header.PlayerID))
	logger.Info("ConnCloseHandler-pmgr.RemovePlayer uid: %v", header.PlayerID)

	common.PlayerMap.Delete(header.PlayerID)

	logger.Info("player close outdone channel uid: %v", header.PlayerID)
}

func SendMsgHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestSendMsg) {
	logger.Info("****SendMsgHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var noti pb.NoticeSendMsg

	noti.ClubId = req.ClubId
	noti.UserId = header.PlayerID
	noti.Msg = req.Msg
	noti.ChatTime = uint32(time.Now().Unix())

	//返回响应
	var resp pb.ResponseSendMsg
	resp.Error = int32(err_num)

	for {
		memberIds, _ := clubmgr.GetClubMemberList(req.ClubId)
		if len(memberIds) != 0 {
			bStored := false
			for _, memberId := range memberIds {
				player, err := pmgr.GetPlayerFromMap(memberId)
				if nil == err {
					if subUserInfo, err := clubmgr.GetSubUserInfo(noti.UserId); err == nil {
						if subUserInfo != nil {
							noti.PlayerName = subUserInfo.Name
							noti.PlayerIcon = subUserInfo.Thumb
						}
					}

					SendMessage(player, conn, header, pb.MSGID_MsgID_SendMsg_Response, &resp)
					if player != nil {
						if nil == err && player != nil && player.Conn != nil {
							common.SendNoti(player, header.RoomID, uint32(memberId), pb.MSGID_MsgID_SendMsg_Notice, &noti)
						}
					}
				} else {
					if !bStored {
						clubmgr.AddMsgContent(&noti)
						bStored = true
					}
					clubmgr.AddPendingMsg(&noti, memberId)
				}
			}
		}

		break
	}
}

func GetUserDataHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestGetUserData) {
	logger.Info("****GetUserDataHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK

	var err error
	var info *club.UserInfo
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		if info, err = clubmgr.GetUserInfo(req.UserId); err != nil {
			err_num = common.Error_Too_Many_Club_To_CreateClub
			logger.Notic("GetUserInfo uid:%v failed:%v UserId:%v", header.PlayerID, err_num, req.UserId)
			break
		}

		break
	}

	logger.Info("GetUserDataHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseGetUserData
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_GetUserData_Response, &resp)

	if err_num == common.Error_OK {
		var noti pb.NoticeGetUserData
		if info != nil {
			//noti.DiamondNum = info.DiamondNum
			noti.GoldNum = info.UserGold
			noti.UserName = info.UserName
			noti.UserIcon = info.AvatarThumb
		}

		SendMessage(player, conn, header, pb.MSGID_MsgID_GetUserData_Notice, &noti)
		logger.Info("send MSGID_MsgID_GetUserData_Notice uid:%v noti:%+v", header.PlayerID, noti)
	}
}

func GetJackpotDataHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestGetJackpotData) {
	logger.Info("****GetJackpotDataHandler header :%+v request:%+v", header, req)

	var noti pb.NoticeGetJackpotData

	var err_num common.ErrorType = common.Error_OK
	var err error = nil
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v  failed:%v", header.PlayerID, err_num)
			break
		}

		noti.Jackpots, err = clubmgr.GetJackpotList(req.ClubId)
		if err != nil {
			err_num = common.Error_Get_JackpotInfo_Failed
			logger.Notic("GetJackpotList uid:%v  failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		}

		noti.ClubName, noti.ClubAvatar, noti.ClubArea, err = clubmgr.GetJackpotClubInfo(req.ClubId)
		if err != nil {
			err_num = common.Error_Get_JackpotClubInfo_Failed
			logger.Notic("GetJackpotClubInfo uid:%v  failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		}

		noti.ClubId = req.ClubId

		break
	}

	logger.Info("GetJackpotDataHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseGetJackpotData
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_GetJackpotData_Response, &resp)

	if err_num == common.Error_OK {
		SendMessage(player, conn, header, pb.MSGID_MsgID_GetJackpotData_Notice, &noti)
		logger.Info("send MsgID_GetJackpotData_Notice uid:%v noti:%+v", header.PlayerID, noti)
	}
}

func JackpotSettingHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestJackpotSetting) {
	logger.Info("****JackpotSettingHandler header :%+v request:%+v", header, req)

	var noti pb.NoticeJackpotSetting

	var err_num common.ErrorType = common.Error_OK
	var err error
	var player *common.GamePlayer = nil
	var percent int
	var bAwardPercent bool = false

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//请求者不是管理员也不是创建者则退出
		if !clubmgr.HasPrivilege(req.ClubId, header.PlayerID) {
			err_num = common.Error_Club_Privilege_Not_Enough
			logger.Notic("HasPrivilege uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		}

		games := roommgr.GetClubGameInfo(req.ClubId)

		var bExist bool = false
		if len(games) > 0 {
			for _, game := range games {
				if game.ClubId == req.ClubId && game.JackpotIsopen {
					bExist = true
					break
				}
			}
			if bExist {
				err_num = common.Error_Jackpotsetting_while_BoardIsRunning
				break
			}
		}

		noti.Jackpots, err = clubmgr.GetJackpotInfoList(req.ClubId)
		if err != nil {
			err_num = common.Error_Get_JackpotInfo_Failed
			logger.Notic("GetJackpotInfoList uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		}

		noti.AwardTypes, err = clubmgr.GetAwardTypeList(req.ClubId)
		if err != nil {
			err_num = common.Error_Get_JackpotAwardType_Failed
			logger.Notic("GetAwardTypeList uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		}

		noti.ClubId = req.ClubId

		percent, bAwardPercent, err = clubmgr.GetAward2ClubPercent(req.ClubId)
		if err != nil {
			err_num = common.Error_Get_Award2ClubPercent_Failed
			logger.Notic("GetAward2ClubPercent uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		} else {
			if !bAwardPercent {
				percent := conf.GetAward2ClubPercent()
				clubmgr.SetAward2ClubPercent(req.ClubId, int32(percent))
			}
		}
		noti.Award2ClubPercent = int32(percent)

		if len(noti.AwardTypes) == 0 {
			Handlevels := conf.GetHandlevels()
			for _, HandlevelInfo := range Handlevels {
				awardType := new(pb.AwardType)
				awardType.HandLevel = int32(HandlevelInfo.ID)
				awardType.AwardPercent = int32(HandlevelInfo.AwardPercent)
				noti.AwardTypes = append(noti.AwardTypes, awardType)
				err = clubmgr.SetJackpotAwardType(req.ClubId, awardType.HandLevel, awardType.AwardPercent)
				if err != nil {
					err_num = common.Error_Set_JackpotAwardType_Failed
					logger.Notic("GetAward2ClubPercent uid:%v failed:%v ClubId:%v HandLevel:%v AwardPercent:%v", header.PlayerID, err_num, req.ClubId, awardType.HandLevel, awardType.AwardPercent)
					break
				}
			}
		}

		break
	}

	logger.Info("JackpotSettingHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseJackpotSetting
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_JackpotSetting_Response, &resp)

	if err_num == common.Error_OK {
		SendMessage(player, conn, header, pb.MSGID_MsgID_JackpotSetting_Notice, &noti)
		logger.Info("JackpotSettingHandler send  MSGID_MsgID_JackpotSetting_Notice uid:%v noti:%+v", header.PlayerID, noti)
	}
}

func SetJackpotHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestSetJackpot) {
	logger.Info("****SetJackpotHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//请求者不是管理员也不是创建者则退出
		if !clubmgr.HasPrivilege(req.ClubId, header.PlayerID) {
			err_num = common.Error_Club_Privilege_Not_Enough
			logger.Notic("uid :%v Has no ClubId:%v 's Privilege err_num:%v", header.PlayerID, req.ClubId, err_num)
			break
		}

		for _, jackpot := range req.Jackpots {
			err := clubmgr.SetJackpot(req.ClubId, jackpot.BlindLevel, jackpot.ProfitScale, jackpot.DrawinAmout)
			if err != nil {
				err_num = common.Error_Set_JackpotInfo_Failed
				logger.Notic("Set JackpotInfo Failed:%v clubid:%v BlindLevel:%v ProfitScale:%v DrawinAmout:%v", err_num, req.ClubId, jackpot.BlindLevel, jackpot.ProfitScale, jackpot.DrawinAmout)
				break
			}
		}

		var bSetAwardErr bool = false
		for _, awardType := range req.AwardTypes {
			err := clubmgr.SetJackpotAwardType(req.ClubId, awardType.HandLevel, awardType.AwardPercent)
			if err != nil {
				err_num = common.Error_Set_JackpotAwardType_Failed
				bSetAwardErr = true
				logger.Notic("SetJackpotAwardType Failed:%v clubid:%v HandLevel:%v AwardPercent:%v ", err_num, req.ClubId, awardType.HandLevel, awardType.AwardPercent)
				break
			}
		}

		if bSetAwardErr {
			break
		}

		err := clubmgr.SetAward2ClubPercent(req.ClubId, req.Award2ClubPercent)
		if err != nil {
			err_num = common.Error_Set_Award2ClubPercent_Failed
			logger.Notic("SetAward2ClubPercent Failed:%v clubid:%v Award2ClubPercent:%v ", err_num, req.ClubId, req.Award2ClubPercent)
			break
		}

		// 删掉关闭的jackpot
		levels, _ := clubmgr.GetClubOpenedLevels(req.ClubId)
		for _, level := range levels {
			isExist := false
			for _, jackpot := range req.Jackpots {
				if int(jackpot.BlindLevel) == level {
					isExist = true
				}
			}
			if !isExist {
				amount, err := clubmgr.GetJackpotAmount(req.ClubId, level)
				if err == nil && amount == 0 {
					clubmgr.DeleteSpecialBlindlevels(req.ClubId, level)
				}
			}
		}

		break
	}

	logger.Info("SetJackpotHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseSetJackpot
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_SetJackpot_Response, &resp)
}

func RecoverJackpotSettingHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestRecoverJackpotSetting) {
	logger.Info("****RecoverJackpotSettingHandler header :%+v request:%+v", header, req)
	var jackpots []*pb.JackpotInfo

	var err_num common.ErrorType
	err_num = common.Error_OK
	var err error = nil

	var awardTypes []*pb.AwardType
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}
		//请求者不是管理员也不是创建者则退出
		if !clubmgr.HasPrivilege(req.ClubId, header.PlayerID) {
			err_num = common.Error_Club_Privilege_Not_Enough
			logger.Notic("HasPrivilege uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		}

		jackpots, err = clubmgr.GetJackpotInfoList(req.ClubId)
		if err != nil {
			err_num = common.Error_Get_ClubOpenedJackpots_Failed
			logger.Notic("GetJackpotInfoList uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		} else {
			var bSetJackpotErr bool = false
			for _, jackpot := range jackpots {
				// 待设置默认值
				blind := conf.GetBlindByIndex(uint32(jackpot.BlindLevel))
				err := clubmgr.SetJackpot(req.ClubId, jackpot.BlindLevel, blind.Scale, blind.DrawinAmout)
				if err != nil {
					err_num = common.Error_Set_JackpotInfo_Failed
					bSetJackpotErr = true
					logger.Notic("SetJackpot failed:%v clubid:%v blindlevel:%v scale:%v drawinamount:%v", err_num, req.ClubId, jackpot.BlindLevel, blind.Scale, blind.DrawinAmout)
					break
				}
			}

			if bSetJackpotErr {
				break
			}
		}

		awardTypes, err = clubmgr.GetAwardTypeList(req.ClubId)
		if err != nil {
			err_num = common.Error_Get_JackpotAwardType_Failed
			logger.Notic("GetAwardTypeList uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		} else {
			var bSetTypeErr bool = false
			for _, awardType := range awardTypes {
				// 待设置默认值
				HandlevelInfo := conf.GetHandlevelByIndex(uint32(awardType.HandLevel))
				err := clubmgr.SetJackpotAwardType(req.ClubId, awardType.HandLevel, int32(HandlevelInfo.AwardPercent))
				if err != nil {
					err_num = common.Error_Set_JackpotAwardType_Failed
					bSetTypeErr = true
					logger.Notic("clubid:%v set jackpot award failed! handlevel:%v awardpercent:%v", req.ClubId, awardType.HandLevel, HandlevelInfo.AwardPercent)
					break
				}
			}
			if bSetTypeErr {
				break
			}
		}

		Percent := conf.GetAward2ClubPercent()
		err := clubmgr.SetAward2ClubPercent(req.ClubId, int32(Percent))
		if err != nil {
			err_num = common.Error_Set_Award2ClubPercent_Failed
			logger.Notic("SetAward2ClubPercent uid:%v failed:%v ClubId:%v Percent:%v", header.PlayerID, err_num, req.ClubId, Percent)
			break
		}

		break
	}

	logger.Info("RecoverJackpotSettingHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseJackpotSetting
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_RecoverJackpotSetting_Response, &resp)
}

func CurrentRoomJackpotHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestCurrentRoomJackpot) {
	logger.Info("****CurrentRoomJackpotHandler header :%+v request:%+v", header, req)

	var noti pb.NoticeCurrentRoomJackpot
	var jackpotInfo *pb.JackpotInfo

	var err_num common.ErrorType = common.Error_OK
	var err error = nil
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		jackpotInfo, err = clubmgr.GetJackpotInfo(req.ClubId, int(req.BlindLevel))
		if err != nil || jackpotInfo == nil {
			err_num = common.Error_Get_JackpotInfo_Failed
			logger.Notic("GetJackpotInfo uid:%v failed:%v ClubId:%v BlindLevel:%v", header.PlayerID, err_num, req.ClubId, req.BlindLevel)
			break
		}

		noti.ProfitScale = jackpotInfo.ProfitScale
		noti.DrawinAmout = jackpotInfo.DrawinAmout

		noti.AwardTypes, err = clubmgr.GetAwardTypeList(req.ClubId)
		if err != nil || len(noti.AwardTypes) == 0 {
			err_num = common.Error_Get_JackpotAwardType_Failed
			logger.Notic("GetAwardTypeList uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		}

		break
	}

	logger.Info("CurrentRoomJackpotHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseCurrentRoomJackpot
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_CurrentRoomJackpot_Response, &resp)

	if err_num == common.Error_OK {
		SendMessage(player, conn, header, pb.MSGID_MsgID_CurrentRoomJackpot_Notice, &noti)
		logger.Info("CurrentRoomJackpotHandler result uid:%v noti:%+v", header.PlayerID, noti)
	}
}

func JackpotAwardRecordHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestJackpotAwardRecord) {
	logger.Info("****JackpotAwardRecordHandler header :%+v request:%+v", header, req)

	var noti pb.NoticeJackpotAwardRecord

	var err_num common.ErrorType = common.Error_OK
	var err error = nil
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		noti.AwardInfos, err = clubmgr.GetJackpotAwardList(req.ClubId, int(req.BlindLevel))
		if err != nil || len(noti.AwardInfos) == 0 {
			err_num = common.Error_Get_JackpotInfo_Failed
			logger.Notic("GetJackpotAwardList failed:%v clubid:%v blindlevel:%v", err_num, req.ClubId, req.BlindLevel)
			break
		}

		noti.LuckDog, err = clubmgr.GetLuckyJackpotAward(req.ClubId, int(req.BlindLevel))
		if err != nil {
			err_num = common.Error_Get_JackpotClubInfo_Failed
			logger.Notic("GetLuckyJackpotAward failed:%v clubid:%v BlindLevel:%v", err_num, req.ClubId, req.BlindLevel)
			break
		}

		break
	}

	logger.Info("JackpotAwardRecordHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseJackpotAwardRecord
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_JackpotAwardRecord_Response, &resp)

	if err_num == common.Error_OK {
		SendMessage(player, conn, header, pb.MSGID_MsgID_JackpotAwardRecord_Notice, &noti)
		logger.Info("JackpotAwardRecordHandler result uid:%v noti:%+v", header.PlayerID, noti)
	}
}

func JackpotInjectAmountHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestJackpotInjectAmount) {
	logger.Info("****JackpotInjectAmountHandler header :%+v request:%+v", header, req)

	var notiAmount pb.NoticeJackpotAmout
	var err_num common.ErrorType = common.Error_OK
	var cur_amount int64 = 0
	var player *common.GamePlayer = nil
	for {
		//请求者不是管理员也不是创建者则退出
		if !clubmgr.HasPrivilege(req.ClubId, header.PlayerID) {
			err_num = common.Error_Club_Privilege_Not_Enough
			logger.Notic("privilege not enough!clubid:%v uid:%v", req.ClubId, header.PlayerID)
			break
		}

		logger.Info("clubid:%v uid:%v BlindLevel:%v Amount:%v", req.ClubId, header.PlayerID, req.BlindLevel, req.Amount)

		if req.Amount < 0 {
			err_num = common.Error_Club_Other
			logger.Notic("Amount not valid!clubid:%v uid:%v Amount:%v", req.ClubId, header.PlayerID, req.Amount)
			break
		}

		// 给俱乐部充值者金币是否够
		if !clubmgr.IsUserGoldEnough(header.PlayerID, req.Amount) {
			err_num = common.Error_UserGold_Not_Enough
			logger.Notic("IsUserGoldEnough amount:%v uid:%v err_num:%v", req.Amount, header.PlayerID, err_num)
			break
		}

		preAmount, err := db.GetJackpotAmount(req.ClubId, int(req.BlindLevel))
		if err != nil {
			logger.Notic("GetJackpotAmount failed! clubid:%v blindlevel:%v ", req.ClubId, req.BlindLevel)
			err_num = common.Error_OperateDB_Failed
			break
		}

		logger.Info("uid:%v ClubId:%v BlindLevel:%v preAmount:%v", header.PlayerID, req.ClubId, req.BlindLevel, preAmount)

		notiAmount.ClubId = req.ClubId
		notiAmount.BlindLevel = req.BlindLevel
		notiAmount.PrevAmount = preAmount
		notiAmount.CurrentAmout = preAmount + req.Amount

		logger.Info("uid:%v ClubId:%v BlindLevel:%v CurrentAmout:%v", header.PlayerID, req.ClubId, req.BlindLevel, notiAmount.CurrentAmout)

		//做修改操作
		cur_amount, err = clubmgr.DoInjectJackpotAmount(header.PlayerID, req.ClubId, int32(req.BlindLevel), req.Amount)
		if err != nil {
			err_num = common.Error_InjectJackpotAmount_Failed
			logger.Notic("DoInjectJackpotAmount err_num:%v ClubId:%v blindlevel:%v Amount:%v", err_num, req.ClubId, req.BlindLevel, req.Amount)
			break
		} else {
			utils.SendEventReport(header.PlayerID, req.ClubId, stat.Event_Type_JackpotInjectAmount, int(req.BlindLevel), int(req.Amount), 0, "")
		}

		break
	}

	logger.Info("JackpotInjectAmountHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseJackpotInjectAmount
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_JackpotInjectAmount_Response, &resp)
	if err_num == common.Error_OK {
		var noti pb.NoticeJackpotInjectAmount
		noti.ClubId = req.ClubId
		noti.BlindLevel = int32(req.BlindLevel)
		noti.Amount = cur_amount
		SendMessage(player, conn, header, pb.MSGID_MsgID_JackpotInjectAmount_Notice, &noti)
		logger.Info("JackpotInjectAmountHandler result uid:%v noti:%+v", header.PlayerID, noti)

		//查询此俱乐部对应的牌局
		var memberIds []uint32
		var AllClubIds []uint32
		allianceClubids := roommgr.GetJackpotClubIds(req.ClubId)
		AllClubIds = append(allianceClubids, req.ClubId)
		AllClubIds = common.RemoveDuplicates(AllClubIds)
		for _, cid := range AllClubIds {
			pIds, _ := db.GetClubMemberList(cid)
			memberIds = append(memberIds, pIds...)
		}

		if len(memberIds) != 0 {
			for _, memberId := range memberIds {
				player, err := pmgr.GetPlayerFromMap(memberId)
				if player != nil {
					if nil == err && player != nil && player.Conn != nil {
						common.SendNoti(player, uint32(header.RoomID), uint32(memberId), pb.MSGID_MsgID_JackpotAmout_Notice, &notiAmount)
					}
				}
			}
		}
	}
}

func HeartBeatHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestHeartBeat) {
	player, er := pmgr.GetPlayerFromMap(header.PlayerID)
	if er == nil {
		var resp pb.ResponseHeartBeat
		resp.Uid = req.Uid
		SendMessage(player, conn, header, pb.MSGID_MsgID_HeartBeat_Response, &resp)
	}
}

func CreateAllianceHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestCreateAlliance) {
	logger.Info("****CreateAllianceHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		full, err := clubmgr.IsCreatedAllianceNumFull(req.ClubId)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("IsCreatedAllianceNumFull uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		}

		if full {
			err_num = common.Error_Too_Many_Alliance_To_CreateAlliance
			logger.Notic("IsCreatedAllianceNumFull uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		}

		name_exist, err := clubmgr.IsAllianceNameExist(req.AllianceName)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("IsAllianceNameExist uid:%v failed:%v AllianceName:%v", header.PlayerID, err_num, req.AllianceName)
			break
		}

		if name_exist {
			err_num = common.Error_Alliance_Name_Already_Exist
			logger.Notic("IsAllianceNameExist uid:%v failed:%v AllianceName:%v", header.PlayerID, err_num, req.AllianceName)
			break
		}

		//		cids, err := clubmgr.GetClubMemberList(int32(req.ClubId))
		//		if err != nil {
		//			err_num = common.Error_OperateDB_Failed
		//			logger.Notic("GetClubMemberList uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
		//			break
		//		} else {
		//			//			if len(cids) < 20 {
		//			//				err_num = common.Error_ClubNumber_Not_Enough
		//			//				logger.Notic("GetClubMemberList uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
		//			//			}

		//			break
		//		}

		//建立联盟数据结构
		Info := BuildAllianceParams(req)

		allianceId, err := clubmgr.AddAlliance(Info)
		if err != nil {
			err_num = common.Error_CreateAlliance_failure
			logger.Notic("AddAlliance uid:%v failed:%v Info:%+v", header.PlayerID, err_num, Info)
			break
		}

		err = clubmgr.AddAllianceMember(allianceId, req.ClubId, req.ClubId)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("AddAllianceMember uid:%v failed:%v allianceId:%v", header.PlayerID, err_num, allianceId)
			break
		}

		err = clubmgr.SetAllianceInvitationCode(allianceId, common.IdTo8BitCode(allianceId))
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("CreateAllianceHandler SetAllianceInvitationCode uid:%v failed:%v allianceId:%v, err:%v", header.PlayerID, err_num, allianceId, err)
			break
		}

		break
	}

	logger.Info("CreateAllianceHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseCreateAlliance
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_CreateAlliance_Response, &resp)
}

func LeaveAllianceHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestLeaveAlliance) {
	logger.Info("****RequestLeaveAlliance header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//普通成员和管理员请求退出可以直接退出
		if !clubmgr.IsTargetAllianceCreater(req.ClubId, req.AllianceId) {
			err_num = clubmgr.DoNonCreaterLeaveAlliance(req.AllianceId, req.ClubId)
			break
		}

		//俱乐部是否为空
		if !clubmgr.IsAllianceMemberEmpty(req.AllianceId) {
			err_num = common.Error_Alliance_Member_Not_Empty
			logger.Notic("IsAllianceMemberEmpty uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		if roommgr.ClubhasBoardRunning(req.ClubId) {
			err_num = common.Error_Board_IsRunning
			logger.Notic("ClubhasBoardRunning uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		err_num = clubmgr.DoCreaterLeaveAlliance(req.AllianceId, req.ClubId)

		break

	}

	logger.Info("LeaveAllianceHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseLeaveAlliance
	resp.Error = int32(err_num)
	if err_num == common.Error_OK {
		clubmgr.DeleteAllianceApplyInfo(req.AllianceId, req.ClubId)

		//roommgr.CleanAllianceDeletedBoard(int(req.ClubId))

		adminIds, e := clubmgr.GetAllianceAdmins(req.AllianceId)
		if e == nil && len(adminIds) != 0 {
			var noti pb.NoticeLeaveAlliance
			noti.AllianceId = req.AllianceId
			noti.ClubId = req.ClubId
			noti.AllianceName, _ = clubmgr.GetAllianceName(req.AllianceId)
			noti.ClubName, _, _ = clubmgr.GetClubInfo(req.ClubId)

			for _, adminId := range adminIds {
				player, err := pmgr.GetPlayerFromMap(adminId)
				if nil == err && player != nil && player.Conn != nil {
					common.SendNoti(player, header.RoomID, uint32(adminId), pb.MSGID_MsgID_LeaveAlliance_Notice, &noti)
				} else {
					clubmgr.AddLeaveallianceNotice(noti, adminId)
				}
			}
		}
	}

	SendMessage(player, conn, header, pb.MSGID_MsgID_LeaveAlliance_Response, &resp)
}

// 联盟信息
func SearchAllianceHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestSearchAllianceInfo) {
	logger.Info("****SearchAllianceHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var err error = nil
	var noti *pb.NoticeSearchAlliance = nil
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		// 获取联盟信息
		if noti, err = clubmgr.GetAllianceInfo(req.AllianceId); err != nil || (noti == nil) {
			err_num = common.Error_Alliance_Not_Found
			logger.Notic("GetAllianceInfo uid:%v err_num:%v", header.PlayerID, err_num)
			break
		} else {
			if len(noti.ClubItems) == 0 {
				err_num = common.Error_Alliance_Not_Found
				logger.Notic("GetAllianceInfo uid:%v err_num:%v", header.PlayerID, err_num)
				break
			}
		}

		break
	}

	logger.Info("SearchAllianceHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseSearchAllianceInfo
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_SearchAlliance_Response, &resp)

	if err_num == common.Error_OK {
		SendMessage(player, conn, header, pb.MSGID_MsgID_SearchAlliance_Notice, noti)
		logger.Info("SearchAllianceHandler result uid:%v noti:%+v", header.PlayerID, noti)
	}
}

func KickoffAllianceMemberHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestKickoffAllianceMember) {

	logger.Info("****KickoffAllianceMemberHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		//被操作者是联盟的创建者则退出
		if clubmgr.IsTargetAllianceCreater(req.TargetId, req.AllianceId) {
			err_num = common.Error_Alliance_Other
			logger.Notic("IsTargetAllianceCreater uid:%v failed:%v TargetId:%v AllianceId:%v", header.PlayerID, err_num, req.TargetId, req.AllianceId)
			break
		}

		//请求者不是管理员也不是创建者则退出
		if !clubmgr.HasAlliancePrivilege(req.AllianceId, req.ClubId) {
			err_num = common.Error_Alliance_Privilege_Not_Enough
			logger.Notic("HasAlliancePrivilege uid:%v failed:%v ClubId:%v AllianceId:%v", header.PlayerID, err_num, req.ClubId, req.AllianceId)
			break
		}

		//被操作者不在联盟中则退出 OK
		ok, _ := clubmgr.IsClubInAlliance(req.AllianceId, req.ClubId)
		if ok == false {
			err_num = common.Error_club_Not_In_Alliance
			logger.Notic("IsClubInAlliance uid:%v failed:%v ClubId:%v AllianceId:%v", header.PlayerID, err_num, req.ClubId, req.AllianceId)
			break
		}

		if roommgr.ClubhasBoardRunning(req.ClubId) {
			err_num = common.Error_Board_IsRunning
			logger.Notic("ClubhasBoardRunning uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		}

		//做修改操作
		err_num = clubmgr.DoRemoveAllianceMember(req.TargetId, req.AllianceId)
		if err_num != common.Error_OK {
			logger.Notic("DoRemoveAllianceMember uid:%v failed:%v TargetId:%v, AllianceId:%v", header.PlayerID, err_num, req.TargetId, req.AllianceId)
			break
		} else {
			clubmgr.DeleteAllianceApplyInfo(req.AllianceId, req.TargetId)
			//roommgr.CleanAllianceDeletedBoard(int(req.TargetId))
		}

		break
	}

	logger.Info("KickoffAllianceMemberHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseKickoffAllianceMember
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_KickoffAllianceMember_Response, &resp)

	var noti pb.NoticeKickoffAllianceMember
	if resp.Error == common.Error_OK {
		//获取俱乐部名称
		if clubName, err := clubmgr.GetClubName(req.TargetId); err == nil {
			noti.TargetClubName = clubName
		}

		if name, err := clubmgr.GetAllianceName(req.AllianceId); err == nil {
			noti.AllianceName = name
		}

		noti.AllianceId = req.AllianceId
		noti.TargetClubId = req.TargetId

		adminIds, e := clubmgr.GetClubAdmins(req.TargetId)
		if e == nil && len(adminIds) != 0 {
			for _, adminId := range adminIds {
				player, err := pmgr.GetPlayerFromMap(adminId)
				if nil == err && player != nil && player.Conn != nil {
					common.SendNoti(player, header.RoomID, uint32(adminId), pb.MSGID_MsgID_KickoffAllianceMember_Notice, &noti)
					logger.Info("KickoffAllianceMemberHandler result uid:%v noti:%+v adminId:%v", header.PlayerID, noti, adminId)
				}
			}
		}
	}
}

// 联盟列表
func AllianceListHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestAllianceList) {
	logger.Info("****AllianceListHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var allianceIds []uint32
	var err error = nil
	var list []*pb.AllianceListParams
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v failed:%v", header.PlayerID, err_num)
			break
		}

		allianceIds, err = clubmgr.GetAllianceIds(req.ClubId)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("GetAllianceIds uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
			break
		}

		allianceIds = common.RemoveDuplicates(allianceIds)

		// 获取俱乐部快照列表
		list, err = clubmgr.GetAllianceList(allianceIds, req.ClubId)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("GetAllianceList uid:%v failed:%v ClubId:%v allianceIds:%v", header.PlayerID, err_num, req.ClubId, allianceIds)
			break
		}

		break
	}

	logger.Info("AllianceListHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseAllianceList
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_AllianceList_Response, &resp)

	if err_num == common.Error_OK {
		var noti pb.NoticeAllianceList
		noti.List = append(noti.List, list...)
		SendMessage(player, conn, header, pb.MSGID_MsgID_AllianceList_Notice, &noti)
		logger.Info("AllianceListHandler result uid:%v noti:%+v", header.PlayerID, noti)
	}
}

func JoinAllianceHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestJoinAlliance) {
	logger.Info("****JoinAllianceHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid failed! uid:%v err:%v", header.PlayerID, er)
			break
		}

		//Alliance exist?
		ok, _ := clubmgr.IsAllianceExsit(req.AllianceId)
		if ok == false {
			err_num = common.Error_AllianceID_Not_Found
			logger.Notic("IsAllianceExsit uid:%v err_num:%v AllianceId:%v", header.PlayerID, err_num, req.AllianceId)
			break
		}

		if exist, _ := clubmgr.IsClubInAlliance(req.AllianceId, req.ClubId); exist {
			err_num = common.Error_Already_In_Alliance
			logger.Notic("IsClubInAlliance uid:%v err_num:%v AllianceId:%v ClubId:%v", header.PlayerID, err_num, req.AllianceId, req.ClubId)
			break
		}

		if exist, _ := clubmgr.IsClubAlreadyApply(req.AllianceId, req.ClubId); exist {
			err_num = common.Error_Already_Apply_Alliance
			logger.Notic("IsClubAlreadyApply uid:%v err_num:%v AllianceId:%v ClubId:%v", header.PlayerID, err_num, req.AllianceId, req.ClubId)
			break
		}

		full, err := clubmgr.IsJoinedAllianceNumFull(req.ClubId)
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("IsJoinedAllianceNumFull uid:%v err_num:%v AllianceId:%v ClubId:%v", header.PlayerID, err_num, req.AllianceId, req.ClubId)
			break
		}

		if full {
			err_num = common.Error_Too_Many_Alliance_To_Join
			logger.Notic("IsJoinedAllianceNumFull uid:%v err_num:%v AllianceId:%v ClubId:%v", header.PlayerID, err_num, req.AllianceId, req.ClubId)
			break
		}

		if clubmgr.IsAllianceFull(req.AllianceId) {
			err_num = common.Error_Alliance_FULL
			logger.Notic("IsAllianceFull uid:%v err_num:%v AllianceId:%v", header.PlayerID, err_num, req.AllianceId)
			break
		}

		//		cids, err := clubmgr.GetClubMemberList(int32(req.ClubId))
		//		if err != nil {
		//			err_num = common.Error_OperateDB_Failed
		//			logger.Notic("GetClubMemberList uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
		//			break
		//		} else {
		//			//			if len(cids) < 20 {
		//			//				err_num = common.Error_ClubNumber_Not_Enough
		//			//				logger.Notic("GetClubMemberList uid:%v failed:%v ClubId:%v", header.PlayerID, err_num, req.ClubId)
		//			//			}

		//			break
		//		}

		// 给在线联盟管理员
		var noti pb.NoticeJoinAlliance
		noti.AllianceId = req.AllianceId
		noti.ClubId = req.ClubId
		noti.Message = req.Message

		//获取联盟名称
		if Name, err := clubmgr.GetAllianceName(noti.AllianceId); err == nil {
			noti.AllianceName = Name
		}

		if clubName, err := clubmgr.GetClubName(noti.ClubId); err == nil {
			noti.ClubName = clubName
		}

		adminIds, _ := clubmgr.GetAllianceAdmins(req.AllianceId)
		if len(adminIds) != 0 {
			for _, adminId := range adminIds {
				player, err := pmgr.GetPlayerFromMap(adminId)
				if nil == err && player != nil && player.Conn != nil {
					common.SendNoti(player, header.RoomID, uint32(adminId), pb.MSGID_MsgID_JoinAlliance_Notice_To_Admin, &noti)
					logger.Info("JoinAllianceHandler result uid:%v noti:%+v adminId:%v", header.PlayerID, noti, adminId)
				}
			}

			clubmgr.DealAllianceApplyMsg(req.AllianceId, req.ClubId, req.Message)
		}

		break
	}

	logger.Info("JoinAllianceHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	var resp pb.ResponseJoinAllianceToMember
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_JoinAlliance_Response_To_Member, &resp)
}

func JoinAllianceReplyHandler(conn net.Conn, header pb.MessageHeader, req *pb.ReplyJoinAllianceToWorld) {
	logger.Info("****JoinAllianceReplyHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK

	var resp pb.ResponseJoinAllianceToAdmin
	var player *common.GamePlayer = nil
	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("GetPlayerFromMap failed! uid:%v error:%v", header.PlayerID, er)
			break
		}

		//被操作者在线，则直接把结果发给被操作者;不在线，则把待发送信息存库
		var noti pb.NoticeJoinAllianceToMember
		noti.Result = req.Result //todo fix
		noti.AllianceId = req.AllianceId
		noti.ClubId = req.ClubId
		noti.Reason = req.Reason

		//获取俱乐部名称
		if name, err := clubmgr.GetAllianceName(noti.AllianceId); err == nil {
			noti.AllianceName = name
		}

		if clubmgr.IsOtherAllianceAdminOperated(noti.AllianceId, noti.ClubId) {
			err_num = common.Error_AllianceOtherAdmin_Already_Operated
			logger.Notic("IsOtherAllianceAdminOperated uid:%v err_num:%v AllianceId:%v ClubId:%v", header.PlayerID, err_num, noti.AllianceId, noti.ClubId)
			break
		}

		if exist, _ := clubmgr.IsClubInAlliance(req.AllianceId, noti.ClubId); exist {
			err_num = common.Error_Already_In_Alliance
			logger.Notic("IsClubInAlliance uid:%v err_num:%v AllianceId:%v ClubId:%v", header.PlayerID, err_num, req.AllianceId, noti.ClubId)
			break
		}

		if req.Result == common.Enum_Apply_Alliance_Agree {
			CreaterId, _ := clubmgr.GetAllianceCreaterId(noti.AllianceId)
			clubmgr.AddAllianceMember(noti.AllianceId, CreaterId, noti.ClubId)
		} else {
			clubmgr.DeleteAllianceApplyInfo(req.AllianceId, req.ClubId)
		}
		clubmgr.ModifyAllianceApplyCheckTime(noti.AllianceId, noti.ClubId)

		adminIds, e := clubmgr.GetClubAdmins(noti.ClubId)
		if e == nil && len(adminIds) != 0 {
			for _, adminId := range adminIds {
				player, err := pmgr.GetPlayerFromMap(adminId)
				if nil == err && player != nil && player.Conn != nil {
					common.SendNoti(player, header.RoomID, uint32(adminId), pb.MSGID_MsgID_JoinAlliance_Notice_To_Member, &noti)
					logger.Info("JoinAllianceReplyHandler result uid:%v noti:%+v adminId:%v", header.PlayerID, noti, adminId)
				} else {
					clubmgr.AddAlliancePending(noti, adminId)
				}
			}
		}

		//删除待审批消息
		//clubmgr.DeleteApplyInfo(int(noti.ClubId), int(noti.Uid))
		break
	}

	logger.Info("JoinAllianceReplyHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	resp.Error = int32(err_num)
	SendMessage(player, conn, header, pb.MSGID_MsgID_JoinAlliance_Response_To_Admin, &resp)
}

func AddRemarksHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestAddRemarks) {
	logger.Info("****AddRemarksHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK

	var noti pb.NoticeAddRemarks
	var prs []common.PlayerRemark
	var sigle_remark []common.PlayerRemark
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("GetPlayerFromMap failed! uid:%v error:%v", header.PlayerID, er)
			break
		}

		if remarks := pmgr.GetPlayerRemarksFromDB(int(header.PlayerID)); !strings.EqualFold(remarks, "") {

			err := json.Unmarshal([]byte(remarks), &prs)
			if err != nil {
				err_num = common.Error_JSON_Failed
				logger.Notic("AddRemarksHandler Can't decode json message error:%v", err)
				break
			}
			var exist bool
			exist = false

			for index, remark := range prs {
				if remark.Uid == req.TargetId {
					prs[index].Remarks = req.TagetRemark
					prs[index].Type = req.RemarkType
					exist = true
				}
			}

			if !exist {
				var pr common.PlayerRemark
				pr.Uid = req.TargetId
				pr.Remarks = req.TagetRemark
				pr.Type = req.RemarkType

				prs = append(prs, pr)
			}

			var sr common.PlayerRemark
			sr.Uid = req.TargetId
			sr.Remarks = req.TagetRemark
			sr.Type = req.RemarkType

			sigle_remark = append(sigle_remark, sr)

			remark_string, err := json.Marshal(prs)
			if err != nil {
				err_num = common.Error_JSON_Failed
				logger.Notic("AddRemarksHandler json err:%v", err)
				break
			}

			sigle_remark_string, err := json.Marshal(sigle_remark)
			if err != nil {
				err_num = common.Error_JSON_Failed
				logger.Notic("AddRemarksHandler json err:%v", err)
				break
			}

			noti.TagetRemark = string(sigle_remark_string)

			err_num = pmgr.UpdatePlayerRemarksToDB(int32(header.PlayerID), string(remark_string))
			if err_num != common.Error_OK {
				logger.Notic("UpdatePlayerRemarksToDB Failed! uid:%v remark:%v", header.PlayerID, remark_string)
				break
			}

		} else {
			var pr common.PlayerRemark
			pr.Uid = req.TargetId
			pr.Remarks = req.TagetRemark
			pr.Type = req.RemarkType

			prs = append(prs, pr)
			sigle_remark = append(sigle_remark, pr)

			remark_string, err := json.Marshal(prs)
			if err != nil {
				err_num = common.Error_JSON_Failed
				logger.Notic("AddRemarksHandler json err:%v", err)
				break
			}

			sigle_remark_string, err := json.Marshal(sigle_remark)
			if err != nil {
				err_num = common.Error_JSON_Failed
				logger.Notic("AddRemarksHandler json err:%v", err)
				break
			}

			noti.TagetRemark = string(sigle_remark_string)

			err_num = pmgr.InsertPlayerRemarksToDB(int32(header.PlayerID), string(remark_string))
			if err_num != common.Error_OK {
				logger.Notic("InsertPlayerRemarksToDB Failed! uid:%v remark:%v", header.PlayerID, remark_string)
				break
			}
		}

		break
	}

	logger.Info("AddRemarksHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseAddRemarks
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_AddRemarks_Response, &resp)

	if err_num == common.Error_OK {
		noti.TargetId = req.TargetId
		noti.RemarkType = req.RemarkType
		SendMessage(player, conn, header, pb.MSGID_MsgID_AddRemarks_Notice, &noti)
		logger.Info("AddRemarksHandler result uid:%v noti:%+v", header.PlayerID, noti)
	}
}

func GetAllRemarksHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestGetAllRemarks) {
	logger.Info("****GetAllRemarksHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType
	err_num = common.Error_OK

	var noti pb.NoticeGetAllRemarks
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("GetPlayerFromMap failed uid:%v er:%v", header.PlayerID, er)
			break
		}

		noti.RemarksData = pmgr.GetPlayerRemarksFromDB(int(header.PlayerID))
		break
	}

	logger.Info("GetAllRemarksHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseGetAllRemarks
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_GetAllRemarks_Response, &resp)

	if err_num == common.Error_OK {
		SendMessage(player, conn, header, pb.MSGID_MsgID_GetAllRemarks_Notice, &noti)
		logger.Info("GetAllRemarksHandler result uid:%v noti:%+v", header.PlayerID, noti)
	}
}

func ClearAllianceMaxBuyinLimitHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestClearAllianceMaxBuyinLimit) {
	logger.Info("****ClearAllianceMaxBuyinLimitHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType
	err_num = common.Error_OK

	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v  failed:%v", header.PlayerID, err_num)
			break
		}

		//请求者不是管理员也不是创建者则退出
		if !clubmgr.PlayerHasAlliancePrivilege(header.PlayerID, req.AllianceId) {
			err_num = common.Error_Club_Privilege_Not_Enough
			logger.Notic("has alliance uid:%v  allianceid:%v failed:%v", header.PlayerID, req.AllianceId, err_num)
			break
		}

		//把指定的联盟俱乐部额度上限清零。clubid为-1，清除联盟下所有俱乐部的额度上限
		if !clubmgr.ClearAllianceCurBuyinLimit(req.AllianceId, req.ClubId) {
			err_num = common.Error_DataBase_Failed
			logger.Notic("clear alliance cur buyin limit uid:%v  allianceid:%v clubid:%v failed:%v", header.PlayerID, req.AllianceId, req.ClubId, err_num)
			break
		}

		break
	}

	logger.Info("ClearAllianceMaxBuyinLimitHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseClearAllianceMaxBuyinLimit
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_ClearAllianceMaxBuyinLimit_Response, &resp)
}

func SetAllianceMaxBuyinLimitHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestSetAllianceMaxBuyinLimit) {
	logger.Info("****SetAllianceMaxBuyinLimitHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v  failed:%v", header.PlayerID, err_num)
			break
		}

		//请求者不是管理员也不是创建者则退出
		if !clubmgr.PlayerHasAlliancePrivilege(header.PlayerID, req.AllianceId) {
			err_num = common.Error_Club_Privilege_Not_Enough
			logger.Notic("PlayerHasAlliancePrivilege AllianceId:%v, uid:%v, err_num:%v", req.AllianceId, header.PlayerID, err_num)
			break
		}

		//设置联盟俱乐部额度
		if !clubmgr.SetAllianceMaxBuyinLimit(req.AllianceId, req.ClubId, int(req.Amount)) {
			err_num = common.Error_DataBase_Failed
			logger.Notic("SetAllianceMaxBuyinLimit AllianceId:%v, ClubId:%v, Amount:%v, err_num:%v", req.AllianceId, req.ClubId, req.Amount, err_num)
			break
		}

		break
	}

	logger.Info("SetAllianceMaxBuyinLimitHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseSetAllianceMaxBuyinLimit
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_SetAllianceMaxBuyinLimit_Response, &resp)
}

func SetAllianceControlBuyinHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestSetAllianceControlBuyin) {
	logger.Info("****SetAllianceControlBuyinHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v  failed:%v", header.PlayerID, err_num)
			break
		}

		//请求者不是管理员也不是创建者则退出
		if !clubmgr.PlayerHasAlliancePrivilege(header.PlayerID, req.AllianceId) {
			err_num = common.Error_Club_Privilege_Not_Enough
			logger.Notic("PlayerHasAlliancePrivilege uid:%v failed:%v AllianceId:%v", header.PlayerID, err_num, req.AllianceId)
			break
		}

		//设置联盟俱乐部控制带入
		if !clubmgr.SetAllianceControlBuyin(req.AllianceId, req.ClubId, req.ControlBuyin) {
			err_num = common.Error_DataBase_Failed
			logger.Notic("SetAllianceControlBuyin uid:%v failed:%v AllianceId:%v ClubId:%v ControlBuyin:%v", header.PlayerID, err_num, req.AllianceId, req.ClubId, req.ControlBuyin)
			break
		}

		break
	}

	logger.Info("SetAllianceControlBuyinHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseSetAllianceControlBuyin
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_SetAllianceControlBuyin_Response, &resp)
}

func FairPlayReportHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestFairPlayReport) {
	logger.Info("****FairPlayReportHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK
	var player *common.GamePlayer = nil

	for {
		var er error = nil
		player, er = pmgr.GetPlayerFromMap(header.PlayerID)
		if er != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("get player uid:%v  failed:%v", header.PlayerID, err_num)
			break
		}

		//report
		utils.SendFairPlayReport(header.PlayerID, req.Roomid, req.Clubid, req.RoomUuid, req.GameUuid, req.SuspectUids, req.Contact, req.Detail)

		break
	}

	logger.Info("ResponseFairPlayReport result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseFairPlayReport
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_FairPlay_Report_Response, &resp)
}

func DeviceInfoReportHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestDeviceInfoReport) {
	logger.Info("****DeviceInfoReportHandler header :%+v request:%+v", header, req)

	for {
		//report
		utils.SendDeviceInfoReport(header.PlayerID, conn.RemoteAddr().String(), req.ReportChannel, req.DeviceInfo)
		break
	}
	/*
		logger.Info("ResponseFairPlayReport result uid:%v err_num:%v", header.PlayerID, err_num)

		//返回响应
		var resp pb.ResponseFairPlayReport
		resp.Error = int32(err_num)

		SendMessage(player, conn, header, pb.MSGID_MsgID_FairPlay_Report_Response, &resp)
	*/
}

func JoinClub(req *pb.RequestJoinClub) common.ErrorType {
	logger.Info("****JoinClubHandler  request:%+v", req)
	req.ClubId = common.CodeToId(req.InvitationCode)

	var err_num common.ErrorType = common.Error_OK

	for {
		//club exist?
		if bClubExsit, err := clubmgr.IsClubExsit(req.ClubId); err == nil {
			if !bClubExsit {
				err_num = common.Error_ClubID_Not_Found
				logger.Notic("IsClubExsit uid:%v failed:%v", req.ClubUid, err_num)
				break
			}
		} else {
			err_num = common.Error_OperateDB_Failed
			logger.Notic("IsClubExsit uid:%v failed:%v", req.ClubUid, err_num)
			break
		}

		if exist, _ := clubmgr.IsPlayerInClub(req.ClubId, req.ClubUid); exist {
			err_num = common.Error_Already_In_Club
			logger.Notic("IsPlayerInClub uid:%v clubid:%v err_num:%v", req.ClubUid, req.ClubId, err_num)
			break
		}

		if exist, _ := clubmgr.IsPlayerAlreadyApply(req.ClubId, req.ClubUid); exist { //Must modify if we have chance
			err_num = common.Error_Already_Apply_Club
			logger.Notic("IsPlayerAlreadyApply uid:%v clubid:%v err_num:%v", req.ClubUid, req.ClubId, err_num)
			break
		}

		//公共俱乐部
		var Type int
		var err error = nil
		if Type, err = clubmgr.GetClubType(req.ClubId); err == nil && Type == common.Enum_Club_Public {
			clubmgr.AddClubMember(req.ClubId, req.ClubUid)
			clubmgr.ModifyClubCurrentMemberNum(req.ClubId, 1)
			break
		}

		if len(req.InvitationCode) != 0 {
			//club_id := common.CodeToId(req.InvitationCode)
			if clubmgr.IsClubTotalPlayerFull(req.ClubId) {
				err_num = common.Error_Club_FULL
				logger.Notic("IsClubTotalPlayerFull uid:%v clubid:%v err_num:%v", req.ClubUid, req.ClubId, err_num)
			} else {
				clubmgr.AddClubMember(req.ClubId, req.ClubUid)
				clubmgr.ModifyClubCurrentMemberNum(req.ClubId, 1)
			}
			break
		}

		break
	}

	logger.Info("JoinClub result uid:%v err_num:%v", req.ClubUid, err_num)

	return err_num
}

func GetIncomeHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestGetIncome) {
	logger.Info("****GetIncomeHandler header :%+v request:%+v", header, req)

	var err_num common.ErrorType = common.Error_OK

	var noti pb.NoticeGetIncome
	var player *common.GamePlayer = nil
	var cc_info *common.ClubCreaterIncomeInfo
	var ac_info *common.AlliCreaterIncomeInfo
	var err error = nil

	for {

		player, err = pmgr.GetPlayerFromMap(header.PlayerID)
		if err != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("GetPlayerFromMap failed! uid:%v error:%v", header.PlayerID, err)
			break
		}

		db.CheckAndLoadClubIncome(uint32(header.PlayerID))

		cc_info, err = db.GetClubIncome(int(header.PlayerID))
		if err != nil {
			//glog.Info("GetClubIncome from db error:", err, " uid:", resp.UID)
			err_num = common.Error_OperateDB_Failed
			break
		}

		db.CheckAndLoadAlliIncome(header.PlayerID)
		ac_info, err = db.GetAlliIncome(int(header.PlayerID))
		if err != nil {
			err_num = common.Error_OperateDB_Failed
			break
		}

		break
	}

	logger.Info("AddRemarksHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseGetIncome
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_GetIncome_Response, &resp)

	if cc_info != nil {
		noti.ClubFee = cc_info.Fee
		noti.ClubInsurance = cc_info.Insurance
		noti.ClubJackpot = cc_info.Jackpot
	}

	if ac_info != nil {
		noti.AlliFee = ac_info.Fee
		noti.AlliInsurance = ac_info.Insurance
		noti.AlliJackpot = ac_info.Jackpot
	}

	if err_num == common.Error_OK {
		SendMessage(player, conn, header, pb.MSGID_MsgID_GetIncome_Notice, &noti)
		logger.Info("GetIncomeHandler result uid:%v noti:%+v", header.PlayerID, noti)
	}
}

func GetUserClubGrantInfoHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestGetUserClubGrantInfo) {
	logger.Info("****GetUserClubGrantInfoHandler header :%+v request:%+v", header, req)
	board_begin_ts := time.Now().Unix()
	logger.Debug("GetUserClubGrantInfoHandler begin uid:%v ts:%v", header.PlayerID, board_begin_ts)

	var err_num common.ErrorType = common.Error_OK

	var noti pb.NoticeGetUserClubGrantInfo
	var toList []*pb.TransferToOtherInfo
	var getList []*pb.TransferToOtherInfo
	var player *common.GamePlayer = nil
	var err error = nil

	for {
		player, err = pmgr.GetPlayerFromMap(header.PlayerID)
		if err != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("GetPlayerFromMap failed! uid:%v error:%v", header.PlayerID, err)
			break
		}

		toList, err = db.GetClubGrantToList(req.Uid)
		if err != nil {
			err_num = common.Error_DataBase_Failed
			logger.Notic("db GetClubGrantToList failed! uid:%v error:%v", header.PlayerID, err)
		}

		getList, err = db.GetClubGrantGetList(req.Uid)
		if err != nil {
			err_num = common.Error_DataBase_Failed
			logger.Notic("db GetClubGrantGetList failed! uid:%v error:%v", header.PlayerID, err)
		}

		break
	}

	logger.Info("AddRemarksHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseGetUserClubGrantInfo
	resp.Error = int32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_GetUserClubGrantInfo_Response, &resp)

	logger.Info("GetUserClubGrantInfoHandler !!!!!!err_num:", err_num)

	if err_num == common.Error_OK {
		noti.ToList = append(noti.ToList, toList...)
		noti.GetList = append(noti.GetList, getList...)
		SendMessage(player, conn, header, pb.MSGID_MsgID_GetUserClubGrantInfo_Notice, &noti)
		logger.Debug("send MSGID_MsgID_GetUserClubGrantInfo_Notice uid:%v ts:%v", header.PlayerID, time.Now().Unix()-board_begin_ts)
		logger.Info("7 MSGID_MsgID_ClubCurrentBoard_Notice uid:%v toList:%v getList:%v", player.UID, noti.ToList, noti.GetList)
	}
}

func GetUserMailListHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestGetUserMailList) {
	logger.Info("****GetUserMailListHandler header :%+v request:%+v", header, req)
	board_begin_ts := time.Now().Unix()
	logger.Debug("GetUserMailListHandler begin uid:%v ts:%v", header.PlayerID, board_begin_ts)

	var err_num common.ErrorType = common.Error_OK
	var noti pb.NoticeGetUserMailList
	var mailList []*pb.MailInfo
	var player *common.GamePlayer = nil
	var err error = nil
	var UserLastFetchMailTime uint32

	for {
		player, err = pmgr.GetPlayerFromMap(header.PlayerID)
		if err != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("GetPlayerFromMap failed! uid:%v error:%v", header.PlayerID, err)
			break
		}

		//取出玩家最后一次点击邮件时间
		logger.Info("GetUserMailListHandler 13.1 before get userlastfetchmailtime  uid:%v seq:%v", header.PlayerID, header.Seq)
		if UserLastFetchMailTime, err = mail.LoadUserFetchSysMailTime(header.PlayerID); err != nil {
			err_num = common.Error_REDIS_Failed
			logger.Notic("player uid:%v mail.LoadUserFetchSysMailTime:%v ", header.PlayerID, err_num)
			break
		}

		//取出玩家个人邮件列表 并且加载系统邮件
		logger.Info("GetUserMailListHandler 13.2 before get mail info  uid:%v seq:%v", header.PlayerID, header.Seq)
		if mailList, err = mail.HandleAndGetUserMail(header.PlayerID, UserLastFetchMailTime); err != nil {
			err_num = common.Error_GetUserMailList_Failed
			logger.Notic("player uid:%v mail.HandleAndGetUserMail:%v ", header.PlayerID, err_num)
			break
		}

		//验证索引
		if req.MailBeginIndex > req.MailEndIndex {
			err_num = common.Error_MailIndex_Not_Legal
			logger.Notic("player uid:%v mail.index failed:%v ", header.PlayerID, err_num)
			break
		}

		//此时需要重置一下时间标签
		err = mail.SaveUserFetchSysMailTime(header.PlayerID, uint32(time.Now().Unix()))
		if err != nil {
			err_num = common.Error_REDIS_Failed
			logger.Notic("player uid:%v SaveUserFetchSysMailTime  failed:%v ", header.PlayerID, err_num)
			break
		}
		break
	}

	logger.Info("AddRemarksHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseGetUserMailList
	resp.Error = uint32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_GetUserMailListInfo_Response, &resp)

	logger.Info("GetUserMailListHandler !!!!!!err_num:", err_num)

	if err_num == common.Error_OK {
		for {
			if req.MailBeginIndex > uint32(len(mailList)) {
				noti.MailList = append(noti.MailList, mailList...)
				break
			}

			if req.MailBeginIndex <= uint32(len(mailList)) && req.MailEndIndex > uint32(len(mailList)) {
				noti.MailList = append(noti.MailList, mailList[req.MailBeginIndex:]...)
				break
			}

			if req.MailBeginIndex <= uint32(len(mailList)) && req.MailEndIndex <= uint32(len(mailList)) {
				noti.MailList = append(noti.MailList, mailList[req.MailBeginIndex:req.MailEndIndex]...)
				break
			}

			logger.Notic("MailBeginIndex:%v MailEndIndex:%v wrong!", req.MailBeginIndex, req.MailEndIndex)
			break
		}

		SendMessage(player, conn, header, pb.MSGID_MsgID_GetUserMailListInfo_Notice, &noti)
		logger.Debug("send MSGID_MsgID_GetUserMailListInfo_Notice uid:%v ts:%v", header.PlayerID, time.Now().Unix()-board_begin_ts)
		logger.Info("7 MSGID_MsgID_GetUserMailListInfo_Notice uid:%v maillist:%v getList:%v", player.UID, noti.MailList)
	}

}

func FetchOneMailHandler(conn net.Conn, header pb.MessageHeader, req *pb.RequestFetchOneMail) {
	logger.Info("****FetchOneMailHandler header :%+v request:%+v", header, req)
	board_begin_ts := time.Now().Unix()
	logger.Debug("FetchOneMailHandler begin uid:%v ts:%v", header.PlayerID, board_begin_ts)

	var err_num common.ErrorType = common.Error_OK
	var noti pb.NoticeFetchOneMail
	var onemail *pb.MailInfo
	var player *common.GamePlayer = nil
	var err error = nil
	for {
		player, err = pmgr.GetPlayerFromMap(header.PlayerID)
		if err != nil {
			err_num = common.Error_Player_Not_Found
			logger.Notic("GetPlayerFromMap failed! uid:%v error:%v", header.PlayerID, err)
			break
		}

		onemail, err = mail.ModifyMailInfo(header.PlayerID, req.MailId)
		if err != nil {
			err_num = common.Error_REDIS_Failed
			logger.Notic("FetchOneMailHandler failed! uid:%v error:%v", header.PlayerID, err)
			break
		}
		break

	}
	logger.Info("FetchOneMailHandler result uid:%v err_num:%v", header.PlayerID, err_num)

	//返回响应
	var resp pb.ResponseFetchOneMail
	resp.Error = uint32(err_num)

	SendMessage(player, conn, header, pb.MSGID_MsgID_ReadAndFetchOneMail_Response, &resp)

	if err_num == common.Error_OK {
		noti.Onemail = new(pb.MailInfo)
		noti.Onemail.MailId = onemail.MailId
		noti.Onemail.MailExpiredtime = onemail.MailExpiredtime
		noti.Onemail.MailSendtime = onemail.MailSendtime
		noti.Onemail.MailTitle = onemail.MailTitle
		noti.Onemail.MailSenderId = onemail.MailSenderId
		noti.Onemail.MailInscribe = onemail.MailInscribe
		noti.Onemail.MailContent = onemail.MailContent
		noti.Onemail.MailAppelaction = onemail.MailAppelaction
		noti.Onemail.MailState = onemail.MailState
		noti.Onemail.MailType = onemail.MailType
		noti.Onemail.Isexpired = onemail.Isexpired
		noti.Onemail.AttachmentList = append(noti.Onemail.AttachmentList, onemail.AttachmentList...)

		SendMessage(player, conn, header, pb.MSGID_MsgID_ReadAndFetchOneMail_Notice, &noti)
		logger.Debug("send MSGID_MsgID_ReadAndFetchOneMail_Notice uid:%v ts:%v", header.PlayerID, time.Now().Unix()-board_begin_ts)
		logger.Info("7 MSGID_MsgID_ReadAndFetchOneMail_Notice uid:%v maillist:%v Onemail:%v", player.UID, noti.Onemail)
	}

}
