package friend_circle

import (
	"applet/app/db"
	"applet/app/e"
	md "applet/app/md/friend_circle"
	"applet/app/svc"
	"applet/app/utils"
	"applet/app/utils/cache"
	"code.fnuoos.com/EggPlanet/egg_models.git/src/implement"
	md2 "code.fnuoos.com/EggPlanet/egg_system_rules.git/md"
	svc2 "code.fnuoos.com/EggPlanet/egg_system_rules.git/svc"
	"code.fnuoos.com/go_rely_warehouse/zyos_go_es.git/es"
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
	"strconv"
	"time"
)

// GetDynamic
// @Summary      社交管理-动态设置-动态(获取)
// @Tags         动态设置
// @Description  动态(获取)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.GetDynamicReq 	false  "筛选条件"
// @Success      200   {object}   md.GetDynamicResp	"生成的黑名单id"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router        /api/friendCircleSettings/dynamic/index [POST]
func GetDynamic(c *gin.Context) {
	var req md.GetDynamicReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		err = svc.HandleValidateErr(err)
		err1 := err.(e.E)
		e.OutErr(c, err1.Code, err1.Error())
		return
	}

	var userIds []int64
	if req.Nickname != "" {
		var users []md.UserIdsGetFromNickname
		nickname := "%" + req.Nickname + "%"
		err = db.Db.Table("user").Where("nickname like ?", nickname).Find(&users)
		if err != nil {
			e.OutErr(c, e.ERR_DB_ORM, err.Error())
			return
		}
		for _, user := range users {
			userIds = append(userIds, user.Id)
		}
	}

	if req.Uid != "" {
		uid := utils.StrToInt64(req.Uid)
		userIds = append(userIds, uid)
	}

	if req.Page == 0 {
		req.Page = 1
	}
	if req.Limit == 0 {
		req.Limit = 10
	}

	aliasName := md2.EggFriendCircleEsAlias
	boolQuery := elastic.NewBoolQuery()
	if userIds != nil {
		boolQuery.Filter(elastic.NewTermsQuery("uid", userIds))
	}
	if req.BeginAt != "" && req.EndAt != "" {
		boolQuery.Filter(elastic.NewRangeQuery("created_at").Gte(req.BeginAt).Lte(req.EndAt).Format("yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"))
	}
	searchResult, err := es.EsClient.Search().
		Index(aliasName).
		Query(boolQuery).
		From((req.Page-1)*req.Limit).Size(req.Limit).
		Sort("created_at", true).
		Pretty(true).
		Do(context.Background())
	if err != nil {
		e.OutErr(c, e.ERR, err.Error())
		return
	}

	var docs []md.EggFriendCircleNode
	var docUserIds []int64
	var total int64
	// 检查是否有结果
	if searchResult.Hits.TotalHits.Value != 0 {
		// 解析结果
		total = searchResult.Hits.TotalHits.Value
		for _, hit := range searchResult.Hits.Hits {
			var doc md.EggFriendCircleNode
			err = json.Unmarshal(hit.Source, &doc)
			if err != nil {
				return
			}
			docUserIds = append(docUserIds, doc.Uid)
			doc.IndexId = hit.Id
			docs = append(docs, doc)
		}
	}

	adminDb := implement.NewAdminDb(db.Db)
	admins, err := adminDb.AdminFindByParams(map[string]interface{}{
		"key":   "adm_id",
		"value": docUserIds,
	})
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	adminMap := make(map[int64]string)
	for _, admin := range admins {
		adminMap[int64(admin.AdmId)] = admin.Username
	}

	userDb := implement.NewUserDb(db.Db)
	users, err := userDb.UserFindByParams(map[string]interface{}{
		"key":   "id",
		"value": docUserIds,
	})
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	userMap := make(map[int64]string)
	for _, user := range users {
		userMap[user.Id] = user.Nickname
	}
	redisConn := cache.GetPool().Get()
	scheme, domain := svc2.ImageBucket(db.Db, redisConn)
	for _, doc := range docs {
		switch doc.Kind {
		case 1:
			doc.Username = userMap[doc.Uid]
		case 2:
			doc.Username = adminMap[doc.Uid]

		}
		doc.Image = svc2.ImageFormatWithBucket(scheme, domain, doc.Image)
		doc.Video = svc2.ImageFormatWithBucket(scheme, domain, doc.Video)
	}

	resp := md.GetDynamicResp{
		List: docs,
		Paginate: md.Paginate{
			Limit: req.Limit,
			Page:  req.Page,
			Total: total,
		},
	}
	e.OutSuc(c, resp, nil)
}

// UpdateDynamic
// @Summary      社交管理-动态设置-动态(更新)
// @Tags         动态设置
// @Description  动态(更新)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.UpdateDynamicReq 	true  "更新动态id必填"
// @Success      200   {string}  	"success"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router        /api/friendCircleSettings/dynamic/update [POST]
func UpdateDynamic(c *gin.Context) {
	var req md.UpdateDynamicReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		err = svc.HandleValidateErr(err)
		err1 := err.(e.E)
		e.OutErr(c, err1.Code, err1.Error())
		return
	}
	updateMap := make(map[string]interface{})
	if req.State != 0 {
		updateMap["state"] = req.State
	}
	if req.IsTopUp != 0 {
		updateMap["is_top_up"] = req.IsTopUp
	}
	if req.IsPraise != 0 {
		updateMap["is_praise"] = req.IsPraise
	}

	aliasName := md2.EggFriendCircleEsAlias
	_, err = es.EsClient.Update().
		Index(aliasName).
		Id(req.IndexId).
		Doc(updateMap).
		Do(context.Background())
	if err != nil {
		e.OutErr(c, e.ERR, err.Error())
		return
	}

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

// DeleteDynamic
// @Summary      社交管理-动态设置-动态(删除)
// @Tags         动态设置
// @Description  动态(删除)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.DeleteDynamicReq 	true  "删除动态id必填"
// @Success      200   {string}  	"success"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router        /api/friendCircleSettings/dynamic/del [DELETE]
func DeleteDynamic(c *gin.Context) {
	var req md.DeleteDynamicReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		err = svc.HandleValidateErr(err)
		err1 := err.(e.E)
		e.OutErr(c, err1.Code, err1.Error())
		return
	}

	aliasName := md2.EggFriendCircleEsAlias
	_, err = es.EsClient.Delete().
		Index(aliasName).
		Id(req.IndexId).
		Do(context.Background())
	if err != nil {
		e.OutErr(c, e.ERR, err.Error())
		return
	}

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

// ReleaseDynamic
// @Summary      社交管理-动态设置-动态(发布)
// @Tags         动态设置
// @Description  动态(发布)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.ReleaseDynamicReq 	true  "发布动态信息"
// @Success      200   {string}  	"success"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/friendCircleSettings/dynamic/release [POST]
func ReleaseDynamic(c *gin.Context) {
	var req md.ReleaseDynamicReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		err = svc.HandleValidateErr(err)
		err1 := err.(e.E)
		e.OutErr(c, err1.Code, err1.Error())
		return
	}

	user := svc.GetUser(c)
	if req.State == 0 {
		req.State = 1
	}
	if req.Kind == 0 {
		req.Kind = 1
	}
	if req.IsPraise == 0 {
		req.IsPraise = 2
	}
	if req.IsTopUp == 0 {
		req.IsTopUp = 2
	}

	now := time.Now()
	m := md2.EggFriendCircleEs{
		Uid:         int64(user.AdmId),
		Kind:        req.Kind,
		Content:     req.Content,
		Image:       utils.SerializeStr(req.Image),
		Video:       req.Video,
		LikesNums:   0,
		ShareNums:   0,
		CommentNums: 0,
		State:       req.State,
		IsTopUp:     req.IsTopUp,
		IsPraise:    req.IsPraise,
		CreatedAt:   now.Format("2006-01-02 15:04:05"),
		UpdatedAt:   now.Format("2006-01-02 15:04:05"),
	}

	createDocRet, err := es.CreateDoc(md2.EggFriendCircleEsIndex, strconv.FormatInt(int64(user.AdmId), 10)+"_"+utils.Int64ToStr(now.Unix()), m)
	fmt.Printf("CreateDoc ==> %+v \n\n", createDocRet)
	e.OutSuc(c, "success", nil)
}