package sop_stage

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

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

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

func (l *DeleteSopStageLogic) DeleteSopStage(req *types.IDReq) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	// 根据 id 关联查询 task 信息，并判断 task 的状态是否为 1
	data, err := l.svcCtx.DB.SopStage.Query().
		Where(sopstage.ID(req.Id)).
		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)
	}

	// 开始一个新的事务
	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
			}
		}
	}()

	// 获取阶段信息
	stage, err := tx.SopStage.Get(l.ctx, req.Id)
	indexSort := stage.IndexSort
	taskId := stage.TaskID

	_, err = tx.SopStage.Delete().Where(sopstage.ID(req.Id)).Exec(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 将具有同一 task_id 且 index_sort 大于当前阶段的阶段 index_sort 减一
	err = tx.SopStage.Update().Where(sopstage.TaskIDEQ(taskId), sopstage.IndexSortGT(indexSort)).AddIndexSort(-1).Exec(l.ctx)

	_, err = tx.SopNode.Delete().Where(sopnode.StageID(req.Id)).Exec(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

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