package public_platoon

import (
	"applet/app/cfg"
	"applet/app/db"
	"applet/app/e"
	md "applet/app/md/institutional_management/public_platoon"
	svc "applet/app/svc/public_platoon"
	"applet/app/utils"
	"code.fnuoos.com/EggPlanet/egg_models.git/src/implement"
	"code.fnuoos.com/EggPlanet/egg_models.git/src/model"
	rule "code.fnuoos.com/EggPlanet/egg_system_rules.git"
	ruleSvc "code.fnuoos.com/EggPlanet/egg_system_rules.git/rule/egg_energy"
	"errors"
	"github.com/gin-gonic/gin"
	"time"
)

// GetPublicPlatoonBasic
// @Summary      制度中心-公排管理-公排基础设置(获取)
// @Tags         公排管理
// @Description  公排基础设置(获取)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Success      200   {object}   md.GetPublicPlatoonBasicResp "具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/getBasic [get]
func GetPublicPlatoonBasic(c *gin.Context) {
	publicPlatoonBasicDb := implement.NewPublicPlatoonBasicSettingDb(db.Db)
	publicPlatoonBasic, err := publicPlatoonBasicDb.PublicPlatoonBasicSettingGetOne()
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err)
		return
	}
	now := time.Now()
	if publicPlatoonBasic == nil {
		publicPlatoonBasic = &model.PublicPlatoonBasicSetting{
			IsOpen:                     1,
			OriginatorUid:              0,
			SeveralTimes:               0,
			SeveralRows:                0,
			SystemPunishReplace:        0,
			SystemPunishReplaceValue:   0,
			IsSelfActiveGetTeamRevenue: 0,
			CreateAt:                   now.Format("2006-01-02 15:04:05"),
			UpdateAt:                   now.Format("2006-01-02 15:04:05"),
		}
		_, err1 := publicPlatoonBasicDb.PublicPlatoonBasicSettingInsert(publicPlatoonBasic)
		if err1 != nil {
			e.OutErr(c, e.ERR_DB_ORM, err1.Error())
			return
		}

	}
	userDb := implement.NewUserDb(db.Db)
	originator, err := userDb.UserGetOneByParams(map[string]interface{}{
		"key":   "id",
		"value": publicPlatoonBasic.OriginatorUid,
	})
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err)
		return
	}
	var resp md.GetPublicPlatoonBasicResp
	resp = md.GetPublicPlatoonBasicResp{
		IsOpen:                     publicPlatoonBasic.IsOpen,
		OriginatorUid:              publicPlatoonBasic.OriginatorUid,
		SeveralTimes:               publicPlatoonBasic.SeveralTimes,
		SeveralRows:                publicPlatoonBasic.SeveralRows,
		SystemPunishReplace:        publicPlatoonBasic.SystemPunishReplace,
		SystemPunishReplaceValue:   publicPlatoonBasic.SystemPunishReplaceValue,
		IsSelfActiveGetTeamRevenue: publicPlatoonBasic.IsSelfActiveGetTeamRevenue,
	}
	if originator != nil {
		resp.OriginatorName = originator.Nickname
	}

	e.OutSuc(c, resp, nil)
}

// UpdatePublicPlatoonBasic
// @Summary      制度中心-公排管理-公排基础设置(修改)
// @Tags         公排管理
// @Description  公排基础设置(修改)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param        req 	body      md.UpdatePublicPlatoonBasicReq          true   "公排设置表单内容"
// @Success      200   {string}  				"success"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/updateBasic [put]
func UpdatePublicPlatoonBasic(c *gin.Context) {
	var req *md.UpdatePublicPlatoonBasicReq
	if err := c.ShouldBindJSON(&req); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}

	publicPlatoonBasicDb := implement.NewPublicPlatoonBasicSettingDb(db.Db)

	publicPlatoonBasic, err := publicPlatoonBasicDb.PublicPlatoonBasicSettingGetOne()
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	setting := &model.PublicPlatoonBasicSetting{
		Id:                         publicPlatoonBasic.Id,
		IsOpen:                     req.IsOpen,
		OriginatorUid:              req.OriginatorUid,
		SeveralTimes:               req.SeveralTimes,
		SeveralRows:                req.SeveralRows,
		SystemPunishReplace:        req.SystemPunishReplace,
		SystemPunishReplaceValue:   req.SystemPunishReplaceValue,
		IsSelfActiveGetTeamRevenue: req.IsSelfActiveGetTeamRevenue,
		CreateAt:                   "",
		UpdateAt:                   "",
	}
	forceColumns := []string{"is_open", "originator_uid", "system_punish_replace", "is_self_active_get_team_revenue", "several_times", "several_rows", "system_punish_replace_value"}

	_, err = publicPlatoonBasicDb.PublicPlatoonBasicSettingUpdate(publicPlatoonBasic.Id, setting, forceColumns...)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	e.OutSuc(c, "success", nil)
}

// SelectMember
// @Summary      制度中心-公排管理-公排基础设置选择会员(查询)
// @Tags         公排管理
// @Description  公排基础设置选择会员(查询)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param        req 	body      md.SelectMemberReq          true   "分页信息必填"
// @Success      200   {object}   md.SelectMemberResp			"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/selectMember [post]
func SelectMember(c *gin.Context) {
	var req *md.SelectMemberReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	levelDb := implement.NewUserLevelDb(db.Db)
	levels, err1 := levelDb.UserLevelAllByAsc()
	if err1 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err1.Error())
		return
	}
	levelsList := make([]map[string]interface{}, 0)
	levelsMap := make(map[int]string)
	for _, level := range levels {
		levelsList = append(levelsList, map[string]interface{}{
			"id":   level.Id,
			"name": level.LevelName,
		})
		levelsMap[level.Id] = level.LevelName
	}

	userDb := implement.NewUserDb(db.Db)
	users, total, err := userDb.UserFindAndCount(req.Uid, req.Phone, req.Nickname, req.Level, req.Page, req.Limit)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	list := make([]md.SelectMemberNode, len(*users))
	for i, user := range *users {
		list[i] = md.SelectMemberNode{
			Uid:      user.Id,
			Avatar:   user.Avatar,
			Nickname: user.Nickname,
			Phone:    user.Phone,
			Level:    levelsMap[user.Level],
		}
	}

	resp := md.SelectMemberResp{
		LevelList: levelsList,
		List:      list,
		Paginate: md.Paginate{
			Limit: req.Limit,
			Page:  req.Page,
			Total: total,
		},
	}

	e.OutSuc(c, resp, nil)
}

// GetRelationshipMap
// @Summary      制度中心-公排管理-关系分布图(获取)
// @Tags         公排管理
// @Description  关系分布图(获取)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @param phone   query string true "phone"
// @param uid   query string true "uid"
// @Success      200   {object}  md.TreeNode	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/relationshipMap [get]
func GetRelationshipMap(c *gin.Context) {
	phone := c.Query("phone")
	uid := c.Query("uid")
	userDb := implement.NewUserDb(db.Db)

	userRelationDb := implement.NewPublicPlatoonUserRelationDb(db.Db)
	var relation *model.PublicPlatoonUserRelation
	var err error
	if phone != "" {
		user, err1 := userDb.UserGetOneByParams(map[string]interface{}{
			"key":   "phone",
			"value": phone,
		})
		if err1 != nil {
			e.OutErr(c, e.ERR_DB_ORM, err1.Error())
			return
		}
		if user == nil {
			e.OutErr(c, e.ERR_NO_DATA, errors.New("手机号不存在"))
			return
		}
		relation, err = userRelationDb.PublicPlatoonUserRelationGetOneByParams(map[string]interface{}{
			"key":   "uid",
			"value": user.Id,
		})
	} else if uid != "" {
		relation, err = userRelationDb.PublicPlatoonUserRelationGetOneByParams(map[string]interface{}{
			"key":   "uid",
			"value": uid,
		})
	} else {
		relation, err = userRelationDb.PublicPlatoonUserRelationGetOneByParams(map[string]interface{}{
			"key":   "level_total",
			"value": 1,
		})
		if err != nil {
			e.OutErr(c, e.ERR_DB_ORM, err.Error())
			return
		}
	}

	var list *md.TreeNode
	list, err = svc.GetTrees(db.Db, relation, 3)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	e.OutSuc(c, list, nil)
}

// FindUserRelationshipMap
// @Summary      制度中心-公排管理-关系分布图(获取指定用户下级)
// @Tags         公排管理
// @Description  关系分布图(获取指定用户下级)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    uid    query    string  true  "用户ID"
// @Success      200   {object}  md.TreeNode	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/findUserRelationshipMap [get]
func FindUserRelationshipMap(c *gin.Context) {
	uid := c.Query("uid")

	userRelationDb := implement.NewPublicPlatoonUserRelationDb(db.Db)
	var err error
	var relation *model.PublicPlatoonUserRelation
	relation, err = userRelationDb.PublicPlatoonUserRelationGetOneByParams(map[string]interface{}{
		"key":   "uid",
		"value": uid,
	})
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	var list *md.TreeNode
	list, err = svc.GetTrees(db.Db, relation, 1)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	e.OutSuc(c, list, nil)
}

// FindSubUserRelationshipMap
// @Summary      制度中心-公排管理-关系分布图(获取指定用户上级)
// @Tags         公排管理
// @Description  关系分布图(获取指定用户上级)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    uid    query    string  true  "用户ID"
// @Success      200   {object}  md.FindSubUserRelationshipMapResp	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/findSubUserRelationshipMap [get]
func FindSubUserRelationshipMap(c *gin.Context) {
	uid := c.Query("uid")

	relateDb := implement.NewPublicPlatoonUserRelationDb(db.Db)
	userRelate, err := relateDb.PublicPlatoonUserRelationGetOneByParams(map[string]interface{}{
		"key":   "uid",
		"value": uid,
	})
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	if userRelate == nil {
		e.OutErr(c, e.ERR_NO_DATA, errors.New("用户不存在"))
		return
	}

	userDb := implement.NewUserDb(db.Db)
	parentUser, err4 := userDb.UserGetOneByParams(map[string]interface{}{
		"key":   "id",
		"value": userRelate.FatherUid1,
	})
	if err4 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err4.Error())
		return
	}

	platoonUserRelationDb := implement.NewPublicPlatoonUserRelationDb(db.Db)
	parentRelation, err := platoonUserRelationDb.PublicPlatoonUserRelationGetOneByParams(map[string]interface{}{
		"key":   "uid",
		"value": parentUser.Id,
	})
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	subUser := md.SubUser{
		AvatarURL: parentUser.Avatar,
		Phone:     parentUser.Phone,
		Nickname:  parentUser.Nickname,
		Uid:       parentUser.Id,
		PID:       parentRelation.RecommendUid,
		Level:     parentRelation.LevelTotal,
		Position:  parentRelation.Position1,
	}

	basicSettingDb := implement.NewPublicPlatoonBasicSettingDb(db.Db)
	basicSetting, err := basicSettingDb.PublicPlatoonBasicSettingGetOne()
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	basicSettingResp := md.BasicSetting{
		Id:                         basicSetting.Id,
		IsOpen:                     basicSetting.IsOpen,
		SeveralTimes:               basicSetting.SeveralTimes,
		SeveralRows:                basicSetting.SeveralRows,
		OriginatorUid:              basicSetting.OriginatorUid,
		SystemPunishReplace:        basicSetting.SystemPunishReplace,
		SystemPunishReplaceValue:   basicSetting.SystemPunishReplaceValue,
		IsSelfActiveGetTeamRevenue: basicSetting.IsSelfActiveGetTeamRevenue,
	}

	resp := md.FindSubUserRelationshipMapResp{
		SubUser:      subUser,
		BasicSetting: basicSettingResp,
		SearchUid:    uid,
	}
	e.OutSuc(c, resp, nil)
}

// ExchangeUserPosition
// @Summary      制度中心-公排管理-关系分布图(位置转换)
// @Tags         公排管理
// @Description  关系分布图(位置转换)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body    md.ExchangeUserPositionReq  true  "需要交换的两个位置"
// @Success      200   {}  	"成功返回"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/exchangeUserPosition [post]
func ExchangeUserPosition(c *gin.Context) {
	var req *md.ExchangeUserPositionReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	userRelationDb := implement.NewPublicPlatoonUserRelationDb(db.Db)
	relation1, err2 := userRelationDb.PublicPlatoonUserRelationGetOneByParams(map[string]interface{}{
		"key":   "id",
		"value": req.Position1,
	})
	if err2 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err2.Error())
		return
	}
	if relation1 == nil {
		e.OutErr(c, e.ERR_BAD_REQUEST, errors.New("position_1 位置有误"))
		return
	}

	relation2, err3 := userRelationDb.PublicPlatoonUserRelationGetOneByParams(map[string]interface{}{
		"key":   "id",
		"value": req.Position2,
	})
	if err3 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err3.Error())
		return
	}
	if relation2 == nil {
		e.OutErr(c, e.ERR_BAD_REQUEST, errors.New("position_2 位置有误"))
		return
	}

	if relation1.LevelTotal == 1 || relation2.LevelTotal == 1 {
		e.OutErr(c, e.ERR_BAD_REQUEST, errors.New("创始人位置不能被修改"))
	}

	err4 := svc.ExchangeUserPosition(db.Db, relation1, relation2)
	if err4 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err4.Error())
		return
	}

	e.OutSuc(c, nil, nil)
}

// GetFreePublishUser
// @Summary      制度中心-公排管理-免罚用户(查询)
// @Tags         公排管理
// @Description  免罚用户(查询)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body    md.GetFreePublishUserReq  true  "页数和行数必填,uid选填"
// @Success      200   {object}  md.GetFreePublishUserResp	"成功返回"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/publicPlatoonUserFreePunish/index [post]
func GetFreePublishUser(c *gin.Context) {
	var req *md.GetFreePublishUserReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	freePunishWithUserDb := implement.NewPublicPlatoonFreePunishWithUserDb(db.Db)
	var m []model.PublicPlatoonFreePunishWithUser
	var err error
	var total int64
	if req.Uid != 0 {
		m, total, err = freePunishWithUserDb.PublicPlatoonFreePunishWithUserCountAndGetPageByParams(req.Page, req.Limit, map[string]interface{}{
			"key":   "uid",
			"value": req.Uid,
		})
	} else {
		m, total, err = freePunishWithUserDb.PublicPlatoonFreePunishWithUserCountAndGetPageByParams(req.Page, req.Limit, nil)
	}
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	userDb := implement.NewUserDb(db.Db)
	var ids []int64
	for _, item := range m {
		ids = append(ids, item.Uid)
	}
	users, err2 := userDb.UserFindByParams(map[string]interface{}{
		"key":   "id",
		"value": ids,
	})
	if err2 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err2.Error())
	}

	var nodes []md.FreePublishUserNode
	for _, user := range users {
		nodes = append(nodes, md.FreePublishUserNode{
			UID:      user.Id,
			Phone:    user.Phone,
			Nickname: user.Nickname,
		})
	}
	var paginate md.Paginate
	paginate = md.Paginate{
		Limit: req.Limit,
		Page:  req.Page,
		Total: total,
	}
	var resp md.GetFreePublishUserResp
	resp = md.GetFreePublishUserResp{
		Paginate: paginate,
		List:     nodes,
	}
	e.OutSuc(c, resp, nil)
}

// AddFreePublishUser
// @Summary      制度中心-公排管理-免罚用户(新增)
// @Tags         公排管理
// @Description  免罚用户(新增)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body    md.AddFreePublishUserReq  true  "免罚用户ID"
// @Success      200   {int}  	"插入数据 ID"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/publicPlatoonUserFreePunish/save [post]
func AddFreePublishUser(c *gin.Context) {
	var req *md.AddFreePublishUserReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	freePunishWithUserDb := implement.NewPublicPlatoonFreePunishWithUserDb(db.Db)
	userExist, err := freePunishWithUserDb.PublicPlatoonFreePunishWithUserGetOneByParams(map[string]interface{}{
		"key":   "uid",
		"value": req.Uid,
	})
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	if userExist != nil {
		e.OutErr(c, e.ERR_DB_ORM, "用户已在名单,无需重复添加")
		return
	}

	userDb := implement.NewUserDb(db.Db)
	user, err2 := userDb.UserGetOneByParams(map[string]interface{}{
		"key":   "id",
		"value": req.Uid,
	})
	if err2 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err2.Error())
		return
	}
	if user == nil {
		e.OutErr(c, e.ERR_DB_ORM, errors.New("该用户不存在"))
	}

	var m model.PublicPlatoonFreePunishWithUser
	m = model.PublicPlatoonFreePunishWithUser{
		Uid: req.Uid,
	}
	id, err3 := freePunishWithUserDb.PublicPlatoonFreePunishWithUserInsert(&m)
	if err3 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err3.Error())
		return
	}
	e.OutSuc(c, id, nil)
}

// DeleteFreePublishUser
// @Summary      制度中心-公排管理-免罚用户(删除)
// @Tags         公排管理
// @Description  免罚用户(删除)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body    md.DeleteFreePublishUserReq  true  "免罚用户ID"
// @Success      200   {int}  	"删除数据数量"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/publicPlatoonUserFreePunish/delete [delete]
func DeleteFreePublishUser(c *gin.Context) {
	var req *md.DeleteFreePublishUserReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	freePunishWithUserDb := implement.NewPublicPlatoonFreePunishWithUserDb(db.Db)
	affected, err := freePunishWithUserDb.PublicPlatoonFreePunishWithUserDeleteOneByUID(utils.StrToInt64(req.Uid))
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	e.OutSuc(c, affected, nil)
}

// ListCommunityDividends
// @Summary      制度中心-公排管理-社区分红(查询)
// @Tags         公排管理
// @Description  社区分红(查询)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body    md.ListCommunityDividendsReq  true  "页数、每页大小必填 起止时间、起止数量选填"
// @Success      200   {object}  md.ListCommunityDividendsResp	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/communityDividends/communityDividendsList [post]
func ListCommunityDividends(c *gin.Context) {
	var req *md.ListCommunityDividendsReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}
	dividendsDb := implement.NewEggEnergyCommunityDividendsDb(db.Db)
	dividends, total, err2 := dividendsDb.EggEnergyCommunityDividendsFindAndCount(req.Page, req.Limit, req.StartAt, req.EndAt, req.StartNums, req.EndNums)
	if err2 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err2.Error())
		return
	}
	list := make([]md.EggEnergyCommunityDividends, len(dividends))
	for i, dividend := range dividends {
		list[i] = md.EggEnergyCommunityDividends{
			Id:         dividend.Id,
			Amount:     dividend.Amount,
			Name:       dividend.Name,
			CoinId:     dividend.CoinId,
			PersonsNum: dividend.PersonsNum,
			IsOver:     dividend.IsOver,
			CreateAt:   dividend.CreateAt,
			UpdateAt:   dividend.UpdateAt,
		}
	}
	resp := md.ListCommunityDividendsResp{
		List: list,
		Paginate: md.Paginate{
			Limit: req.Limit,
			Page:  req.Page,
			Total: total,
		},
	}
	e.OutSuc(c, resp, nil)
}

// AddCommunityDividends
// @Summary      制度中心-公排管理-社区分红(新增)
// @Tags         公排管理
// @Description  社区分红(新增)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body    md.AddCommunityDividendsReq  true  "分红名称、分红总量"
// @Success      200   {success}  	"成功"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/communityDividends/communityDividendsAdd [post]
func AddCommunityDividends(c *gin.Context) {
	var req *md.AddCommunityDividendsReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	settingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
	basic, err1 := settingDb.EggEnergyBasicSettingGetOne()
	if err1 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err1.Error())
		return
	}

	rule.Init(cfg.RedisAddr)
	err2 := ruleSvc.AddCommunityDividends(db.Db, req.Amount, req.Name, *basic)
	if err2 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err2.Error())
		return
	}

	e.OutSuc(c, "success", nil)
}

// ListCommunityDividendsWithUser
// @Summary      制度中心-公排管理-社区长列表(查询)
// @Tags         公排管理
// @Description  社区长列表(查询)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body    md.ListCommunityDividendsWithUserReq  true  "页数、每页大小必填 手机号、用户ID选填"
// @Success      200   {object}  md.ListCommunityDividendsWithUserResp 	"社区长列表"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/communityDividends/communityDividendsWithUserList [post]
func ListCommunityDividendsWithUser(c *gin.Context) {
	var req *md.ListCommunityDividendsWithUserReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	var uid int64
	if req.Phone != "" {
		userDb := implement.NewUserDb(db.Db)
		user, err := userDb.UserGetOneByParams(map[string]interface{}{
			"key":   "phone",
			"value": req.Phone,
		})
		if err != nil {
			e.OutErr(c, e.ERR_DB_ORM, err.Error())
			return
		}
		uid = user.Id
	}
	if req.Uid != 0 {
		uid = req.Uid
	}

	dividendsWithUserDb := implement.NewEggEnergyCommunityDividendsWithUserDb(db.Db)
	dividendsWithUserList, total, err := dividendsWithUserDb.EggEnergyCommunityDividendsWithUserFindAndCount(req.Page, req.Limit, uid)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	list := make([]md.EggEnergyCommunityDividendsWithUser, len(dividendsWithUserList))
	if len(dividendsWithUserList) > 0 {
		uids := make([]int64, len(dividendsWithUserList))
		for i, user := range dividendsWithUserList {
			uids[i] = user.Uid
		}
		userDb := implement.NewUserDb(db.Db)
		users, err := userDb.UserFindByParams(map[string]interface{}{
			"key":   "id",
			"value": uids,
		})
		if err != nil {
			e.OutErr(c, e.ERR_DB_ORM, err.Error())
			return
		}
		userMap := make(map[int64]model.User)
		for _, user := range users {
			userMap[user.Id] = user
		}

		for i, user := range dividendsWithUserList {
			list[i] = md.EggEnergyCommunityDividendsWithUser{
				Id:       user.Id,
				Uid:      user.Uid,
				Memo:     user.Memo,
				Phone:    userMap[user.Uid].Phone,
				Nickname: userMap[user.Uid].Nickname,
			}
		}
	}

	resp := md.ListCommunityDividendsWithUserResp{
		List: list,
		Paginate: md.Paginate{
			Limit: req.Limit,
			Page:  req.Page,
			Total: total,
		},
	}

	e.OutSuc(c, resp, nil)
}

// AddCommunityDividendsWithUser
// @Summary      制度中心-公排管理-社区长列表(新增)
// @Tags         公排管理
// @Description  社区长列表(新增)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body    md.AddCommunityDividendsWithUserReq  true  "新增社区长 ID、备注"
// @Success      200   {int}  	"插入数据 ID"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/communityDividends/communityDividendsWithUserAdd [post]
func AddCommunityDividendsWithUser(c *gin.Context) {
	var req *md.AddCommunityDividendsWithUserReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	communityDividendsWithUserDb := implement.NewEggEnergyCommunityDividendsWithUserDb(db.Db)
	exist, err := communityDividendsWithUserDb.EggEnergyCommunityDividendsWithUserExist(req.Uid)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	if exist {
		e.OutErr(c, e.ERR_BAD_REQUEST, "请勿重复添加")
		return
	}

	now := time.Now()
	var m model.EggEnergyCommunityDividendsWithUser
	m = model.EggEnergyCommunityDividendsWithUser{
		Uid:      req.Uid,
		Memo:     req.Memo,
		CreateAt: now.Format("2006-01-02 15:04:05"),
		UpdateAt: now.Format("2006-01-02 15:04:05"),
	}

	id, err := communityDividendsWithUserDb.EggEnergyCommunityDividendsWithUserInsert(&m)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	e.OutSuc(c, id, nil)
}

// UserDailyActivityAnalysis
// @Summary      制度中心-公排管理-日活分析
// @Tags         公排管理
// @Description  日活分析
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body    md.UserDailyActivityAnalysisReq  true  "用户 ID、查询开始时间、结束时间(查询时间不超过30天)、页数、每页大小"
// @Success      200   {object}   md.UserDailyActivityAnalysisResp  	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/publicPlatoon/userDailyActivityAnalysis/index [post]
func UserDailyActivityAnalysis(c *gin.Context) {
	var req *md.UserDailyActivityAnalysisReq
	if err := c.ShouldBindJSON(&req); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err.Error())
		return
	}

	total, sons, err := svc.GetSonUserDailyActivity(db.Db, req.Uid, req.StartDate, req.EndDate, req.Page, req.PageSize)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	sql1 := "SELECT COUNT(*) AS total, uid FROM `egg_energy_user_activity` WHERE uid IN (SELECT uid FROM `user_relate` WHERE parent_uid = ?) AND date > ? AND date < ? GROUP BY uid"
	results, err := db.Db.QueryString(sql1, req.Uid, req.StartDate, req.EndDate)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	var activityCount, activityUserCount int64
	for _, result := range results {
		tempCount := utils.StrToInt64(result["total"])
		activityCount += tempCount
		activityUserCount++
	}

	topData := md.DailyActivityAnalysisTopData{
		TeamUserCount:         total,
		ActivityCount:         activityCount,
		TeamActivityUserCount: activityUserCount,
	}

	if sons == nil {
		sons = make([]md.SonUserDailyActivityAnalysisNode, 0)
	}

	resp := md.UserDailyActivityAnalysisResp{
		TopData:     topData,
		SonUserData: sons,
	}

	e.OutSuc(c, resp, nil)
}