package org.springblade.yeePay.utils;

import com.alibaba.fastjson.JSON;
import com.yeepay.yop.sdk.service.common.request.YopRequest;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author: lianghanqiang
 * @description: 易宝工具类
 * @since: 9/6/21 -- 2:22 PM
 */
public class  YeepayUtils {

	/**
	 * 	添加请求参数
	 * @param obj 请求所需DTO对象
	 * @param request 所需添加参数请求
	 * @param clazz */
	public static void addParamsFromObj(Object obj, YopRequest request, Class clazz){


		//获取包含父类在内的所有属性
		List<Field> fieldList = new ArrayList<>();
		while (clazz != null) {
			fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
			clazz = clazz.getSuperclass();
		}

			(fieldList).stream().forEach(field -> {
					field.setAccessible(true);
					try {
						Object paramValue = field.get(obj);
						if(!Objects.isNull(paramValue)){
							if(paramValue instanceof String || paramValue instanceof Enum){
								request.addParameter(field.getName(),paramValue);
							}else{
								String s = JSON.toJSONString(paramValue);
								request.addParameter(field.getName(),s);
							}
						}
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			);
	}
}
