package com.ag.secp.platform.common;

import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * Created by Administrator on 2017/4/12 0012.
 */
public class ParamUtil<T> extends SqlUtil<T> {

    public T packPOJO(Map<String, String> map, Class<T> clz){
        T t = getEntity(clz);
        if(t == null){
            return null;
        }
        Method[] ms=t.getClass().getMethods();
        for(Method m: ms) {
            String fieldName = getFieldName(m);
            if(fieldName == null){
                continue;
            }
            if(!StringUtils.isEmpty(map.get(fieldName))){
                setMethodValue(t, m, map.get(fieldName));
                continue;
            }
            String colName = toLower(fieldName).toUpperCase();
            if(!StringUtils.isEmpty(map.get(colName))){
                setMethodValue(t, m, map.get(colName));
            }
        }

        return t;

    }

    private void setMethodValue(T t, Method m, String paramVal) {
        String paramType = m.getParameterTypes()[0].toString();
        try {
            if(paramType.contains("String")){
                m.invoke(t, paramVal);
            }else if(paramType.contains("Integer")){
                m.invoke(t, Integer.valueOf(paramVal));
            }else if(paramType.contains("Double")){
                m.invoke(t, Double.valueOf(paramVal));
            }else if(paramType.contains("Date")){
                m.invoke(t, new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(paramVal));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void printMap(Map<String,String> map){
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }
    }
}
