package sop_node

import (
	"context"
	"fmt"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/logx"
	"wechat-api/ent"
	"wechat-api/ent/predicate"
	"wechat-api/ent/sopnode"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"
)

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

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

func (l *GetSopNodeListLogic) GetSopNodeList(req *types.SopNodeListReq) (*types.SopNodeListResp, error) {
	var predicates []predicate.SopNode
	if req.StageId != nil {
		predicates = append(predicates, sopnode.StageID(*req.StageId))
	} else {
		return nil, dberrorhandler.DefaultEntError(l.Logger, fmt.Errorf("StageId 不能为空"), req)
	}
	data, err := l.svcCtx.DB.SopNode.Query().Where(predicates...).All(l.ctx)

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

	resp := &types.SopNodeListResp{}
	resp.Msg = errormsg.Success

	childNodeList, _ := GetSopNodeListByParentId(0, data)

	resp.Data = childNodeList

	return resp, nil
}

// 从node列表中找到指定 ParentId 的所有节点
func GetSopNodeListByParentId(parentId uint64, nodeList []*ent.SopNode) ([]*types.SopChildNodeInfo, error) {
	// 遍历 nodeList 找到 ParentId 为指定 parentId 的所有节点
	var result []*types.SopChildNodeInfo
	for _, node := range nodeList {
		if node.ParentID == parentId {
			childNodeList, _ := GetSopNodeListByParentId(node.ID, nodeList)
			var actionMessage []types.Action
			if len(node.ActionMessage) > 0 {
				actionMessage = make([]types.Action, len(node.ActionMessage))
				for i, condition := range node.ActionMessage {
					actionMessage[i] = types.Action{
						Type:    condition.Type,
						Content: condition.Content,
					}
				}
			}

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

			var childNode *types.SopChildNodeInfo
			if len(childNodeList) > 0 {
				childNode = &types.SopChildNodeInfo{
					ConditionNodes: childNodeList,
				}
			}

			child := types.SopChildNodeInfo{
				NodeName:  &node.Name,
				ChildNode: childNode,
				SopNodeInfo: types.SopNodeInfo{
					BaseIDInfo: types.BaseIDInfo{
						Id: &node.ID,
					},
					Status:           &node.Status,
					StageId:          &node.StageID,
					ParentId:         &node.ParentID,
					Name:             &node.Name,
					ConditionType:    &node.ConditionType,
					ConditionList:    node.ConditionList,
					NoReplyCondition: &node.NoReplyCondition,
					NoReplyUnit:      &node.NoReplyUnit,
					ActionMessage:    actionMessage,
					ActionLabelAdd:   node.ActionLabelAdd,
					ActionLabelDel:   node.ActionLabelDel,
					ActionForward:    actionForward,
				},
			}
			result = append(result, &child)
		}
	}
	return result, nil
}

//func (l *GetSopNodeListLogic) GetSopNodeList(req *types.SopNodeListReq) (*types.SopNodeListResp, error) {
//	var predicates []predicate.SopNode
//	if req.StageId != nil {
//		predicates = append(predicates, sopnode.StageID(*req.StageId))
//	} else {
//		return nil, dberrorhandler.DefaultEntError(l.Logger, fmt.Errorf("StageId 不能为空"), req)
//	}
//	data, err := l.svcCtx.DB.SopNode.Query().Where(predicates...).All(l.ctx)
//
//	if err != nil {
//		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
//	}
//
//	resp := &types.SopNodeListResp{}
//	resp.Msg = errormsg.Success
//
//	for _, v := range data {
//		var actionMessage []types.Action
//		if len(v.ActionMessage) > 0 {
//			actionMessage = make([]types.Action, len(v.ActionMessage))
//			for i, condition := range v.ActionMessage {
//				actionMessage[i] = types.Action{
//					Type:    condition.Type,
//					Content: condition.Content,
//				}
//			}
//		}
//
//		resp.Data.Data = append(resp.Data.Data,
//			types.SopNodeInfo{
//				BaseIDInfo: types.BaseIDInfo{
//					Id:        &v.ID,
//					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
//					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
//				},
//				Status:        &v.Status,
//				StageId:       &v.StageID,
//				ParentId:      &v.ParentID,
//				Name:          &v.Name,
//				ConditionType: &v.ConditionType,
//				ConditionList: v.ConditionList,
//				ActionMessage: actionMessage,
//				ActionLabel:   v.ActionLabel,
//			})
//	}
//
//	return resp, nil
//}
