package sop_stage

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"wechat-api/ent"
	"wechat-api/ent/sopnode"
	"wechat-api/ent/sopstage"
	"wechat-api/internal/utils/dberrorhandler"

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

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *SopStageCopyLogic) SopStageCopy(req *types.StageCopyReq) (resp *types.BaseMsgResp, err error) {
	//  查询任务及阶段
	data, err := l.svcCtx.DB.SopStage.Query().
		Where(sopstage.ID(req.Id)).
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	//  开始事务
	tx, err := l.svcCtx.DB.Tx(context.Background())
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 查询任务的阶段数量
	count, err := l.svcCtx.DB.SopStage.Query().Where(sopstage.TaskIDEQ(data.TaskID)).Count(l.ctx)

	//  创建新阶段
	newStage, err := tx.SopStage.Create().
		SetTaskID(data.TaskID).
		SetName(data.Name).
		SetConditionType(data.ConditionType).
		SetConditionOperator(data.ConditionOperator).
		SetConditionList(data.ConditionList).
		SetNotNilActionMessage(data.ActionMessage).
		SetNotNilActionLabelAdd(data.ActionLabelAdd).
		SetNotNilActionLabelDel(data.ActionLabelDel).
		SetNotNilActionForward(&data.ActionForward).
		SetIndexSort(count + 1).
		Save(l.ctx)
	if err != nil {
		_ = tx.Rollback()
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	err = CreateNodes(tx, data.ID, 0, newStage.ID, 0, l.ctx, l.Logger)
	if err != nil {
		_ = tx.Rollback()
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 所有操作成功，提交事务
	err = tx.Commit()
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

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

func CreateNodes(tx *ent.Tx, stageId uint64, parentId uint64, newStageId uint64, newParentId uint64, ctx context.Context, logger logx.Logger) (err error) {
	data, err := tx.SopNode.Query().
		Where(sopnode.StageID(stageId), sopnode.ParentID(parentId)).All(ctx)
	if err != nil {
		return nil
	}

	for _, n := range data {
		newNode, err := tx.SopNode.Create().
			SetStageID(newStageId).
			SetParentID(newParentId).
			SetName(n.Name).
			SetConditionType(n.ConditionType).
			SetConditionList(n.ConditionList).
			SetNotNilNoReplyCondition(&n.NoReplyCondition).
			SetNotNilActionMessage(n.ActionMessage).
			SetNotNilActionLabelAdd(n.ActionLabelAdd).
			SetNotNilActionLabelDel(n.ActionLabelDel).
			SetNotNilActionForward(&n.ActionForward).
			Save(ctx)
		if err != nil {
			return err
		}
		err = CreateNodes(tx, stageId, n.ID, newStageId, newNode.ID, ctx, logger)
		if err != nil {
			return err
		}
	}
	return nil
}
