package notice

import (
	"applet/app/db"
	"applet/app/e"
	"applet/app/md"
	svc2 "applet/app/svc"
	svc "applet/app/svc/member_center"
	"applet/app/svc/notice"
	"applet/app/utils"
	"code.fnuoos.com/EggPlanet/egg_models.git/src/implement"
	"github.com/gin-gonic/gin"
)

// List
// @Summary      消息中心-基本配置-通知模板
// @Tags         消息中心
// @Description  基本配置-通知模板
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param        req 	body      md.NoticeListReq          true   "(分页信息必填)"
// @Success      200   {object}  md.NoticeListResp			"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/base/list [post]
func List(c *gin.Context) {
	notice.List(c)
}

// Save
// @Summary      消息中心-基本配置-通知模板添加编辑
// @Tags         消息中心
// @Description  基本配置-通知模板添加编辑
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param        req 	body      md.NoticeSaveReq          true   "(分页信息必填)"
// @Success      200   {string}  			"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/base/save [post]
func Save(c *gin.Context) {
	notice.Save(c)
}

// Del
// @Summary      消息中心-基本配置-通知模板删除
// @Tags         消息中心
// @Description  基本配置-通知模板删除
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param        req 	body      md.NoticeDelReq          true   "(分页信息必填)"
// @Success      200   {string}  			"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/base/del [post]
func Del(c *gin.Context) {
	notice.Del(c)
}

// PushList
// @Summary      消息中心-基本配置-推送记录列表
// @Tags         消息中心
// @Description  基本配置-推送记录列表
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param        req 	body      md.NoticeListReq          true   "(分页信息必填)"
// @Success      200   {object}  md.NoticePushListResp			"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/jPush/push/list [post]
func PushList(c *gin.Context) {
	notice.PushList(c)
}

// PushSave
// @Summary      消息中心-基本配置-推送记录添加-发送(不做编辑了)
// @Tags         消息中心
// @Description  基本配置-推送记录添加-发送 (不做编辑了)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param        req 	body      md.NoticePushSaveReq          true   "(分页信息必填)"
// @Success      200   {string}  			"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/jPush/push/save [post]
func PushSave(c *gin.Context) {
	notice.PushSave(c)
}

// JPushGetUserList
// @Summary      消息中心-基本配置-获取用户信息
// @Tags         消息中心
// @Description  获取用户信息
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param        req 	body      md.JPushGetUserListReq          true   "(分页信息必填)"
// @Success      200   {Object}    md.JPushGetUserListResp			"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/jPush/getUserList [post]
func JPushGetUserList(c *gin.Context) {
	var req *md.JPushGetUserListReq
	if err := c.ShouldBindJSON(&req); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err.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
	}

	tagDb := implement.NewUserTagDb(db.Db)
	tags, err2 := tagDb.UserTagAllByAsc()
	if err2 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err2.Error())
		return
	}
	tagsList := make([]map[string]interface{}, 0)
	tagsMap := make(map[int]string)
	for _, tag := range tags {
		tagsList = append(tagsList, map[string]interface{}{
			"id":   tag.Id,
			"name": tag.TagName,
		})
		tagsMap[tag.Id] = tag.TagName
	}

	stateList := []map[string]interface{}{
		{
			"name":  "正常",
			"value": "1",
		},
		{
			"name":  "冻结",
			"value": "2",
		},
	}
	userMemberRequest := req.ToUserMemberRequest()
	users, total, err3 := svc.UserManagementGetUsers(userMemberRequest)
	if err3 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err3.Error())
		return
	}
	userIDs := make([]int64, len(users))
	for i, user := range users {
		userIDs[i] = user.Id
	}

	recordsDb := implement.NewUserTagRecordsDb(db.Db)
	records, err := recordsDb.UserTagRecordsFindByParams(map[string]interface{}{
		"key":   "uid",
		"value": userIDs,
	})
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	var levelCounts []md.LevelCount
	err4 := db.Db.Table("user").Select("level, Count(*) AS count").GroupBy("level").Find(&levelCounts)
	if err4 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err4.Error())
		return
	}

	userMap := make(map[int64]int, len(users))
	list := make([]md.GetUserListNode, len(users))
	for i, user := range users {
		list[i] = md.GetUserListNode{
			ID:               user.Id,
			Sex:              user.Sex,
			Avatar:           svc2.GetOssUrl(user.Avatar),
			Nickname:         user.Nickname,
			Phone:            user.Phone,
			IsRealName:       user.IsRealName,
			InviteCode:       user.SystemInviteCode,
			ParentID:         user.ParentUid,
			ParentInviteCode: user.ParentSystemInviteCode,
			ParentPhone:      user.Phone,
			RegisterTime:     user.CreateAt,
			Memo:             user.Memo,
			Wechat:           user.UnionId,
			RegisterType:     user.RegisterType,
			State:            user.State,
			LastLoginAt:      user.UpdateAt,
		}
		var tempTagList []md.TagNode
		list[i].Tag = tempTagList
		userMap[user.Id] = i
		level, ok := levelsMap[user.Level]
		if ok {
			list[i].LevelName = level
		}
	}

	for _, record := range *records {
		tempTagNode := md.TagNode{
			TagID:   record.TagId,
			TagName: tagsMap[record.TagId],
		}
		list[userMap[record.Uid]].Tag = append(list[userMap[record.Uid]].Tag, tempTagNode)
	}

	resp := md.JPushGetUserListResp{
		LevelsList: levelsList,
		TagsList:   tagsList,
		StateList:  stateList,
		List:       list,
		Paginate: md.Paginate{
			Limit: req.Limit,
			Page:  req.Page,
			Total: total,
		},
	}
	e.OutSuc(c, resp, nil)
}

// JPushGetTagList
// @Summary      消息中心-基本配置-标签管理(获取)
// @Tags         消息中心
// @Description  标签管理(获取)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    limit    query	 int 	true  "每页大小"
// @Param    page    query	 int 	true  "页数"
// @Success      200   {object}  md.JPushGetTagListResp    	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/jPush/getTagList [get]
func JPushGetTagList(c *gin.Context) {
	page := c.DefaultQuery("page", "1")
	limit := c.DefaultQuery("limit", "10")

	list, total, err := svc.TagManagementGetList(page, limit)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	resp := md.JPushGetTagListResp{
		List: list,
		Paginate: md.Paginate{
			Limit: utils.StrToInt(limit),
			Page:  utils.StrToInt(page),
			Total: total,
		},
	}
	e.OutSuc(c, resp, nil)
}

// JPushGetLevelList
// @Summary      消息中心-基本配置-等级管理(获取)
// @Tags         消息中心
// @Description  等级管理(获取)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    limit    query	 int 	true  "每页大小"
// @Param    page    query	 int 	true  "页数"
// @Success      200   {object}  md.JPushGetLevelListResp    	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/jPush/getLevelList [get]
func JPushGetLevelList(c *gin.Context) {
	page := c.DefaultQuery("page", "1")
	limit := c.DefaultQuery("limit", "10")

	list, total, err := svc.LevelManagementGetLevelList(page, limit)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	resp := md.JPushGetLevelListResp{
		List: list,
		Paginate: md.Paginate{
			Limit: utils.StrToInt(limit),
			Page:  utils.StrToInt(page),
			Total: total,
		},
	}

	e.OutSuc(c, resp, nil)
}