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/service"
	"youngee_b_api/util"
)

func WrapGetAllProjectHandler(ctx *gin.Context) {
	handler := newGetAllProductHandler(ctx)
	baseRun(handler)
}

type GetAllProductHandler struct {
	ctx  *gin.Context
	req  *http_model.GetAllProductRequest
	resp *http_model.CommonResponse
}

func (g GetAllProductHandler) getContext() *gin.Context {
	return g.ctx
}

func (g GetAllProductHandler) getResponse() interface{} {
	return g.resp
}

func (g GetAllProductHandler) getRequest() interface{} {
	return g.req
}

func (g GetAllProductHandler) run() {
	enterpriseID := middleware.GetSessionAuth(g.ctx).EnterpriseID
	res, err := service.Product.GetAllProduct(g.ctx, g.req, enterpriseID)
	if err != nil {
		logrus.Errorf("[GetAllProductHandler] call GetAllProduct err:%+v\n", err)
		util.HandlerPackErrorResp(g.resp, consts.ErrorInternal, "")
		logrus.Info("GetAllProduct fail,req:%+v", g.req)
		return
	}
	g.resp.Message = "项目列表查询成功"
	g.resp.Data = res
}

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

func newGetAllProductHandler(ctx *gin.Context) *GetAllProductHandler {
	return &GetAllProductHandler{
		ctx:  ctx,
		req:  http_model.NewGetAllProductRequest(),
		resp: http_model.NewGetAllProductResponse(),
	}
}
