// Package method 业务逻辑方法包，实现反馈相关的业务操作
package method

import (
	"context"

	"bsm/full/module/base/feedback/internal/impl"
	"bsm/full/module/base/feedback/internal/models"
	pb "bsm/full/module/base/feedback/pb"
	"git.apinb.com/bsm-sdk/core/service"
)

// List 获取反馈记录列表
// ctx: 上下文，包含用户认证信息
// in: 查询请求参数，包含分页、筛选条件等
// 返回: 反馈记录列表和总数
func List(ctx context.Context, in *pb.ListRequest) (reply *pb.ListReply, err error) {
	// 解析用户认证信息
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// 分页参数校验和设置
	if in.GetPage() < 1 {
		in.Page = 1
	}
	size := in.GetSize()
	if size < 1 || size > 50 {
		in.Size = 10
	}
	offset := (in.Page - 1) * in.GetSize()

	// 构建查询会话，预加载图片信息
	sess := impl.DBService.Preload("Images")

	// 根据机构筛选或用户身份筛选
	if in.GetAgency() != "" {
		sess = sess.Where("agency = ?", in.GetAgency())
	} else {
		userIdentity := auth.Identity
		if userIdentity != "" {
			sess = sess.Where("passport_identity = ?", userIdentity)
		}
	}

	// 用户名筛选
	username := in.GetUserName()
	if username != "" {
		sess = sess.Where("username = ?", username)
	}

	// 状态筛选
	status := in.GetStatus()
	if status != 0 {
		sess = sess.Where("status = ?", status)
	}

	// 分类筛选
	category := in.GetCategory()
	if category != "" {
		sess = sess.Where("category = ?", category)
	}

	var (
		list  []models.FeedbackItem
		count int64
	)

	// 执行查询，按创建时间倒序排列
	if err := sess.Limit(int(in.GetSize())).Offset(int(offset)).Order("created_at desc").Find(&list).Count(&count).Error; err != nil {
		return nil, err
	}

	// 构建响应结果
	out := &pb.ListReply{
		Count: count,
		List:  make([]*pb.FeedbackItem, 0, len(list)),
	}

	// 转换数据格式
	for _, v := range list {
		item := convert(v)
		out.List = append(out.List, item)
	}
	return out, nil
}
