package sop_task

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"wechat-api/ent/messagerecords"
	"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 SopTaskStartLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *SopTaskStartLogic) SopTaskStart(req *types.IDReq) (resp *types.BaseMsgResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	// 开始事务
	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
		).
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	if task.Status != 2 && task.Status != 4 {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	err = l.svcCtx.DB.SopTask.UpdateOneID(req.Id).
		SetStatus(3).
		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.Status(5), messagerecords.SourceType(3), messagerecords.SourceID(stage.ID)).
			All(l.ctx)
		for _, m := range messages {
			_, err := tx.MessageRecords.UpdateOneID(m.ID).SetStatus(1).Save(l.ctx)
			if err != nil {
				_ = tx.Rollback()
			}
		}
	}

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