package sop_task

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/soptask"
	"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 UpdateSopTaskLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *UpdateSopTaskLogic) UpdateSopTask(req *types.SopTaskInfo) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(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)
	}

	err := l.svcCtx.DB.SopTask.UpdateOneID(*req.Id).
		Where(soptask.StatusEQ(1), soptask.OrganizationID(organizationId)).
		SetNotNilStatus(req.Status).
		SetNotNilName(req.Name).
		SetNotNilBotWxidList(req.BotWxidList).
		SetNotNilType(req.Type).
		SetNotNilPlanStartTime(pointy.GetTimeMilliPointer(req.PlanStartTime)).
		SetNotNilPlanEndTime(pointy.GetTimeMilliPointer(req.PlanEndTime)).
		SetNotNilCreatorID(req.CreatorId).
		SetNotNilToken(req.Token).
		Exec(l.ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return nil, errorx.NewInvalidArgumentError("未发布状态的SOP才可以编辑")
		}
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
}
