package sop_task

import (
	"context"
	"fmt"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateSopTaskLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateSopTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateSopTaskLogic {
	return &CreateSopTaskLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateSopTaskLogic) CreateSopTask(req *types.SopTaskInfo) (*types.SopTaskCreateResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	//departmentId := l.ctx.Value("departmentId").(uint64)

	// 判断 planEndTime 和 planStartTime 是否非空，且 planEndTime 是否大于 planStartTime
	if req.PlanEndTime != nil && req.PlanStartTime != nil && (*req.PlanEndTime <= *req.PlanStartTime) {
		return nil, dberrorhandler.DefaultEntError(l.Logger, fmt.Errorf("planEndTime must be greater than planStartTime"), req)
	}

	currentUserID, _ := l.ctx.Value("userId").(string)
	fmt.Printf("ctx: %s\n\n", currentUserID)
	newTask, err := l.svcCtx.DB.SopTask.Create().
		SetNotNilStatus(req.Status).
		SetNotNilName(req.Name).
		SetNotNilBotWxidList(req.BotWxidList).
		SetNotNilType(req.Type).
		SetNotNilPlanStartTime(pointy.GetTimeMilliPointer(req.PlanStartTime)).
		SetNotNilPlanEndTime(pointy.GetTimeMilliPointer(req.PlanEndTime)).
		SetNotNilCreatorID(&currentUserID).
		SetOrganizationID(organizationId).
		Save(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	return &types.SopTaskCreateResp{BaseDataInfo: types.BaseDataInfo{Msg: errormsg.CreateSuccess}, Data: newTask.ID}, nil
}
