package message

import (
	"github.com/gin-gonic/gin"
	"go-admin/app/admin/models"
	orm "go-admin/common/global"
	"go-admin/tools"
	"go-admin/tools/app"
	"net/http"
	"time"
)

// UserMessageList 用户消息-列表
// @Summary 用户消息-列表
// @Description 获取当前用户的消息记录
// @Tags 消息中心
// @Accept json
// @Produce json
// @Param data body models.UserMessageListReq true "消息查询参数"
// @Success 200 {object} models.UserMessageListResp
// @Router /api/v1/user_message/list [post]
func UserMessageList(c *gin.Context) {
	var req models.UserMessageListReq
	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, http.StatusBadRequest, nil, "参数错误: "+err.Error())
		return
	}

	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}

	userID := tools.GetUserId(c)
	query := orm.Eloquent.Where("user_id = ? AND is_visible = ?", userID, true)

	if req.IsRead != 0 && req.IsRead != 1 && req.IsRead != 2 {
		app.Error(c, http.StatusBadRequest, nil, "不支持的目标状态")
		return
	} else if req.IsRead == 1 {
		query = query.Where("is_read = ?", true)
	} else if req.IsRead == 2 {
		query = query.Where("is_read = ?", false)
	}

	var total int64
	if err := query.Model(&models.SystemUserMessage{}).Count(&total).Error; err != nil {
		app.Error(c, http.StatusInternalServerError, nil, "查询总数失败: "+err.Error())
		return
	}

	var messages []models.SystemUserMessage
	if err := query.Order("created_at desc").
		Offset((req.Page - 1) * req.PageSize).
		Limit(req.PageSize).
		Find(&messages).Error; err != nil {
		app.Error(c, http.StatusInternalServerError, nil, "查询列表失败: "+err.Error())
		return
	}

	var result []models.UserMessageDetailRespItem
	var configIDs []uint

	for _, msg := range messages {
		item := models.UserMessageDetailRespItem{
			ID:              uint(msg.ID),
			CreatedAt:       msg.CreatedAt,
			UserID:          msg.UserID,
			MessageConfigID: msg.MessageConfigID,
			MessageType:     msg.MessageType,
			Title:           msg.Title,
			Content:         msg.Content,
			IsRead:          msg.IsRead,
			ReadTime:        msg.ReadTime,
			IsVisible:       msg.IsVisible,
		}
		if msg.MessageType == models.AnnouncementMessageType && msg.MessageConfigID != 0 {
			configIDs = append(configIDs, msg.MessageConfigID)
		}
		result = append(result, item)
	}

	// 加载所有相关公告配置
	var configs []models.SystemMessageConfig
	if len(configIDs) > 0 {
		err := orm.Eloquent.
			Where("id IN (?)", configIDs).
			Find(&configs).Error
		if err != nil {
			app.Error(c, http.StatusInternalServerError, nil, "加载公告配置失败: "+err.Error())
			return
		}
		// 构建映射
		configMap := make(map[uint]models.SystemMessageConfig)
		for _, cfg := range configs {
			configMap[uint(cfg.ID)] = cfg
		}
		// 填充扩展字段
		for i, item := range result {
			if item.MessageType == models.AnnouncementMessageType {
				if cfg, ok := configMap[item.MessageConfigID]; ok {
					result[i].Level = cfg.Level
					result[i].DisplayMode = cfg.DisplayMode
					result[i].StartTime = cfg.StartTime
					result[i].EndTime = cfg.EndTime
				}
			}
		}
	}

	app.OK(c, models.UserMessageListResp{
		List:     result,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	}, "查询成功")
}

// UserMessageSetStatus 用户消息-设置已读（支持单条或全部）
// @Summary 用户消息-设置已读（支持单条或全部）
// @Description 设为单条或全部已读
// @Tags 消息中心
// @Accept json
// @Produce json
// @Param data body models.UserMessageSetStatusReq true "设置参数"
// @Success 200 {object} app.Response
// @Router /api/v1/user_message/set_status [post]
func UserMessageSetStatus(c *gin.Context) {
	var req models.UserMessageSetStatusReq
	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, http.StatusBadRequest, nil, "参数错误: "+err.Error())
		return
	}

	userID := tools.GetUserId(c)
	now := time.Now()
	query := orm.Eloquent.Model(&models.SystemUserMessage{}).
		Where("user_id = ? AND is_read = ?", userID, false)

	if req.ReadAll {
		// 全部设为已读
	} else {
		if len(req.ID) == 0 {
			app.Error(c, http.StatusBadRequest, nil, "参数错误: 未提供消息ID")
			return
		}
		query = query.Where("id IN ?", req.ID)
	}

	err := query.Updates(map[string]interface{}{
		"is_read":   true,
		"read_time": &now,
	}).Error
	if err != nil {
		app.Error(c, http.StatusInternalServerError, nil, "设置失败: "+err.Error())
		return
	}

	app.OK(c, nil, "设置成功")
}

// UserMessageDelete 用户消息-删除（支持单条、批量或全部）
// @Summary 用户消息-删除（支持单条、批量或全部）
// @Description 删除指定消息、批量消息或全部消息（逻辑删除，限当前用户）
// @Tags 消息中心
// @Accept json
// @Produce json
// @Param data body models.UserMessageDeleteReq true "删除参数"
// @Success 200 {object} app.Response
// @Router /api/v1/user_message/delete [post]
func UserMessageDelete(c *gin.Context) {
	var req models.UserMessageDeleteReq
	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, http.StatusBadRequest, nil, "参数错误: "+err.Error())
		return
	}

	userID := tools.GetUserId(c)
	query := orm.Eloquent.Model(&models.SystemUserMessage{}).
		Where("user_id = ?", userID).
		Where("is_visible = ?", true)

	if req.DeleteAll {
		// 删除当前用户的所有可见消息
	} else {
		if len(req.IDs) == 0 {
			app.Error(c, http.StatusBadRequest, nil, "参数错误: 未提供消息ID列表")
			return
		}

		// 校验消息是否都属于当前用户
		var count int64
		err := orm.Eloquent.
			Model(&models.SystemUserMessage{}).
			Where("id IN ?", req.IDs).
			Where("user_id = ?", userID).
			Count(&count).Error
		if err != nil {
			app.Error(c, http.StatusInternalServerError, nil, "校验失败: "+err.Error())
			return
		}

		if count != int64(len(req.IDs)) {
			app.Error(c, http.StatusForbidden, nil, "删除失败：包含不属于当前用户的消息")
			return
		}

		query = query.Where("id IN ?", req.IDs)
	}

	err := query.Updates(map[string]interface{}{
		"is_visible": false,
	}).Error
	if err != nil {
		app.Error(c, http.StatusInternalServerError, nil, "删除失败: "+err.Error())
		return
	}

	app.OK(c, nil, "删除成功")
}
