package sop_node

import (
	"context"
	"wechat-api/ent"
	"wechat-api/ent/custom_types"
	"wechat-api/ent/sopnode"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

func (l *UpdateSopNodeLogic) UpdateSopNode(req *types.SopNodeInfo) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	// 根据 id 关联查询处 task 信息，并判断 status 是否为 1
	data, err := l.svcCtx.DB.SopNode.Query().
		Where(sopnode.ID(*req.Id)).
		WithSopStage(func(query *ent.SopStageQuery) {
			query.WithSopTask()
		}).
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	task := data.Edges.SopStage.Edges.SopTask
	if task.Status != 1 || task.OrganizationID != organizationId {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	var actionMessage []custom_types.Action
	if len(req.ActionMessage) > 0 {
		actionMessage = make([]custom_types.Action, len(req.ActionMessage))
		for i, condition := range req.ActionMessage {
			if condition.Type == 1 {
				actionMessage[i] = custom_types.Action{
					Type:    condition.Type,
					Content: condition.Content,
				}
			} else {
				actionMessage[i] = custom_types.Action{
					Type:    condition.Type,
					Content: condition.Content,
					Meta: &custom_types.Meta{
						Filename: condition.Meta.Filename,
					},
				}
			}
		}
	}

	var forward *custom_types.ActionForward
	if req.ActionForward != nil {
		forward = &custom_types.ActionForward{}
		forward.Wxid = req.ActionForward.Wxid
		var forwardAction []custom_types.Action
		if len(req.ActionForward.Action) > 0 {
			forwardAction = make([]custom_types.Action, len(req.ActionForward.Action))
			for i, condition := range req.ActionForward.Action {
				if condition.Type == 1 {
					forwardAction[i] = custom_types.Action{
						Type:    condition.Type,
						Content: condition.Content,
					}
				} else {
					forwardAction[i] = custom_types.Action{
						Type:    condition.Type,
						Content: condition.Content,
						Meta: &custom_types.Meta{
							Filename: condition.Meta.Filename,
						},
					}
				}
			}
		}
		forward.Action = forwardAction
	} else {
		forward = nil
	}

	var noReplyCondition uint64
	if req.NoReplyCondition == nil {
		noReplyCondition = 0
	} else {
		noReplyCondition = *req.NoReplyCondition
	}

	createStmt := l.svcCtx.DB.SopNode.UpdateOneID(*req.Id).
		SetStageID(*req.StageId).
		SetName(*req.Name).
		SetConditionType(*req.ConditionType).
		SetConditionList(req.ConditionList).
		SetNoReplyCondition(noReplyCondition).
		SetNoReplyUnit(*req.NoReplyUnit).
		SetNotNilActionMessage(actionMessage).
		SetNotNilActionLabelAdd(req.ActionLabelAdd).
		SetNotNilActionLabelDel(req.ActionLabelDel)

	if forward != nil {
		createStmt.SetActionForward(forward)
	} else {
		createStmt.ClearActionForward()
	}

	err = createStmt.Exec(l.ctx)

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

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