package sop_task

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

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

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetSopTaskByIdLogic) GetSopTaskById(req *types.IDReq) (*types.SopTaskInfoResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	data, err := l.svcCtx.DB.SopTask.Query().
		Where(soptask.ID(req.Id), soptask.OrganizationIDEQ(organizationId)).
		WithTaskStages(func(q *ent.SopStageQuery) {
			q.Order(ent.Asc("index_sort"))
		}).
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	stageList := make([]types.SopStageInfo, 0)
	if data.Edges.TaskStages != nil {
		for _, ts := range data.Edges.TaskStages {
			stageList = append(stageList, types.SopStageInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id: &ts.ID,
				},
				Status:            &ts.Status,
				TaskId:            &ts.TaskID,
				Name:              &ts.Name,
				ConditionType:     &ts.ConditionType,
				ConditionOperator: &ts.ConditionOperator,
				IndexSort:         &ts.IndexSort,
			})
		}
	}

	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,
			StageList:     stageList,
		},
	}, nil
}
