package handler

import (
	"errors"
	"fmt"
	"time"
	"youngee_b_api/consts"
	"youngee_b_api/middleware"
	"youngee_b_api/model/http_model"
	"youngee_b_api/pack"
	"youngee_b_api/service"
	"youngee_b_api/util"

	"github.com/issue9/conv"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func WrapProjectDraftBoxListHandler(ctx *gin.Context) {
	handler := newProjectDraftListHandler(ctx)
	baseRun(handler)
}

func newProjectDraftListHandler(ctx *gin.Context) *ProjectDraftListHandler {
	return &ProjectDraftListHandler{
		req:  http_model.NewProjectDraftListRequest(),
		resp: http_model.NewProjectDraftListResponse(),
		ctx:  ctx,
	}
}

type ProjectDraftListHandler struct {
	req  *http_model.ProjectDraftListRequest
	resp *http_model.CommonResponse
	ctx  *gin.Context
}

func (h *ProjectDraftListHandler) getRequest() interface{} {
	return h.req
}
func (h *ProjectDraftListHandler) getContext() *gin.Context {
	return h.ctx
}
func (h *ProjectDraftListHandler) getResponse() interface{} {
	return h.resp
}
func (h *ProjectDraftListHandler) run() {
	enterpriseID := middleware.GetSessionAuth(h.ctx).EnterpriseID
	condition := pack.HttpProjectDraftRequestToCondition(h.req)
	data, err := service.Project.GetProjectDraftList(h.ctx, enterpriseID, h.req.PageSize, h.req.PageNum, condition)
	if err != nil {
		logrus.WithContext(h.ctx).Errorf("[ProjectDraftListHandler] error GetProjectDraftList, err:%+v", err)
		util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, consts.DefaultToast)
		return
	}
	h.resp.Data = data
}
func (h *ProjectDraftListHandler) checkParam() error {
	var errs []error
	if h.req.PageNum < 0 || h.req.PageSize <= 0 {
		errs = append(errs, errors.New("page param error"))
	}
	h.req.PageNum--
	h.req.ProjectForm = util.IsNull(h.req.ProjectForm)
	if _, err := conv.Int64(h.req.ProjectForm); err != nil {
		errs = append(errs, err)
	}
	// h.req.ProjectId = util.IsNull(h.req.ProjectId)
	// if _, err := conv.Int64(h.req.ProjectId); err != nil {
	// 	errs = append(errs, err)
	// }
	//h.req.ProjectName = util.IsNull(h.req.ProjectName)

	h.req.ProjectStatus = util.IsNull(h.req.ProjectStatus)
	if _, err := conv.Int64(h.req.ProjectStatus); err != nil {
		errs = append(errs, err)
	}
	formatTime, _ := time.Parse("2006-01-02 15:04:05", h.req.ProjectUpdated)
	//fmt.Println(h.req.ProjectUpdated)
	h.req.ProjectUpdated = util.IsNull(h.req.ProjectUpdated)
	if _, err := conv.Int64(formatTime.Unix()); err != nil {
		errs = append(errs, err)
	}
	h.req.ProjectContentType = util.IsNull(h.req.ProjectContentType)
	if _, err := conv.Int64(h.req.ProjectContentType); err != nil {
		errs = append(errs, err)
	}
	h.req.ProjectPlatform = util.IsNull(h.req.ProjectPlatform)
	if _, err := conv.Int64(h.req.ProjectPlatform); err != nil {
		errs = append(errs, err)
	}
	if len(errs) != 0 {
		return fmt.Errorf("check param errs:%+v", errs)
	}
	return nil
}
