package sop_node

import (
	"context"
	"fmt"
	"wechat-api/ent/custom_types"
	"wechat-api/ent/sopstage"
	"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 CreateSopNodeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *CreateSopNodeLogic) CreateSopNode(req *types.SopNodeInfo) (*types.SopNodeCreateResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	// 根据 id 关联查询处 task 信息，并判断 status 是否为 1
	data, err := l.svcCtx.DB.SopStage.Query().
		Where(sopstage.ID(*req.StageId)).
		WithSopTask().
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	task := data.Edges.SopTask
	if task.Status != 1 || task.OrganizationID != organizationId {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	fmt.Printf("req.ActionMessage: %+v\n", req.ActionMessage)
	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
	}

	createStmt := l.svcCtx.DB.SopNode.Create().
		SetNotNilStatus(req.Status).
		SetNotNilStageID(req.StageId).
		SetNotNilParentID(req.ParentId).
		SetNotNilName(req.Name).
		SetNotNilConditionType(req.ConditionType).
		SetNotNilConditionList(req.ConditionList).
		SetNotNilNoReplyCondition(req.NoReplyCondition).
		SetNotNilNoReplyUnit(req.NoReplyUnit).
		SetNotNilActionMessage(actionMessage).
		SetNotNilActionLabelAdd(req.ActionLabelAdd).
		SetNotNilActionLabelDel(req.ActionLabelDel)

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

	newNode, err := createStmt.Save(l.ctx)

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

	return &types.SopNodeCreateResp{BaseDataInfo: types.BaseDataInfo{Msg: errormsg.CreateSuccess}, Data: newNode.ID}, nil
}
