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"
)

// AliyunSmsFilePhone
// @Summary      消息中心-短信推送记录-通知模板
// @Tags         消息中心
// @Description  短信推送记录-通知模板
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param file formData string true "参数 file-----文件上传格式"
// @Success      200   {string}  			"phone 一个数组"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/aliyunSms/file/phone [post]
func AliyunSmsFilePhone(c *gin.Context) {
	notice.AliyunSmsFilePhone(c)
}

//
//// AliyunSmsList
//// @Summary      消息中心-短信推送记录-通知模板(跟app推送记录的通知模板一样的效果)
//// @Tags         消息中心
//// @Description  短信推送记录-通知模板
//// @Accept       json
//// @Produce      json
//// @param Authorization header string true "验证参数Bearer和token空格拼接"
//// @Param        req 	body      md.NoticeAliyunSmsListReq          true   "(分页信息必填)"
//// @Success      200   {object}  md.NoticeAliyunSmsListResp			"具体数据"
//// @Failure      400   {object}   md.Response              	"具体错误"
//// @Router       /api/notice/aliyunSms/list [get]
//func AliyunSmsList(c *gin.Context) {
//	notice.AliyunSmsList(c)
//}
//
//// AliyunSmsSave
//// @Summary      消息中心-短信推送记录-通知模板添加编辑
//// @Tags         消息中心
//// @Description  短信推送记录-通知模板添加编辑
//// @Accept       json
//// @Produce      json
//// @param Authorization header string true "验证参数Bearer和token空格拼接"
//// @Param        req 	body      md.NoticeAliyunSmsSaveReq          true   "参数"
//// @Success      200   {string}  			"具体数据"
//// @Failure      400   {object}   md.Response              	"具体错误"
//// @Router       /api/notice/aliyunSms/save [post]
//func AliyunSmsSave(c *gin.Context) {
//	notice.AliyunSmsSave(c)
//}
//
//// AliyunSmsDel
//// @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/aliyunSms/del [post]
//func AliyunSmsDel(c *gin.Context) {
//	notice.AliyunSmsDel(c)
//}

// AliyunSmsSaleBase
// @Summary      消息中心-短信推送记录-营销短信-通知模板
// @Tags         消息中心
// @Description  短信推送记录-营销短信-通知模板
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Success      200   {object}  md.NoticeAliyunSmsListResp			"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/aliyunSms/sale/base [get]
func AliyunSmsSaleBase(c *gin.Context) {
	notice.AliyunSmsSaleBase(c)
}

// AliyunSmsSaleSave
// @Summary      消息中心-短信推送记录-营销短信-通知模板添加编辑
// @Tags         消息中心
// @Description  短信推送记录-营销短信-通知模板添加编辑
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param        req 	body    string         true   "数组  把列表的数组传过来"
// @Success      200   {string}  			"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/aliyunSms/sale/save [post]
func AliyunSmsSaleSave(c *gin.Context) {
	notice.AliyunSmsSaleSave(c)
}

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

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

// AliyunSmsGetUserList
// @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/aliyunSms/getUserList [post]
func AliyunSmsGetUserList(c *gin.Context) {
	var req *md.AliyunSmsUserListReq
	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.AliyunSmsGetUserListResp{
		LevelsList: levelsList,
		TagsList:   tagsList,
		StateList:  stateList,
		List:       list,
		Paginate: md.Paginate{
			Limit: req.Limit,
			Page:  req.Page,
			Total: total,
		},
	}
	e.OutSuc(c, resp, nil)
}

// AliyunSmsTagList
// @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.AliyunSmsGetTagListResp    	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/aliyunSms/getTagList [get]
func AliyunSmsTagList(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.AliyunSmsGetTagListResp{
		List: list,
		Paginate: md.Paginate{
			Limit: utils.StrToInt(limit),
			Page:  utils.StrToInt(page),
			Total: total,
		},
	}
	e.OutSuc(c, resp, nil)
}

// AliyunSmsGetLevelList
// @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.AliyunSmsGetLevelListResp    	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/notice/aliyunSms/getLevelList [get]
func AliyunSmsGetLevelList(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.AliyunSmsGetLevelListResp{
		List: list,
		Paginate: md.Paginate{
			Limit: utils.StrToInt(limit),
			Page:  utils.StrToInt(page),
			Total: total,
		},
	}

	e.OutSuc(c, resp, nil)
}