package order

import (
	"context"
	"math"

	"github.com/duke-git/lancet/v2/slice"
	"github.com/gogf/gf/v2/errors/gcode"

	"kami/api/commonApi"
	v1 "kami/api/order/v1"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"
)

func (c *ControllerV1) OrderSummaryDailyGetList(ctx context.Context, req *v1.OrderSummaryDailyGetListReq) (res *v1.OrderSummaryDailyGetListRes, err error) {
	userInfo, err := service.SysAuth().LoginWithIFrameAndLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	orderService := service.OrderSummary()
	total, list, err := orderService.GetDailyStats(ctx, &model.OrderSummaryDailyListInput{
		OrderSummaryDailyGetListReq: *req,
		UserId:                      userInfo.Id,
	})
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeDbOperationError, err, "获取订单汇总列表失败")
		return
	}
	returnList := make([]*v1.OrderSummaryDailyRecord, len(list))
	slice.ForEach(list, func(index int, item *model.OrderSummaryDailyListOutput) {
		returnList[index] = &v1.OrderSummaryDailyRecord{
			SucceedShowAmount: item.SucceedShowAmount,
			TotalCount:        item.TotalCount,
			TotalFactAmount:   item.TotalFactAmount,
			MerchantUid:       item.MerchantUid,
			MerchantName:      item.MerchantName,
			TotalShowAmount:   item.TotalShowAmount,
			SucceedCount:      item.SucceedCount,
			Date:              item.Date,
			RoadUid:           item.RoadUid,
			RoadName:          item.RoadName,
			SucceedFactAmount: item.SucceedFactAmount,
			Rate:              math.Round(item.Rate*100) / 100,
			WaitedCount:       item.WaitedCount,
			FailedCount:       item.FailedCount,
		}

	})
	res = &v1.OrderSummaryDailyGetListRes{
		CommonPageRes: commonApi.CommonPageRes[*v1.OrderSummaryDailyRecord]{
			CommonDataRes: commonApi.CommonDataRes[*v1.OrderSummaryDailyRecord]{
				List: returnList,
			},
			Total: total,
		},
	}
	return
}
