package sop_task

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

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

func (l *GetSopTaskDetailLogic) GetSopTaskDetail(req *types.IDReq) (resp *types.SopTaskInfoResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	data, err := l.svcCtx.DB.SopTask.Query().
		Where(soptask.ID(req.Id), soptask.OrganizationIDEQ(organizationId)).
		WithTaskStages().
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	return &types.SopTaskInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.SopTaskInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Status:        &data.Status,
			Name:          &data.Name,
			BotWxidList:   data.BotWxidList,
			Type:          &data.Type,
			PlanStartTime: pointy.GetUnixMilliPointer(data.PlanStartTime.UnixMilli()),
			PlanEndTime:   pointy.GetUnixMilliPointer(data.PlanEndTime.UnixMilli()),
			CreatorId:     &data.CreatorID,
		},
	}, nil
}
