// Package utils -----------------------------
// @file      : requestDataToProto.go
// @author    : JJXu
// @contact   : wavingbear@163.com
// @time      : 2023/8/28 17:57
// -------------------------------------------
package utils

import (
	"reflect"
	"strings"
)

// http请求转proto请求
func RequestDataConvert(from interface{}, to interface{}) {
	var proxyField = "Query"
	fromValue := reflect.ValueOf(from)
	toValue := reflect.ValueOf(to)
	toType := reflect.TypeOf(to)

	// 获取From结构体的字段信息
	fromType := fromValue.Type().Elem()
	for i := 0; i < fromType.NumField(); i++ {
		// 获取字段名和字段值
		fieldName := fromType.Field(i).Name
		fieldValue := fromValue.Elem().FieldByName(fieldName)
		if fieldName != proxyField {
			_, exists := toType.Elem().FieldByName(fieldName)
			if exists {
				// 设置To结构体中相应字段的值
				toValue.Elem().FieldByName(fieldName).Set(fieldValue)
			}
		}
	}
	queryField, exists := toType.Elem().FieldByName(proxyField)
	if exists {
		var queryFieldTypeName string
		// 指针类型额外处理，拿到真实的数据类型
		if queryField.Type.Kind() == reflect.Ptr {
			queryFieldTypeName = queryField.Type.Elem().String()
		} else {
			queryFieldTypeName = queryField.Type.Kind().String()
		}
		//处理拿到的结构体类型如 utils.xxxx的类型，去掉utils.这部分
		if strings.Contains(queryFieldTypeName, ".") {
			queryFieldTypeName = strings.Split(queryFieldTypeName, ".")[1]
		}
		fromQueryValue := fromValue.Elem().FieldByName(queryFieldTypeName)
		toValue.Elem().FieldByName(proxyField).Set(fromQueryValue.Addr())
	}
}
