package service

import (
	"gadmin/config"
	"gadmin/internal/admin/consts"
	"gadmin/internal/admin/forms"
	"gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"gadmin/utility/serializer"
	"github.com/gin-gonic/gin"
)

// OrderSettle 订单
var OrderSettle = new(sOrderSettle)

type sOrderSettle struct{}

func (s *sOrderSettle) List(ctx *gin.Context, req forms.OrderSettleListReq) serializer.Response {

	type OrderSettleLstModel struct {
		model.OrdersSettle
	}

	var (
		o            = query.Use(config.DB).OrdersSettle
		m            = o.WithContext(ctx)
		offset int64 = 0
		models forms.OrderSettleListRes
		lists  []OrderSettleLstModel
	)

	if len(req.Time) == 2 {
		m = m.Where(o.CreatedAt.Between(req.Time[0], req.Time[1]))
	}

	if req.UserId > 0 {
		m = m.Where(o.UserID.Eq(req.UserId))
	}

	if req.Status > 0 {
		m = m.Where(o.Status.Eq(req.Status))
	}

	if req.OrderSn != "" {
		m = m.Where(o.OrderSn.Like("%" + req.OrderSn + "%"))
	}

	m = m.Order(o.CreatedAt.Desc())

	req.Page, req.PerPage, offset = forms.CalculatePage(req.Page, req.PerPage)

	count, err := m.Count()
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错 count", err)
	}

	if count > 0 {
		// 列表展示
		if err = m.Limit(int(req.PerPage)).Offset(int(offset)).Scan(&lists); err != nil {
			return serializer.Err(consts.CodeParamErr, "查询出错 lists", err)
		}
	}

	models.List = lists
	models.Page = req.Page
	models.PerPage = req.PerPage
	models.PageCount = (count + req.PerPage - 1) / req.PerPage

	return serializer.Suc(models)
}
