package sop_node

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

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

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

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

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

func (l *GetSopNodeDetailLogic) GetSopNodeDetail(req *types.IDReq) (resp *types.SopNodeInfoResp, err error) {
	data, err := l.svcCtx.DB.SopNode.Get(l.ctx, req.Id)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	var actionMessage []types.Action
	if len(data.ActionMessage) > 0 {
		actionMessage = make([]types.Action, len(data.ActionMessage))
		for i, condition := range data.ActionMessage {
			actionMessage[i] = types.Action{
				Type:    condition.Type,
				Content: condition.Content,
			}
		}
	}

	var actionForward *types.ActionForward
	if data.ActionForward != nil {
		actionForward = &types.ActionForward{}
		actionForward.Wxid = data.ActionForward.Wxid
		if len(data.ActionForward.Action) > 0 {
			forwardAction := make([]types.Action, len(data.ActionForward.Action))
			for i, condition := range data.ActionForward.Action {
				forwardAction[i] = types.Action{
					Type:    condition.Type,
					Content: condition.Content,
				}
			}
			actionForward.Action = forwardAction
		}
	} else {
		actionForward = nil
	}

	return &types.SopNodeInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.SopNodeInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Status:           &data.Status,
			StageId:          &data.StageID,
			ParentId:         &data.ParentID,
			Name:             &data.Name,
			ConditionType:    &data.ConditionType,
			ConditionList:    data.ConditionList,
			NoReplyCondition: &data.NoReplyCondition,
			NoReplyUnit:      &data.NoReplyUnit,
			ActionMessage:    actionMessage,
			ActionLabelAdd:   data.ActionLabelAdd,
			ActionLabelDel:   data.ActionLabelDel,
			ActionForward:    actionForward,
		},
	}, nil
}
