package handler

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"youngee_b_api/consts"
	"youngee_b_api/middleware"
	"youngee_b_api/model/http_model"
	"youngee_b_api/pack"
	"youngee_b_api/service/selection_service"
	"youngee_b_api/util"
)

func WrapFindAllSelectionHandler(ctx *gin.Context) {
	handler := newFindAllSelection(ctx)
	baseRun(handler)
}

type FindAllSelectionHandler struct {
	ctx  *gin.Context
	req  *http_model.FindAllSelectionRequest
	resp *http_model.CommonResponse
}

func (f FindAllSelectionHandler) getContext() *gin.Context {
	return f.ctx
}

func (f FindAllSelectionHandler) getResponse() interface{} {
	return f.resp
}

func (f FindAllSelectionHandler) getRequest() interface{} {
	return f.req
}

func (f FindAllSelectionHandler) run() {
	enterpriseID := middleware.GetSessionAuth(f.ctx).EnterpriseID
	fmt.Printf("2企业ID2 %+v", enterpriseID)
	condition := pack.HttpFindAllSelectionRequestToCondition(f.req)
	data, err := selection_service.Selection.GetAllSelection(f.ctx, enterpriseID, f.req.PageSize, f.req.PageNum, condition)
	if err != nil {
		logrus.WithContext(f.ctx).Errorf("[FindAllSelectionHandler] error GetAllSelection, err:%+v", err)
		util.HandlerPackErrorResp(f.resp, consts.ErrorInternal, consts.DefaultToast)
		return
	}
	f.resp.Data = data
}

func (f FindAllSelectionHandler) checkParam() error {
	var errs []error
	if f.req.PageNum < 0 || f.req.PageSize <= 0 {
		errs = append(errs, errors.New("page param error"))
	}
	f.req.PageNum--
	if len(errs) != 0 {
		return fmt.Errorf("check param errs:%+v", errs)
	}
	return nil
}

func newFindAllSelection(ctx *gin.Context) *FindAllSelectionHandler {
	return &FindAllSelectionHandler{
		ctx:  ctx,
		req:  http_model.NewFindAllSelectionRequest(),
		resp: http_model.NewFindAllSelectionResponse(),
	}
}
