package sop_task

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

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

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

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

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

func (l *SopTaskStopLogic) SopTaskStop(req *types.IDReq) (resp *types.BaseMsgResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	isAdmin := l.ctx.Value("isAdmin").(bool)
	// 开始事务
	tx, err := l.svcCtx.DB.Tx(context.Background())
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 根据 id 查询 task 信息，如果 Status 的值不为 1，则不允许修改
	task, err := tx.SopTask.Query().
		Where(
			soptask.IDEQ(req.Id),                   // Filter by ID
			soptask.OrganizationID(organizationId), // Additional filter by organizationId
		).
		WithTaskStages().
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	if task.Status != 3 {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	if isAdmin || organizationId == 12 {
		err = tx.SopTask.UpdateOneID(req.Id).
			SetStatus(1).
			Exec(l.ctx)
		sourceInfo, err := l.svcCtx.DB.SopStage.Query().
			Where(sopstage.TaskID(req.Id)).
			WithStageNodes().
			All(l.ctx)
		if err != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
		for _, stage := range sourceInfo {
			_, err := tx.MessageRecords.Delete().Where(messagerecords.SourceIDEQ(stage.ID)).Exec(l.ctx)

			if err != nil {
				return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
			}
			for _, node := range stage.Edges.StageNodes {
				_, err := tx.MessageRecords.Delete().Where(messagerecords.SourceIDEQ(node.ID)).Exec(l.ctx)
				if err != nil {
					return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
				}
			}
		}
	} else {
		err = tx.SopTask.UpdateOneID(req.Id).
			SetStatus(2).
			Exec(l.ctx)
	}

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

	// 查询task的所有sop_stages
	for _, stage := range task.Edges.TaskStages {
		// 更新最旧的 p.Number 条 status 值为 1 或 4 的 message_records 记录的 status 为 2
		messages, _ := tx.MessageRecords.Query().
			Where(messagerecords.StatusIn(1, 2, 4), messagerecords.SourceType(3), messagerecords.SourceID(stage.ID)).
			All(l.ctx)
		for _, m := range messages {
			_, err := tx.MessageRecords.UpdateOneID(m.ID).SetStatus(5).Save(l.ctx)
			if err != nil {
				_ = tx.Rollback()
			}
		}
	}
	err = tx.Commit()
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
}
