package sop_node

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

	"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 DeleteSopNodeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *DeleteSopNodeLogic) DeleteSopNode(req *types.IDReq) (*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)
	}

	// 开始一个新的事务
	tx, err := l.svcCtx.DB.Tx(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 确保在函数返回时回滚事务，除非提交事务成功
	defer func() {
		if err != nil {
			if rbErr := tx.Rollback(); rbErr != nil {
				l.Logger.Errorf("tx rollback error: %v", rbErr)
			}
		} else {
			if commitErr := tx.Commit(); commitErr != nil {
				err = commitErr
			}
		}
	}()

	// 首先删除所有子节点
	err = l.deleteChildren(tx, req.Id)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 删除节点本身
	_, err = tx.SopNode.Delete().Where(sopnode.IDIn(req.Id)).Exec(l.ctx)
	if err != nil {
		_ = tx.Rollback()
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

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

func (l *DeleteSopNodeLogic) deleteChildren(tx *ent.Tx, parentID uint64) error {
	// 查找所有子节点
	children, err := tx.SopNode.Query().Where(sopnode.ParentID(parentID)).All(l.ctx)
	if err != nil {
		return err
	}

	// 对每个子节点递归执行删除操作
	for _, child := range children {
		err := l.deleteChildren(tx, child.ID)
		if err != nil {
			return err
		}

		_, err = tx.SopNode.Delete().Where(sopnode.ID(child.ID)).Exec(l.ctx)
		if err != nil {
			return err
		}
	}

	return nil
}
