package query

import (
	"context"
	"hm-server/app/main/api/internal/svc"
	"hm-server/app/main/api/internal/types"
	"hm-server/common/ctxdata"
	"hm-server/common/xerr"

	"github.com/Masterminds/squirrel"
	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type QueryListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewQueryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryListLogic {
	return &QueryListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryListLogic) QueryList(req *types.QueryListReq) (resp *types.QueryListResp, err error) {
	userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
	if getUidErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告列表查询, 获取用户信息失败, %+v", getUidErr)
	}

	// 直接构建查询query表的条件
	build := l.svcCtx.QueryModel.SelectBuilder().Where(squirrel.Eq{
		"user_id": userID,
	})

	// 直接从query表分页查询
	queryList, total, err := l.svcCtx.QueryModel.FindPageListByPageWithTotal(l.ctx, build, req.Page, req.PageSize, "create_time DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告列表查询, 查找报告列表错误, %+v", err)
	}

	var list []types.Query
	if len(queryList) > 0 {
		for _, queryModel := range queryList {
			var query types.Query
			query.CreateTime = queryModel.CreateTime.Format("2006-01-02 15:04:05")
			query.UpdateTime = queryModel.UpdateTime.Format("2006-01-02 15:04:05")
			copyErr := copier.Copy(&query, queryModel)
			if copyErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告列表查询, 报告结构体复制失败, %+v", err)
			}
			product, findProductErr := l.svcCtx.ProductModel.FindOne(l.ctx, queryModel.ProductId)
			if findProductErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告列表查询, 获取商品信息失败, %+v", err)
			}
			query.ProductName = product.ProductName
			list = append(list, query)
		}
	}

	return &types.QueryListResp{
		Total: total,
		List:  list,
	}, nil
}
