group_power.go 46.3 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7
package group_power_r

import (
	"context"
	"fmt"
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/mycontext"
chenweijian's avatar
chenweijian committed
8
	"git.hilo.cn/hilo-common/resource/config"
hujiebin's avatar
hujiebin committed
9 10
	"git.hilo.cn/hilo-common/resource/mysql"
	"git.hilo.cn/hilo-common/resource/redisCli"
chenweijian's avatar
chenweijian committed
11 12
	"git.hilo.cn/hilo-common/sdk/aws"
	"git.hilo.cn/hilo-common/sdk/tencentyun"
chenweijian's avatar
chenweijian committed
13
	"git.hilo.cn/hilo-common/txop/msg"
hujiebin's avatar
hujiebin committed
14 15
	"git.hilo.cn/hilo-common/utils"
	"github.com/gin-gonic/gin"
chenweijian's avatar
chenweijian committed
16
	"github.com/jinzhu/now"
hujiebin's avatar
hujiebin committed
17 18 19 20
	"hilo-group/_const/enum/groupPower_e"
	"hilo-group/_const/enum/group_e"
	"hilo-group/_const/enum/msg_e"
	"hilo-group/_const/redis_key"
chenweijian's avatar
chenweijian committed
21
	"hilo-group/common"
hujiebin's avatar
hujiebin committed
22 23 24 25 26
	"hilo-group/cv/group_cv"
	"hilo-group/cv/group_power_cv"
	"hilo-group/cv/medal_cv"
	"hilo-group/cv/user_cv"
	"hilo-group/domain/cache/res_c"
chenweijian's avatar
chenweijian committed
27
	"hilo-group/domain/cache/user_c"
hujiebin's avatar
hujiebin committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
	"hilo-group/domain/model/game_m"
	"hilo-group/domain/model/groupPower_m"
	"hilo-group/domain/model/group_m"
	"hilo-group/domain/model/res_m"
	"hilo-group/domain/model/rocket_m"
	"hilo-group/domain/model/user_m"
	"hilo-group/domain/service/group_power_s"
	"hilo-group/domain/service/group_s"
	"hilo-group/myerr"
	"hilo-group/myerr/bizerr"
	"hilo-group/req"
	"hilo-group/resp"
	"sort"
	"strconv"
	"strings"
	"time"
)

// @Tags 国家势力
// @Summary 加入国家势力
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param groupPowerId formData int true "国家势力Id"
// @Success 200
// @Router /v1/groupPower/user [post]
func GroupPowerJoin(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	groupPowerId, err := strconv.ParseUint(c.PostForm("groupPowerId"), 10, 64)
	if err != nil {
		return myContext, err
	}
	//获取用户
	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
	if err := group_power_s.NewGroupPowerService(myContext).GroupPowerUserJoin(groupPowerId, userId); err != nil {
		return myContext, err
	}
	resp.ResponseOk(c, nil)
	return myContext, nil
}

// @Tags 国家势力
// @Summary 退出国家势力
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param groupPowerId path int true "国家势力ID"
// @Success 200
// @Router /v1/groupPower/user/{groupPowerId} [delete]
func GroupPowerLeave(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	groupPowerId, err := strconv.ParseUint(c.Param("groupPowerId"), 10, 64)
	if err != nil {
		return myContext, err
	}
	//获取用户
	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
	remainSeconds, err := group_power_s.NewGroupPowerService(myContext).GroupPowerUserLeave(groupPowerId, userId)
	if err != nil {
		if remainSeconds == 0 {
			return myContext, err
		}

		model := domain.CreateModelContext(myContext)

		user, newErr := user_m.GetUser(model, userId)
		if newErr != nil {
			return myContext, newErr
		} else if user == nil {
			return myContext, err
		} else {
			text := res_m.ResMultiText{MsgId: msg_e.MSG_ID_GROUP_LEAVE_POWER, Language: user.Language}
			if text.Get(model.Db) == nil {
				dayLimit := "0"
				day, sTime := formatSeconds(remainSeconds)
				sDay := fmt.Sprintf("%d", day)
				errmsg := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(text.Content, "%d", dayLimit), "%s", sDay), "xx:xx:xx", sTime)
				return myContext, myerr.NewBusinessCodeNoCheck(bizerr.GroupPowerStayTooShort.GetCode(), errmsg, myerr.BusinessData{})
			} else {
				return myContext, err
			}
		}
	}
	resp.ResponseOk(c, nil)
	return myContext, nil
}

func formatSeconds(seconds int) (int, string) {
	sec := seconds % 60
	minute := seconds / 60
	hour := minute / 60
	minute %= 60
	day := hour / 24
	hour %= 24
	sTime := fmt.Sprintf("%02d:%02d:%02d", hour, minute, sec)
	return day, sTime
}

// @Tags 国家势力
// @Summary 国家势力标题页
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param groupPowerId path int true "国家势力ID"
hujiebin's avatar
hujiebin committed
138
// @Success 200 {object} group_cv.GroupPowerTitle
hujiebin's avatar
hujiebin committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
// @Router /v1/groupPower/title/{groupPowerId} [get]
func GetGroupPowerTitle(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	groupPowerId, err := strconv.ParseUint(c.Param("groupPowerId"), 10, 64)
	if err != nil {
		return myContext, err
	}

	myUserId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}

	model := domain.CreateModelContext(myContext)

	groupPower, err := groupPower_m.GetGroupPower(model, groupPowerId)
	if err != nil {
		return myContext, err
	}

	if groupPower == nil {
		return myContext, bizerr.GroupPowerNotExist
	}

	gi, err := group_m.GetGroupInfo(model, groupPower.GroupUid)
	if err != nil {
		return myContext, err
	}
	if gi == nil {
		return myContext, bizerr.GroupNotFound
	}
	gpu := groupPower_m.GroupPowerUser{GroupPowerId: groupPowerId}
	count, err := gpu.GetCount(model.Db)
	if err != nil {
		return myContext, err
	}

	gpu = groupPower_m.GroupPowerUser{GroupPowerId: groupPowerId, Role: groupPower_e.GroupPowerUserRoleMgr}
	records, err := gpu.Get(model.Db)
	if err != nil {
		return myContext, err
	}
	if len(records) != 1 {
		return myContext, bizerr.GroupPowerNoOwner
	}
	owner := records[0].UserId
	userIds := []uint64{owner}

	assistants, err := group_m.FindRolesInGroup(model.Db, groupPower.GroupUid, group_e.GROUP_ADMIN)
	if err != nil {
		return myContext, err
	}

	userIds = append(userIds, assistants...)
	users, err := user_cv.GetUserBaseMap(userIds, myUserId)
	if err != nil {
		return myContext, err
	}

	result := group_cv.GroupPowerTitle{
		Id:        groupPowerId,
		Name:      gi.Name,
		GroupId:   gi.TxGroupId,
		Avatar:    gi.FaceUrl,
		MemberNum: count,
	}

	if users[owner] != nil {
		result.Owner = *users[owner]
	}

	// FIXME:排序规则是什么?
	for _, i := range assistants {
		if users[i] != nil {
			result.Assistants = append(result.Assistants, *users[i])
		}
	}

	if len(result.Assistants) > 4 {
		result.Assistants = result.Assistants[0:4]
	}

	gp, err := groupPower_m.GetGroupPowerUserOrNil(model, myUserId)
	if err != nil {
		return myContext, err
	}
	if gp != nil && gp.GroupPowerId == groupPowerId {
		result.IsMyGroupPower = true
	} else {
		result.IsMyGroupPower = false
	}

	resp.ResponseOk(c, result)
	return myContext, nil
}

// @Tags 国家势力
// @Summary 国家势力成员群组
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param pageSize query int false "分页大小 默认:10" default(10)
// @Param pageIndex query int false "第几个分页,从1开始 默认:1" default(1)
// @Param groupPowerId path int true "国家势力ID"
hujiebin's avatar
hujiebin committed
243
// @Success 200 {object} group_cv.PopularGroupInfo
hujiebin's avatar
hujiebin committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
// @Router /v1/groupPower/group/{groupPowerId} [get]
func GetGroupPowerGroups(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	myUserId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}

	pageSize, err := strconv.Atoi(c.Query("pageSize"))
	if err != nil || pageSize <= 0 {
		pageSize = 10
	}
	pageIndex, err := strconv.Atoi(c.Query("pageIndex"))
	if err != nil || pageIndex <= 0 {
		pageIndex = 1
	}

	groupPowerId, err := strconv.ParseUint(c.Param("groupPowerId"), 10, 64)
	if err != nil {
		return myContext, err
	}

	model := domain.CreateModelContext(myContext)

	groupPower, err := groupPower_m.GetGroupPower(model, groupPowerId)
	if err != nil {
		return myContext, err
	}

	if groupPower == nil {
		return myContext, bizerr.GroupPowerNotExist
	}

	gpu := groupPower_m.GroupPowerUser{GroupPowerId: groupPowerId}
	records, err := gpu.Get(model.Db)
	if err != nil {
		return myContext, err
	}
	members := make([]uint64, 0)
	for _, i := range records {
		members = append(members, i.UserId)
	}
	groupMap, err := group_m.FindGroupByOwners(model.Db, members)
	if err != nil {
		return myContext, err
	}

	groupList := make([]*group_m.GroupInfo, 0)
	groupIds := make([]string, 0)
	visitCount := make(map[string]int64, 0)
	for _, i := range members {
		if g, ok := groupMap[i]; ok {
			groupList = append(groupList, &g)
			groupIds = append(groupIds, g.ImGroupId)
			if count, err := group_m.GetRoomVisitCount(g.ImGroupId); err == nil {
				visitCount[g.ImGroupId] = count
			}
		}
	}
	model.Log.Infof("GetGroupPowerGroups, members: %v, groupMap: %v, groupList %v", members, groupMap, groupList)

	// 获取麦上有人的所有群组
	micGroupList, err := group_m.GetMicHasInGroups()
	if err != nil {
		return myContext, err
	}
	micGroupMap := make(map[string]bool, 0)
	for _, i := range micGroupList {
		micGroupMap[i] = true
	}

	supportLevels, err := group_s.NewGroupService(myContext).GetWeekMaxSupportLevelMap()
	if err != nil {
		return myContext, err
	}

	roomMicUserMap, err := group_m.BatchGetAllMicUser(model, groupIds)
	if err != nil {
		return myContext, err
	}
	model.Log.Infof("GetGroupPowerGroups, roomMicUserMap : %v", roomMicUserMap)

	sort.Slice(groupList, func(i, j int) bool {
		gi := groupList[i].ImGroupId
		gj := groupList[j].ImGroupId
		if micGroupMap[gi] == true && micGroupMap[gj] == false {
			return true
		} else if micGroupMap[gi] == false && micGroupMap[gj] == true {
			return false
		}
		if supportLevels[gi] > supportLevels[gj] {
			return true
		} else if supportLevels[gi] < supportLevels[gj] {
			return false
		}
		if len(roomMicUserMap[gi]) > len(roomMicUserMap[gj]) {
			return true
		} else if len(roomMicUserMap[gi]) < len(roomMicUserMap[gj]) {
			return false
		}
		if visitCount[gi] > visitCount[gj] {
			return true
		} else if visitCount[gi] < visitCount[gj] {
			return false
		}

		// * Final resort: 群组CODE,短号优先,然后按字母序
		return len(groupList[i].Code) < len(groupList[j].Code) || len(groupList[i].Code) == len(groupList[j].Code) && groupList[i].Code < groupList[j].Code
	})

	// for pretty log
	// ^ 麦上有人
	//logstr := ""
	//for _, i := range groupList {
	//hotGroupList = append(hotGroupList, groups[i])
	//prefix := " "
	//if len(roomMicUserMap[i.ImGroupId]) > 0 {
	//	prefix += "^"
	//}
	//logstr += prefix + i.ImGroupId + ":" + i.Code + ":" + strconv.Itoa(int(supportLevels[i.ImGroupId])) +
	//	":" + strconv.Itoa(len(roomMicUserMap[i.ImGroupId])) + ":" + strconv.Itoa(int(visitCount[i.ImGroupId]))
	//}
	total := len(groupList)
	model.Log.Infof("GetGroupPowerGroups: GroupList size = %d", total)

	result := make([]group_cv.PopularGroupInfo, 0)

	beginPos := pageSize * (pageIndex - 1)
	endPos := pageSize * pageIndex
	if beginPos < total {
		if endPos > total {
			endPos = total
		}

		groupIds := make([]string, 0)
		owners := make([]uint64, 0)
		for _, i := range groupList[beginPos:endPos] {
			groupIds = append(groupIds, i.ImGroupId)
			owners = append(owners, i.Owner)
		}
385
		powerIds, powerNames, powerNameplates, powerGrades, err := group_power_cv.BatchGetGroupPower(model.Db, owners)
hujiebin's avatar
hujiebin committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
		if err != nil {
			return myContext, err
		}
		groupMedals, err := group_m.BatchGetMedals(model.Db, groupIds)
		if err != nil {
			return myContext, err
		}
		resMedal, err := res_m.MedalGetAllMap(model.Db)
		if err != nil {
			return myContext, err
		}

		model.Log.Infof("GetGroupPowerGroups: final start = %d, end = %d, %v", beginPos, endPos, groupIds)

		/*		txGroupInfoMap, err := cv.BatchGetGroupInfo(model, groupIds, false)
				if err != nil {
					return myContext, err
				}*/

		countryInfo, err := res_c.GetCountryIconMap(model)
		if err != nil {
			return myContext, err
		}

		uids := make([]uint64, 0)
		micUsersMap := make(map[string][]uint64, 0)
		for _, i := range groupList[beginPos:endPos] {
			// 规则:麦上够4个就全用;全空的话,用群主补
			u := roomMicUserMap[i.ImGroupId]
			if len(u) >= 4 {
				micUsersMap[i.ImGroupId] = u[0:4]
			} else if len(u) > 0 {
				micUsersMap[i.ImGroupId] = u
			} else {
				micUsersMap[i.ImGroupId] = []uint64{i.Owner}
			}
			uids = append(uids, micUsersMap[i.ImGroupId]...)
		}

		uids = utils.UniqueSliceUInt64(uids)
		userTiny, err := user_cv.GetUserTinyMap(uids)
		if err != nil {
			return myContext, err
		}

		rr := rocket_m.RocketResult{}
		maxStageMap, err := rr.GetMaxStage(mysql.Db, groupIds)
		if err != nil {
			return myContext, err
		}

		roomCount, err := group_m.BatchGetRoomCount(model, groupIds)
		if err != nil {
			return nil, err
		}
		// 正在进行的游戏
		games := game_m.GetNotEndGamesMap(model)

		for _, i := range groupList[beginPos:endPos] {
			micUsers := make([]user_cv.CvUserTiny, 0)
			for _, j := range micUsersMap[i.ImGroupId] {
				micUsers = append(micUsers, userTiny[j])
			}

			var maxStage *uint16 = nil
			if s, ok := maxStageMap[i.ImGroupId]; ok {
				maxStage = &s
			}

			medals := make([]medal_cv.PicElement, 0)
			if m, ok := groupMedals[i.ImGroupId]; ok {
				for _, j := range m {
					mId := uint32(j)
					if e, ok := resMedal[mId]; ok {
						medals = append(medals, medal_cv.PicElement{
							PicUrl: e.PicUrl,
						})
					}
				}
			}
			// 补上房间流水勋章
			var pe *medal_cv.PicElement
			_, pe, err = medal_cv.GetGroupConsumeMedal(model, i.ImGroupId)
			if err != nil {
				model.Log.Infof("GetGroupPowerGroups: GetGroupConsumeMedal: %s", err.Error())
			} else if pe != nil {
				medals = append(medals, medal_cv.PicElement{PicUrl: pe.PicUrl})
			}

			var password *string = nil
			if len(i.Password) > 0 && i.Owner != myUserId {
				emptyStr := ""
				password = &emptyStr
			}

			result = append(result, group_cv.PopularGroupInfo{
				GroupInfo: group_cv.GroupInfo{
					GroupBasicInfo: group_cv.GroupBasicInfo{
						GroupId:             i.TxGroupId,
						Name:                i.Name,
						Introduction:        i.Introduction,
						Notification:        i.Notification,
						FaceUrl:             i.FaceUrl,
						Code:                i.Code,
						CountryIcon:         countryInfo[i.Country],
						Password:            password,
						SupportLevel:        supportLevels[i.ImGroupId],
						GroupInUserDuration: visitCount[i.ImGroupId],
						MicNumType:          int(i.MicNumType),
						GroupMedals:         medals,
					},
hujiebin's avatar
hujiebin committed
497 498 499 500
					HasOnMic:            len(roomMicUserMap[i.ImGroupId]) > 0,
					GroupPowerId:        powerIds[i.Owner],
					GroupPowerName:      powerNames[i.Owner],
					GroupPowerNameplate: powerNameplates[i.Owner],
501 502 503 504 505 506
					GroupPower: group_cv.GroupPower{
						Id:        powerIds[i.Owner],
						Name:      powerNames[i.Owner],
						Nameplate: powerNameplates[i.Owner],
						Grade:     powerGrades[i.Owner],
					},
hujiebin's avatar
hujiebin committed
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
				},
				MicUsers:      micUsers,
				RoomUserCount: uint(roomCount[i.ImGroupId]),
				MaxStage:      maxStage,
				GameTypes:     games[i.TxGroupId],
			})
		}
	}

	resp.ResponseOk(c, result)
	return myContext, nil
}

// @Tags 国家势力
// @Summary 国家势力团队信息
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param groupPowerId query int true "国家势力ID"
hujiebin's avatar
hujiebin committed
525
// @Success 200 {object} group_power_cv.CvGroupPowerTeam
hujiebin's avatar
hujiebin committed
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
// @Router /v1/groupPower/team [get]
func GroupPowerTeam(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	groupPowerId, err := strconv.ParseUint(c.Query("groupPowerId"), 10, 64)
	if err != nil {
		return myContext, err
	}
	usreId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
	cvGroupPowerTeam, err := group_power_cv.GetCvGroupPowerTeam(myContext, groupPowerId, usreId)
	if err != nil {
		return myContext, err
	}
	resp.ResponseOk(c, cvGroupPowerTeam)
	return myContext, nil
}

// @Tags 国家势力
// @Summary 榜单排行榜,这周
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param type query int true "week:1:thisWeek 2:lastWeek" Enums(1,2)
// @Param pageSize query int true "分页大小 默认:10" default(10)
// @Param pageIndex query int true "第几个分页,从1开始 默认:1" default(1)
hujiebin's avatar
hujiebin committed
552
// @Success 200 {object} group_power_cv.CvGroupPowerDiamondTotal
hujiebin's avatar
hujiebin committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
// @Router /v1/groupPower/billboard/week [get]
func GroupPowerBillboardWeek(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	pageSize, err := strconv.Atoi(c.Query("pageSize"))
	if err != nil {
		pageSize = 10
	}
	pageIndex, err := strconv.Atoi(c.Query("pageIndex"))
	if err != nil {
		pageIndex = 1
	}
	t, err := strconv.ParseUint(c.Query("type"), 10, 64)
	if err != nil {
		return myContext, err
	}
	now := time.Now()
	monday := utils.GetMonday(now)
	midnight := time.Date(monday.Year(), monday.Month(), monday.Day(), 0, 0, 0, 0, time.Local)
	var beginTime, endTime time.Time
	if t == 1 {
		endTime = now
		beginTime = midnight
	} else if t == 2 {
		endTime = midnight
		beginTime = midnight.AddDate(0, 0, -7)
	} else {
		return myContext, myerr.NewSysError("type 参数错误")
	}
	cvGroupPowerDiamondTotals, err := group_power_cv.GetCvGroupPowerDiamondTotalList(beginTime, endTime, pageSize, pageIndex)
	if err != nil {
		return myContext, err
	}

	ids := make([]uint64, 0, len(cvGroupPowerDiamondTotals))
	for i, _ := range cvGroupPowerDiamondTotals {
		ids = append(ids, cvGroupPowerDiamondTotals[i].GroupPowerId)
	}

	userMap, err := group_power_cv.GetCvGroupPowerUserMapN(ids)
	if err != nil {
		return myContext, nil
	}

	for i, _ := range cvGroupPowerDiamondTotals {
		cvGroupPowerDiamondTotals[i].UserN = userMap[cvGroupPowerDiamondTotals[i].GroupPowerId]
	}

	resp.ResponseOk(c, cvGroupPowerDiamondTotals)
	return myContext, nil
}

type ReturnGroupPowerBillboardOwnerWeek struct {
	User    user_cv.CvUserDetail `json:"user"`
	Diamond uint                 `json:"diamond"`
}

// @Tags 国家势力
// @Summary 榜单排行榜,这周,上周,top3,势力主的信息
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param type query int true "week:1:thisWeek 2:lastWeek" Enums(1,2)
// @Success 200 {object} ReturnGroupPowerBillboardOwnerWeek
// @Router /v1/groupPower/billboard/owner/week [get]
func GroupPowerBillboardOwnerWeek(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
	t, err := strconv.ParseUint(c.Query("type"), 10, 64)
	if err != nil {
		return myContext, err
	}
	now := time.Now()
	monday := utils.GetMonday(now)
	midnight := time.Date(monday.Year(), monday.Month(), monday.Day(), 0, 0, 0, 0, time.Local)
	//var beginTime, endTime time.Time
	var beginTime time.Time
	if t == 1 {
		//endTime = now
		beginTime = midnight
	} else if t == 2 {
		//endTime = midnight
		beginTime = midnight.AddDate(0, 0, -7)
	} else {
		return myContext, myerr.NewSysError("type 参数错误")
	}

	type R struct {
		DiamondNum uint
		UserId     uint64
	}
	rs := []R{}
	//fixme:解决性能问题.
	/*	if err := mysql.Db.Raw("SELECT SUM(l.diamond_num) AS diamond_num, (SELECT u.user_id from group_power_user u where u.group_power_id = l.group_power_id and u.role = ?) as user_id  FROM group_power_diamond_log l, group_power p WHERE l.group_power_id = p.id and p.status = ? and l.created_time >= ? AND l.created_time < ? GROUP BY l.group_power_id ORDER BY diamond_num DESC LIMIT 3", groupPower_m2.GroupPowerUserRoleMgr, groupPower_m2.GroupPowerUserHas, beginTime, endTime).Scan(&rs).Error; err != nil {
		return myContext, err
	}*/
	//用缓存
	rows, err := redisCli.GetRedis().ZRevRangeWithScores(context.Background(), redis_key.GetGroupPowerDiamondLogWeek(beginTime.Format(utils.COMPACT_DATE_FORMAT)), 0, -1).Result()
	if err != nil {
		return nil, myerr.WrapErr(err)
	}
	groupPowerIds := make([]uint64, 0, len(rows))
	for i, _ := range rows {
		groupPowerId, err := strconv.ParseUint(rows[i].Member.(string), 10, 64)
		if err != nil {
			return nil, myerr.WrapErr(err)
		}
		groupPowerIds = append(groupPowerIds, groupPowerId)
	}
	//搜集所有的群组(有效) + 群组管理人
	groupPowerUsers := []groupPower_m.GroupPowerUser{}
	if err := mysql.Db.Raw("SELECT u.user_id, u.group_power_id FROM group_power_user u, group_power p WHERE u.group_power_id = p.id AND u.role = ? and p.status = ? and p.id in (?)", groupPower_e.GroupPowerUserRoleMgr, groupPower_e.GroupPowerUserHas, groupPowerIds).Scan(&groupPowerUsers).Error; err != nil {
		return nil, myerr.WrapErr(err)
	}
	//转换成map
	groupPowerIdUserIdMap := map[uint64]uint64{}
	for _, r := range groupPowerUsers {
		groupPowerIdUserIdMap[r.GroupPowerId] = r.UserId
	}
	//只需找到前3个
	for i, _ := range rows {
		groupPowerId, err := strconv.ParseUint(rows[i].Member.(string), 10, 64)
		if err != nil {
			return nil, myerr.WrapErr(err)
		}
		if len(rs) >= 3 {
			break
		} else if userId, flag := groupPowerIdUserIdMap[groupPowerId]; flag {
			rs = append(rs, R{
				DiamondNum: uint(rows[i].Score),
				UserId:     userId,
			})
		}
	}

	userIds := make([]uint64, 0, 64)
	for i, _ := range rs {
		userIds = append(userIds, rs[i].UserId)
	}

	userMap, err := user_cv.GetUserDetailMap(userIds, userId)
	if err != nil {
		return myContext, err
	}

	results := make([]ReturnGroupPowerBillboardOwnerWeek, 0, len(userIds))
	for i, _ := range rs {
		results = append(results, ReturnGroupPowerBillboardOwnerWeek{
			User:    *userMap[rs[i].UserId],
			Diamond: rs[i].DiamondNum,
		})
	}
	resp.ResponseOk(c, results)
	return myContext, nil
}
chenweijian's avatar
chenweijian committed
709 710 711 712 713 714 715 716

// @Tags 家族
// @Summary 家族信息
// @Param id query int true "家族id"
// @Success 200 {object} group_power_cv.GroupPowerInfo
// @Router /v1/groupPower/info [get]
func GroupPowerInfo(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
chenweijian's avatar
chenweijian committed
717 718 719 720
	myUserId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
721 722 723 724 725 726 727 728
	familyId, err := strconv.ParseUint(c.Query("id"), 10, 64)
	if err != nil {
		return myContext, err
	}
	model := domain.CreateModelContext(myContext)
	gp := &groupPower_m.GroupPower{Entity: mysql.Entity{ID: familyId}}
	gpInfo, err := gp.Get(model)
	if err != nil {
chenweijian's avatar
chenweijian committed
729
		return myContext, myerr.WrapErr(err)
chenweijian's avatar
chenweijian committed
730 731
	}
	gpU := &groupPower_m.GroupPowerUser{GroupPowerId: gpInfo.ID}
chenweijian's avatar
chenweijian committed
732
	members, total, _, _, err := gpU.GetBy(model, 5, 0)
chenweijian's avatar
chenweijian committed
733
	if err != nil {
chenweijian's avatar
chenweijian committed
734
		return myContext, myerr.WrapErr(err)
chenweijian's avatar
chenweijian committed
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
	}
	uids := make([]uint64, 0, len(members))
	for _, v := range members {
		uids = append(uids, v.UserId)
	}
	//查找用户信息
	//uids = common.UniqueSliceUInt64(uids)
	userMap, err := user_c.GetUserTinyMap(domain.CreateModelContext(myContext), uids, true)
	if err != nil {
		return myContext, err
	}
	resMembers := make([]*group_power_cv.GroupPowerUser, 0, len(members))
	for _, v := range members {
		resMembers = append(resMembers, &group_power_cv.GroupPowerUser{User: userMap[v.UserId], Role: v.Role})
	}
hujiebin's avatar
hujiebin committed
750 751 752 753 754
	gradeM, err := groupPower_m.MGetGroupPowerGrade(model, []mysql.ID{gp.ID})
	if err != nil {
		return myContext, err
	}
	grade := gradeM[gp.ID]
755
	nextExp := groupPower_e.GroupPowerGradeExp[groupPower_e.GroupPowerGradeMax]
hujiebin's avatar
hujiebin committed
756 757 758
	if grade.Grade != groupPower_e.GroupPowerGradeMax {
		nextExp = groupPower_e.GroupPowerGradeExp[grade.Grade+1]
	}
chenweijian's avatar
chenweijian committed
759 760
	info := &group_power_cv.GroupPower{
		Id: gpInfo.ID, Name: gpInfo.Name, Nameplate: gpInfo.Nameplate, Declaration: gpInfo.Declaration, Icon: gpInfo.Icon,
hujiebin's avatar
hujiebin committed
761
		Grade: grade.Grade, Exp: grade.Exp, NextExp: nextExp, GradeName: gpInfo.GradeName, GradeMedal: gpInfo.GradeMedal,
762
		MemberNum: mysql.Num(total), MemberMax: mysql.Num(group_power_cv.GroupPowerGradePrivilegeNum[grade.Grade][0].Num),
chenweijian's avatar
chenweijian committed
763
	}
chenweijian's avatar
chenweijian committed
764 765 766
	if info.Icon != "" {
		info.Icon = common.MakeFullUrl(info.Icon)
	}
chenweijian's avatar
chenweijian committed
767 768 769 770 771 772 773
	if info.Nameplate == "" {
		groupInfo, err := group_m.GetGroupInfoByOwner(model, myUserId)
		if err != nil {
			return myContext, err
		}
		if groupInfo != nil {
			info.Nameplate = groupInfo.Name
chenweijian's avatar
chenweijian committed
774 775 776
			if len(info.Nameplate) > 6 {
				info.Nameplate = info.Nameplate[:6]
			}
chenweijian's avatar
chenweijian committed
777 778
		}
	}
chenweijian's avatar
chenweijian committed
779 780 781 782 783 784
	// 家族月排名
	beginDate, endDate := now.BeginningOfMonth().Format("2006-01-02"), now.EndOfMonth().Format("2006-01-02")
	info.MonthRank, err = groupPower_m.GetGroupPowerExpRankById(model, beginDate, endDate, 30, info.Id)
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
785 786 787 788 789 790 791 792 793 794
	// 我在该家族中的角色
	myPU := groupPower_m.GroupPowerUser{UserId: myUserId}
	myGroupPUser, err := myPU.GetGroupPowerUser(model)
	if err != nil {
		return myContext, err
	}
	if myGroupPUser != nil && myGroupPUser.GroupPowerId == info.Id {
		info.Role = int(myGroupPUser.Role)
	} else {
		// 是否申请了加入
chenweijian's avatar
chenweijian committed
795
		apply, err := groupPower_m.GetGroupPowerApplyJoin(model, myUserId, info.Id, 0)
chenweijian's avatar
chenweijian committed
796 797 798 799 800 801 802
		if err != nil {
			return myContext, err
		}
		if apply != nil && apply.IsAccept == 0 {
			info.IsApply = true
		}
	}
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
	// 补上家族之星三个榜一
	stars, err := groupPower_m.GetGroupPowerMonthStartTop1(model, gp.ID)
	if err != nil {
		return myContext, myerr.WrapErr(err)
	}
	var cvStar []*group_power_cv.GroupPowerStar
	if len(stars) > 0 {
		var userIds []uint64
		for _, star := range stars {
			userIds = append(userIds, star.UserId)
		}
		userM, err := user_cv.GetUserTinyMap(userIds)
		if err != nil {
			return myContext, err
		}
		for _, star := range stars {
			cvStar = append(cvStar, &group_power_cv.GroupPowerStar{
				User:        userM[star.UserId],
				RankingType: groupPower_e.GroupPowerRankType(star.Type),
			})
		}
	}
	res := group_power_cv.GroupPowerInfo{Info: info, Members: resMembers, Stars: cvStar}
chenweijian's avatar
chenweijian committed
826 827 828 829

	resp.ResponseOk(c, res)
	return myContext, nil
}
chenweijian's avatar
chenweijian committed
830 831 832 833 834

// @Tags 家族
// @Summary 获取某个家族房间列表
// @Param id query int true "家族id"
// @Param pageSize query int true "分页大小 默认:10" default(10)
chenweijian's avatar
chenweijian committed
835
// @Param pageIndex query int true "分页开始索引,偏移量" default(1)
chenweijian's avatar
chenweijian committed
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
// @Success 200 {object} []group_cv.PopularGroupInfo
// @Router /v1/groupPower/rooms [get]
func GroupPowerRooms(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
	familyId, err := strconv.ParseUint(c.Query("id"), 10, 64)
	if err != nil {
		return myContext, err
	}
	pageSize, err := strconv.Atoi(c.Query("pageSize"))
	if err != nil {
		return myContext, err
	}
	pageIndex, err := strconv.Atoi(c.Query("pageIndex"))
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
856 857 858
	if pageIndex == 1 {
		pageIndex = 0
	}
chenweijian's avatar
chenweijian committed
859
	model := domain.CreateModelContext(myContext)
chenweijian's avatar
chenweijian committed
860
	rooms, nextPageIndex, hasNextPage, err := group_m.GetFamilyRooms(model, familyId, pageSize, pageIndex)
chenweijian's avatar
chenweijian committed
861 862 863 864 865 866 867 868
	if err != nil {
		return myContext, err
	}
	resRooms, err := group_cv.BuildPopularGroupInfo(model, userId, rooms)
	if err != nil {
		return myContext, err
	}

chenweijian's avatar
chenweijian committed
869
	resp.ResponsePageBaseOk(c, resRooms, nextPageIndex, hasNextPage)
chenweijian's avatar
chenweijian committed
870 871
	return myContext, nil
}
chenweijian's avatar
chenweijian committed
872 873 874

// @Tags 家族
// @Summary 获取家族成员列表
chenweijian's avatar
chenweijian committed
875
// @Param userCode query string false "用户extId,搜索时输入"
chenweijian's avatar
chenweijian committed
876 877
// @Param id query int true "家族id"
// @Param pageSize query int true "分页大小 默认:10" default(10)
chenweijian's avatar
chenweijian committed
878
// @Param pageIndex query int true "分页开始索引,偏移量" default(1)
chenweijian's avatar
chenweijian committed
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
// @Success 200 {object} []group_power_cv.FamilyMemberDetail
// @Router /v1/groupPower/members [get]
func GroupPowerMembers(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
	familyId, err := strconv.ParseUint(c.Query("id"), 10, 64)
	if err != nil {
		return myContext, err
	}
	pageSize, err := strconv.Atoi(c.Query("pageSize"))
	if err != nil {
		return myContext, err
	}
	pageIndex, err := strconv.Atoi(c.Query("pageIndex"))
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
899 900 901
	if pageIndex == 1 {
		pageIndex = 0
	}
chenweijian's avatar
chenweijian committed
902
	model := domain.CreateModelContext(myContext)
chenweijian's avatar
chenweijian committed
903
	userCode := c.Query("userCode")
chenweijian's avatar
chenweijian committed
904 905

	gpU := &groupPower_m.GroupPowerUser{GroupPowerId: familyId}
chenweijian's avatar
chenweijian committed
906 907
	if userCode != "" {
		u, err := user_m.GetUserByCode(model, userCode)
chenweijian's avatar
chenweijian committed
908 909 910
		if err != nil || u == nil || u.ID <= 0 {
			resp.ResponsePageBaseOk(c, nil, 0, false)
			return myContext, nil
chenweijian's avatar
chenweijian committed
911 912 913 914 915 916
		}
		if u != nil && u.ID > 0 {
			gpU.UserId = u.ID
		}
	}

chenweijian's avatar
chenweijian committed
917
	members, _, nextPageIndex, hasNextPage, err := gpU.GetBy(model, pageSize, pageIndex)
chenweijian's avatar
chenweijian committed
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
	if err != nil {
		return myContext, err
	}

	userIds := make([]uint64, 0)
	for _, v := range members {
		userIds = append(userIds, v.UserId)
	}

	result := make([]group_power_cv.FamilyMemberDetail, 0)
	if len(userIds) > 0 {
		users, err := user_cv.BatchGetUserExtend(model, userIds, userId)
		if err != nil {
			return myContext, err
		}

		for _, v := range members {
			result = append(result, group_power_cv.FamilyMemberDetail{
chenweijian's avatar
chenweijian committed
936 937
				User: users[v.UserId],
				Role: v.Role,
chenweijian's avatar
chenweijian committed
938 939 940 941
			})
		}
	}

chenweijian's avatar
chenweijian committed
942
	resp.ResponsePageBaseOk(c, result, nextPageIndex, hasNextPage)
chenweijian's avatar
chenweijian committed
943 944
	return myContext, nil
}
chenweijian's avatar
chenweijian committed
945 946 947 948 949

// @Tags 家族
// @Summary 申请加入家族
// @Param id formData int true "家族id"
// @Success 200
chenweijian's avatar
chenweijian committed
950
// @Router /v1/groupPower/apply [post]
chenweijian's avatar
chenweijian committed
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
func GroupPowerApplyJoin(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
	familyId, err := strconv.ParseUint(c.PostForm("id"), 10, 64)
	if err != nil {
		return myContext, myerr.WrapErr(err)
	}
	model := domain.CreateModelContext(myContext)

	// 判断家族是否存在
	gp := &groupPower_m.GroupPower{Entity: mysql.Entity{ID: familyId}}
	gpInfo, err := gp.Get(model)
	if err != nil {
		return myContext, err
	}
	if gpInfo == nil || gpInfo.ID <= 0 {
chenweijian's avatar
chenweijian committed
970 971 972 973 974 975 976 977 978 979
		return myContext, bizerr.GroupPowerNotExist
	}
	// 判断是否加入了家族
	gpU := groupPower_m.GroupPowerUser{UserId: userId}
	uList, err := gpU.Get(model.Db)
	if err != nil {
		return myContext, err
	}
	if len(uList) > 0 {
		return myContext, bizerr.GroupPowerHasJoinOther
chenweijian's avatar
chenweijian committed
980
	}
981 982 983 984 985 986 987 988 989
	// 判断家族是否满人了
	nowNum, err := groupPower_m.GetMemberNum(model, familyId)
	if err != nil {
		return myContext, myerr.WrapErr(err)
	}
	maxNum := group_power_cv.GroupPowerGradePrivilegeNum[gpInfo.Grade][0].Num
	if nowNum+1 > int64(maxNum) {
		return myContext, bizerr.GroupPowerMemberMax
	}
chenweijian's avatar
chenweijian committed
990 991

	// 插入申请表
chenweijian's avatar
chenweijian committed
992 993 994 995 996 997 998 999 1000 1001
	err = groupPower_m.InsertGroupPowerApplyJoin(model, userId, gpInfo.ID)
	if err != nil {
		return myContext, err
	}

	resp.ResponseOk(c, nil)
	return myContext, nil
}

// @Tags 家族
chenweijian's avatar
chenweijian committed
1002
// @Summary 审核加入家族申请
chenweijian's avatar
chenweijian committed
1003
// @Param userExtId formData string true "用户extId"
chenweijian's avatar
chenweijian committed
1004
// @Param type formData int true "1.通过,2.不通过"
chenweijian's avatar
chenweijian committed
1005
// @Success 200
chenweijian's avatar
chenweijian committed
1006
// @Router /v1/groupPower/apply/pass [post]
chenweijian's avatar
chenweijian committed
1007 1008 1009 1010 1011 1012
func GroupPowerApplyPass(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
1013 1014 1015 1016 1017 1018 1019
	optType, err := strconv.Atoi(c.PostForm("type"))
	if err != nil {
		return myContext, bizerr.InvalidParameter
	}
	if optType < 1 || optType > 2 {
		return myContext, bizerr.InvalidParameter
	}
chenweijian's avatar
chenweijian committed
1020 1021 1022 1023
	userExtId := c.PostForm("userExtId")
	if userExtId == "" {
		return myContext, bizerr.InvalidParameter
	}
chenweijian's avatar
chenweijian committed
1024
	model := domain.CreateModelContext(myContext)
chenweijian's avatar
chenweijian committed
1025 1026 1027 1028
	optUser, err := user_c.GetUserByExternalId(model, userExtId)
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043

	// 判断是否加入了家族
	gpU := groupPower_m.GroupPowerUser{UserId: userId}
	myGroupPUser, err := gpU.GetGroupPowerUser(model)
	if err != nil {
		return myContext, err
	}
	// 操作者是否加入了家族,是否有操作权限
	if myGroupPUser == nil || myGroupPUser.ID == 0 {
		return myContext, bizerr.GroupPowerHaveNoJoin
	}
	if myGroupPUser.Role == 0 || myGroupPUser.Role == groupPower_e.GroupPowerUserRoleUser {
		return myContext, bizerr.GroupPowerHaveNoPower
	}
	// 查找申请记录
chenweijian's avatar
chenweijian committed
1044
	apply, err := groupPower_m.GetGroupPowerApplyJoin(model, optUser.ID, myGroupPUser.GroupPowerId, 0)
chenweijian's avatar
chenweijian committed
1045 1046 1047 1048 1049 1050 1051
	if err != nil {
		return myContext, err
	}
	if apply == nil {
		return myContext, bizerr.GroupPowerHaveNoApply
	}

chenweijian's avatar
chenweijian committed
1052 1053
	if optType == 2 { // 拒绝
		// 更改申请表状态
chenweijian's avatar
chenweijian committed
1054
		err = groupPower_m.OptGroupPowerApplyJoinById(model, apply.Id, userId, optType)
chenweijian's avatar
chenweijian committed
1055 1056 1057 1058 1059 1060
		if err != nil {
			return myContext, err
		}
		resp.ResponseOk(c, nil)
		return myContext, nil
	}
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
	// 判断家族是否满人了
	nowNum, err := groupPower_m.GetMemberNum(model, apply.GroupPowerId)
	if err != nil {
		return myContext, myerr.WrapErr(err)
	}
	gradeM, err := groupPower_m.MGetGroupPowerGrade(model, []mysql.ID{apply.GroupPowerId})
	if err != nil {
		return myContext, err
	}
	grade := gradeM[apply.GroupPowerId]
	maxNum := group_power_cv.GroupPowerGradePrivilegeNum[grade.Grade][0].Num
	if int(nowNum+1) > maxNum {
		return myContext, bizerr.GroupPowerMemberMax
	}
chenweijian's avatar
chenweijian committed
1075

chenweijian's avatar
chenweijian committed
1076 1077 1078 1079 1080 1081 1082 1083 1084
	err = model.Transaction(func(model *domain.Model) error {
		txModel := domain.CreateModel(model.CtxAndDb)
		// 插入家族成员表
		gpU := groupPower_m.GroupPowerUser{GroupPowerId: apply.GroupPowerId, UserId: apply.UserId, Role: groupPower_e.GroupPowerUserRoleUser}
		err := gpU.Create(txModel.Db)
		if err != nil {
			txModel.Log.Errorf("GroupPowerApplyPass err:%v, info:%v", err, gpU)
			return err
		}
1085 1086 1087 1088 1089 1090 1091 1092 1093
		newNum, err := groupPower_m.GetMemberNum(txModel, apply.GroupPowerId)
		if err != nil {
			txModel.Log.Errorf("GroupPowerApplyPass err:%v, info:%v", err, gpU)
			return err
		}
		if int(newNum) > maxNum {
			txModel.Log.Errorf("GroupPowerApplyPass err:%v, info:%v", bizerr.GroupPowerMemberMax, gpU)
			return bizerr.GroupPowerMemberMax
		}
chenweijian's avatar
chenweijian committed
1094
		// 更改申请表状态
chenweijian's avatar
chenweijian committed
1095
		err = groupPower_m.OptGroupPowerApplyJoinById(model, apply.Id, userId, optType)
chenweijian's avatar
chenweijian committed
1096 1097 1098
		if err != nil {
			return err
		}
chenweijian's avatar
chenweijian committed
1099
		// 删除他在其他家族未处理的申请
chenweijian's avatar
chenweijian committed
1100
		err = groupPower_m.DelGroupPowerApplyJoinNoDeal(model, apply.UserId)
chenweijian's avatar
chenweijian committed
1101 1102 1103 1104
		if err != nil {
			return err
		}

chenweijian's avatar
chenweijian committed
1105 1106
		return nil
	})
chenweijian's avatar
chenweijian committed
1107 1108 1109
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
1110 1111 1112 1113 1114
	// 发小助手通知用户
	err = msg.SendLittleAssistantMsg(model, apply.UserId, msg_e.GroupPowerWelcomeJoin, "", "", "", "", "")
	if err != nil {
		model.Log.Errorf("GroupPowerApplyPass msg err:%v", err)
	}
chenweijian's avatar
chenweijian committed
1115 1116 1117 1118

	resp.ResponseOk(c, nil)
	return myContext, nil
}
chenweijian's avatar
chenweijian committed
1119 1120 1121 1122

// @Tags 家族
// @Summary 申请加入列表
// @Param pageSize query int true "分页大小 默认:10" default(10)
chenweijian's avatar
chenweijian committed
1123
// @Param pageIndex query int true "分页开始索引,偏移量" default(1)
chenweijian's avatar
chenweijian committed
1124
// @Success 200 {object} []group_power_cv.FamilyApplyList
chenweijian's avatar
chenweijian committed
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
// @Router /v1/groupPower/apply/list [get]
func GroupPowerApplyList(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
	pageSize, err := strconv.Atoi(c.Query("pageSize"))
	if err != nil {
		return myContext, err
	}
	pageIndex, err := strconv.Atoi(c.Query("pageIndex"))
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
1140 1141 1142
	if pageIndex == 1 {
		pageIndex = 0
	}
chenweijian's avatar
chenweijian committed
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
	model := domain.CreateModelContext(myContext)

	// 判断是否加入了家族
	gpU := groupPower_m.GroupPowerUser{UserId: userId}
	myGroupPUser, err := gpU.GetGroupPowerUser(model)
	if err != nil {
		return myContext, err
	}
	// 操作者是否加入了家族,是否有操作权限
	if myGroupPUser == nil || myGroupPUser.ID == 0 {
		return myContext, bizerr.GroupPowerHaveNoJoin
	}
	if myGroupPUser.Role == 0 || myGroupPUser.Role == groupPower_e.GroupPowerUserRoleUser {
		return myContext, bizerr.GroupPowerHaveNoPower
	}
	// 申请列表
chenweijian's avatar
chenweijian committed
1159
	rows, nextPageIndex, hasNextPage, err := groupPower_m.OptGroupPowerApplyList(model, myGroupPUser.GroupPowerId, pageSize, pageIndex)
chenweijian's avatar
chenweijian committed
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
	if err != nil {
		return myContext, err
	}

	uids := make([]uint64, 0, len(rows))
	for _, v := range rows {
		uids = append(uids, v.UserId, v.MgrId)
	}
	//查找用户信息
	uids = common.UniqueSliceUInt64(uids)
	userMap, err := user_c.GetUserTinyMap(domain.CreateModelContext(myContext), uids, true)

	result := make([]*group_power_cv.FamilyApplyList, 0, len(rows))
	for _, v := range rows {
chenweijian's avatar
chenweijian committed
1174
		info := &group_power_cv.FamilyApplyList{User: userMap[v.UserId], Time: v.CreatedTime.UnixMilli(), Status: v.IsAccept}
chenweijian's avatar
chenweijian committed
1175 1176 1177 1178
		if v.MgrId > 0 {
			info.MgrName = userMap[v.MgrId].Nick
		}
		result = append(result, info)
chenweijian's avatar
chenweijian committed
1179 1180
	}

chenweijian's avatar
chenweijian committed
1181
	resp.ResponsePageBaseOk(c, result, nextPageIndex, hasNextPage)
chenweijian's avatar
chenweijian committed
1182 1183
	return myContext, nil
}
chenweijian's avatar
chenweijian committed
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196

// @Tags 家族
// @Summary 退出/踢出家族
// @Param type formData int true "1.自己退出,2.踢人"
// @Param userExtId formData string false "用户extId"
// @Success 200
// @Router /v1/groupPower/quit [post]
func GroupPowerQuit(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
1197
	quitType, err := strconv.Atoi(c.PostForm("type"))
chenweijian's avatar
chenweijian committed
1198
	if err != nil {
chenweijian's avatar
chenweijian committed
1199
		return myContext, myerr.WrapErr(err)
chenweijian's avatar
chenweijian committed
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
	}
	if quitType < 1 || quitType > 2 {
		return myContext, bizerr.InvalidParameter
	}
	model := domain.CreateModelContext(myContext)

	if quitType == 1 { // 主动退出
		// 判断是否加入了家族
		gpU := groupPower_m.GroupPowerUser{UserId: userId}
		groupPUser, err := gpU.GetGroupPowerUser(model)
		if err != nil {
			return myContext, err
		}
		if groupPUser == nil {
			return myContext, bizerr.GroupPowerHaveNoJoin
		}
chenweijian's avatar
chenweijian committed
1216 1217 1218
		if groupPUser.Role == groupPower_e.GroupPowerUserRoleMgr {
			return myContext, bizerr.GroupPowerCannotQuit
		}
chenweijian's avatar
chenweijian committed
1219 1220 1221 1222 1223 1224 1225
		// 退出家族、log
		err = model.Transaction(func(model *domain.Model) error {
			return groupPower_m.QuitFamily(model, userId, userId, groupPUser.GroupPowerId)
		})
		if err != nil {
			return myContext, err
		}
chenweijian's avatar
chenweijian committed
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243

		resp.ResponseOk(c, nil)
		return myContext, nil
	}
	// 判断是否加入了家族
	gpU := groupPower_m.GroupPowerUser{UserId: userId}
	myGroupPUser, err := gpU.GetGroupPowerUser(model)
	if err != nil {
		return myContext, err
	}
	// 操作者是否加入了家族,是否有操作权限
	if myGroupPUser == nil {
		return myContext, bizerr.GroupPowerHaveNoJoin
	}
	if myGroupPUser.Role == 0 || myGroupPUser.Role == groupPower_e.GroupPowerUserRoleUser {
		return myContext, bizerr.GroupPowerHaveNoPower
	}
	// 被踢人信息
chenweijian's avatar
chenweijian committed
1244
	userExtId := c.PostForm("userExtId")
chenweijian's avatar
chenweijian committed
1245 1246 1247 1248 1249 1250 1251
	if userExtId == "" {
		return myContext, bizerr.InvalidParameter
	}
	u, err := user_c.GetUserByExternalId(model, userExtId)
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
1252 1253 1254
	// 被踢者
	gpUKick := groupPower_m.GroupPowerUser{UserId: userId}
	kickGroupPUser, err := gpUKick.GetGroupPowerUser(model)
chenweijian's avatar
chenweijian committed
1255 1256 1257
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
1258
	if kickGroupPUser == nil {
chenweijian's avatar
chenweijian committed
1259 1260
		return myContext, bizerr.GroupPowerHaveNoJoin
	}
chenweijian's avatar
chenweijian committed
1261 1262 1263 1264 1265 1266 1267
	// 退出家族、log
	err = model.Transaction(func(model *domain.Model) error {
		return groupPower_m.QuitFamily(model, u.ID, userId, kickGroupPUser.GroupPowerId)
	})
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
1268

chenweijian's avatar
chenweijian committed
1269
	resp.ResponseOk(c, nil)
chenweijian's avatar
chenweijian committed
1270 1271
	return myContext, nil
}
chenweijian's avatar
chenweijian committed
1272 1273 1274 1275 1276

// @Tags 家族
// @Summary 家族退出列表
// @Param pageSize query int true "分页大小 默认:10" default(10)
// @Param pageIndex query int true "第几个分页,从1开始 默认:1" default(1)
chenweijian's avatar
chenweijian committed
1277
// @Success 200 {object} []group_power_cv.FamilyQuitList
chenweijian's avatar
chenweijian committed
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
// @Router /v1/groupPower/quit/list [get]
func GroupPowerQuitList(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
	pageSize, err := strconv.Atoi(c.Query("pageSize"))
	if err != nil {
		return myContext, err
	}
	pageIndex, err := strconv.Atoi(c.Query("pageIndex"))
	if err != nil {
		return myContext, err
	}
chenweijian's avatar
chenweijian committed
1293 1294 1295
	if pageIndex == 1 {
		pageIndex = 0
	}
chenweijian's avatar
chenweijian committed
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
	model := domain.CreateModelContext(myContext)

	// 判断是否加入了家族
	gpU := groupPower_m.GroupPowerUser{UserId: userId}
	myGroupPUser, err := gpU.GetGroupPowerUser(model)
	if err != nil {
		return myContext, err
	}
	// 操作者是否加入了家族,是否有操作权限
	if myGroupPUser == nil || myGroupPUser.ID == 0 {
		return myContext, bizerr.GroupPowerHaveNoJoin
	}
	if myGroupPUser.Role == 0 || myGroupPUser.Role == groupPower_e.GroupPowerUserRoleUser {
		return myContext, bizerr.GroupPowerHaveNoPower
	}
	// 列表
	rows, nextPageIndex, hasNextPage, err := groupPower_m.GroupPowerQuitList(model, myGroupPUser.GroupPowerId, pageSize, pageIndex)
	if err != nil {
		return myContext, err
	}

	uids := make([]uint64, 0, len(rows))
	for _, v := range rows {
		uids = append(uids, v.UserId, v.MgrId)
	}
	//查找用户信息
	uids = common.UniqueSliceUInt64(uids)
	userMap, err := user_c.GetUserTinyMap(domain.CreateModelContext(myContext), uids, true)

	result := make([]*group_power_cv.FamilyQuitList, 0, len(rows))
	for _, v := range rows {
chenweijian's avatar
chenweijian committed
1327
		item := &group_power_cv.FamilyQuitList{User: userMap[v.UserId], Time: v.CreatedTime.UnixMilli()}
chenweijian's avatar
chenweijian committed
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
		if v.UserId == v.MgrId {
			item.QuitType = 1 // 主动退出
		} else {
			item.QuitType = 2 // 被踢出
			item.MgrName = userMap[v.MgrId].Nick
		}
		result = append(result, item)
	}

	resp.ResponsePageBaseOk(c, result, nextPageIndex, hasNextPage)
	return myContext, nil
}
chenweijian's avatar
chenweijian committed
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389

// @Tags 家族
// @Summary 设置/取消管理员
// @Param userExtId formData string false "用户extId"
// @Param type formData int true "1.设置为管理员,2.取消管理员"
// @Success 200
// @Router /v1/groupPower/admin [post]
func GroupPowerSetAdmin(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
	optType, err := strconv.Atoi(c.PostForm("type"))
	if err != nil {
		return myContext, bizerr.InvalidParameter
	}
	if optType < 1 || optType > 2 {
		return myContext, bizerr.InvalidParameter
	}
	userExtId := c.PostForm("userExtId")
	if userExtId == "" {
		return myContext, bizerr.InvalidParameter
	}
	model := domain.CreateModelContext(myContext)
	optUser, err := user_c.GetUserByExternalId(model, userExtId)
	if err != nil {
		return myContext, err
	}

	// 判断是否加入了家族
	gpU := groupPower_m.GroupPowerUser{UserId: userId}
	myGroupPUser, err := gpU.GetGroupPowerUser(model)
	if err != nil {
		return myContext, err
	}
	// 操作者是否加入了家族,是否有操作权限
	if myGroupPUser == nil {
		return myContext, bizerr.GroupPowerHaveNoJoin
	}
	if myGroupPUser.Role != groupPower_e.GroupPowerUserRoleMgr {
		return myContext, bizerr.GroupPowerHaveNoPower
	}
	// 被操作者是否加入了家族
	gpOptUser := groupPower_m.GroupPowerUser{UserId: optUser.ID}
	optGroupPUser, err := gpOptUser.GetGroupPowerUser(model)
	if err != nil {
		return myContext, err
	}
	if optGroupPUser == nil {
chenweijian's avatar
chenweijian committed
1390
		return myContext, bizerr.GroupPowerUserHaveNoJoin
chenweijian's avatar
chenweijian committed
1391
	}
chenweijian's avatar
chenweijian committed
1392 1393 1394
	if optUser.ID == userId { // 不能操作自己
		return myContext, bizerr.GroupPowerHaveNoPower
	}
chenweijian's avatar
chenweijian committed
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
	// 目标身份
	var targetRole groupPower_e.GroupPowerUserRole
	if optType == 1 {
		targetRole = groupPower_e.GroupPowerUserRoleAdmin
	} else {
		targetRole = groupPower_e.GroupPowerUserRoleUser
	}
	// 和原来的身份是否一致
	if optGroupPUser.Role == targetRole {
		return myContext, bizerr.GroupPowerHaveAlreadyChange
	}
	// 变更
chenweijian's avatar
chenweijian committed
1407
	err = groupPower_m.UpdateFamilyAdmin(model, optGroupPUser.UserId, optGroupPUser.GroupPowerId, targetRole)
chenweijian's avatar
chenweijian committed
1408 1409 1410 1411 1412 1413 1414
	if optGroupPUser == nil {
		return myContext, myerr.WrapErr(err)
	}

	resp.ResponseOk(c, nil)
	return myContext, nil
}
chenweijian's avatar
chenweijian committed
1415 1416 1417 1418 1419 1420 1421 1422

// @Tags 家族
// @Summary 设置家族信息
// @Param id formData int true "家族id"
// @Param icon formData string false "家族图片"
// @Param name formData string false "家族名称"
// @Param nameplate formData string false "家族铭牌"
// @Param declaration formData string false "家族宣言"
hujiebin's avatar
hujiebin committed
1423
// @Success 200 {object} group_power_cv.GroupPower
chenweijian's avatar
chenweijian committed
1424 1425 1426
// @Router /v1/groupPower/info/set [post]
func GroupPowerSetInfo(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)
chenweijian's avatar
chenweijian committed
1427
	userId, lang, err := req.GetUserIdLang(c, myContext)
chenweijian's avatar
chenweijian committed
1428 1429 1430 1431
	if err != nil {
		return myContext, err
	}
	type param struct {
chenweijian's avatar
chenweijian committed
1432 1433 1434 1435 1436
		Id          uint64 `form:"id"`
		Name        string `form:"name"`
		Nameplate   string `form:"nameplate"`   // 铭牌
		Declaration string `form:"declaration"` // 宣言
		Icon        string `form:"icon"`        // 头像
chenweijian's avatar
chenweijian committed
1437
	}
chenweijian's avatar
chenweijian committed
1438
	var para param
chenweijian's avatar
chenweijian committed
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
	if err := c.ShouldBind(&para); err != nil {
		return myContext, err
	}
	if para.Id <= 0 {
		return myContext, bizerr.InvalidParameter
	}
	model := domain.CreateModelContext(myContext)

	// 判断是否加入了家族
	gpU := groupPower_m.GroupPowerUser{UserId: userId}
	myGroupPUser, err := gpU.GetGroupPowerUser(model)
	if err != nil {
		return myContext, err
	}
	// 操作者是否加入了家族,是否有操作权限
	if myGroupPUser == nil {
		return myContext, bizerr.GroupPowerHaveNoJoin
	}
	if myGroupPUser.Role != groupPower_e.GroupPowerUserRoleMgr {
		return myContext, bizerr.GroupPowerHaveNoPower
	}
	// 检查铭牌是否能够修改
	if para.Nameplate != "" {
		// 等级检查
hujiebin's avatar
hujiebin committed
1463
		gradeM, err := groupPower_m.MGetGroupPowerGrade(model, []mysql.ID{myGroupPUser.GroupPowerId})
chenweijian's avatar
chenweijian committed
1464 1465 1466
		if err != nil {
			return myContext, err
		}
hujiebin's avatar
hujiebin committed
1467 1468
		grade := gradeM[myGroupPUser.GroupPowerId]
		if grade.Grade < 1 {
chenweijian's avatar
chenweijian committed
1469
			return myContext, res_m.GetErrByLanguage(model.Db, common.MSG_ID_SET_FAMILY_NAMEPL, lang, bizerr.GroupPowerChangeNameplate)
chenweijian's avatar
chenweijian committed
1470 1471
		}
		// 检查铭牌长度和唯一性
chenweijian's avatar
chenweijian committed
1472
		if len(para.Nameplate) > 6 {
chenweijian's avatar
chenweijian committed
1473 1474 1475 1476 1477 1478
			return myContext, bizerr.GroupPowerHaveTooLong
		}
		if groupPower_m.IsExistsNameplate(model, para.Nameplate) {
			return myContext, bizerr.GroupPowerCannotRepeated
		}
	}
chenweijian's avatar
chenweijian committed
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
	if para.Icon != "" {
		switch config.GetConfigApp().MODERATE {
		case "AWS":
			passed, err := aws.ModerateLabels(model.Log, userId, para.Icon)
			if err == nil {
				if !passed {
					return myContext, bizerr.ImagePolicyViolation
				}
			} else {
				model.Log.Warnf("ModerateLabels err:%v", err)
			}
		case "TENCENT":
			label, err := tencentyun.ModerateImage(model, userId, "", utils.StripAwsPrefix(para.Icon), para.Icon)
			if err == nil && label != "Pass" {
				return myContext, bizerr.ImagePolicyViolation
			}
		}
	}
chenweijian's avatar
chenweijian committed
1497 1498

	// 修改家族信息
chenweijian's avatar
chenweijian committed
1499
	err = groupPower_m.UpdateFamily(model, para.Id, para.Name, para.Nameplate, para.Declaration, para.Icon)
chenweijian's avatar
chenweijian committed
1500 1501 1502
	if err != nil {
		return myContext, myerr.WrapErr(err)
	}
chenweijian's avatar
chenweijian committed
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
	// 返回家族信息
	gp := &groupPower_m.GroupPower{Entity: mysql.Entity{ID: para.Id}}
	gpInfo, err := gp.Get(model)
	if err != nil {
		return myContext, myerr.WrapErr(err)
	}
	gpMember := &groupPower_m.GroupPowerUser{GroupPowerId: gpInfo.ID}
	_, total, _, _, err := gpMember.GetBy(model, 5, 0)
	if err != nil {
		return myContext, myerr.WrapErr(err)
	}
	groupPowerGrade, err := groupPower_m.MGetGroupPowerGrade(model, []mysql.ID{gp.ID})
hujiebin's avatar
hujiebin committed
1515 1516 1517 1518 1519
	gradeM, err := groupPower_m.MGetGroupPowerGrade(model, []mysql.ID{gp.ID})
	if err != nil {
		return myContext, err
	}
	grade := gradeM[gp.ID]
1520
	nextExp := groupPower_e.GroupPowerGradeExp[groupPower_e.GroupPowerGradeMax]
hujiebin's avatar
hujiebin committed
1521 1522 1523
	if grade.Grade != groupPower_e.GroupPowerGradeMax {
		nextExp = groupPower_e.GroupPowerGradeExp[grade.Grade+1]
	}
chenweijian's avatar
chenweijian committed
1524 1525
	info := &group_power_cv.GroupPower{
		Id: gpInfo.ID, Name: gpInfo.Name, Nameplate: gpInfo.Nameplate, Declaration: gpInfo.Declaration, Icon: gpInfo.Icon,
hujiebin's avatar
hujiebin committed
1526
		Grade: grade.Grade, Exp: grade.Exp, NextExp: nextExp, GradeName: gpInfo.GradeName, GradeMedal: gpInfo.GradeMedal,
chenweijian's avatar
chenweijian committed
1527 1528 1529 1530 1531
		MemberNum: mysql.Num(total), MemberMax: mysql.Num(group_power_cv.GroupPowerGradePrivilegeNum[groupPowerGrade[gp.ID].Grade][0].Num),
	}
	if info.Icon != "" {
		info.Icon = common.MakeFullUrl(info.Icon)
	}
chenweijian's avatar
chenweijian committed
1532 1533 1534 1535
	// 我在该家族中的角色
	if myGroupPUser != nil && myGroupPUser.GroupPowerId == info.Id {
		info.Role = int(myGroupPUser.Role)
	}
chenweijian's avatar
chenweijian committed
1536

chenweijian's avatar
chenweijian committed
1537
	resp.ResponseOk(c, info)
chenweijian's avatar
chenweijian committed
1538 1539
	return myContext, nil
}