package com.chinacreator.video.validate;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;

/**
 * 参数验证
 * @author xu.zhou
 * @date 20200331
 */
@Component
public class ParamValidate {
	//必须验证的参数
	HashMap<String, String> commparams =new HashMap<String, String>();
	{
		commparams.put("cpid", ""); 
		commparams.put("spid", "");
		commparams.put("channel", "");
		commparams.put("type", "0,1"); //此参数只能是0或1
		commparams.put("timestamp", "");
		commparams.put("userid", "");
		commparams.put("signature", "");
		commparams.put("orderid", "");
	}
	
	/**
	 * 验证参数是否合法
	 * @param orderInfo
	 * @param params 预设参数数据，key为参数名，value为参数值，参数值多个用逗号分隔，value为空时不验证实际值，params为空时使用默认验证
	 * 比如操作类型type的值是0和1，代表订购和退订， params为{cpid=youtu, type=1,0}
	 * @throws Exception
	 */
	public void validate(OrderInfo orderInfo, HashMap<String, String> params) throws Exception {
		if(orderInfo == null){
			return;
		}
		if(params == null || params.size() == 0){
			params = commparams;
		}
		//获取输入参数
		TreeMap<String, String> tm = truncBean(orderInfo);
		//System.out.println("tm=>"+tm);
		String key = "";
		String value = "";
		boolean item = false;
		Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = it.next();
			key = entry.getKey();
			value = entry.getValue();
			if(tm.get(key) == null){//输入参数不包含要验证的参数名称
				throw new BussinessException("80015", "参数异常，缺少"+key);
			}else if(!"".equals(value)){ //限制了输入值，判断输入值是否为指定内容
				String [] tmpArray = value.split(",");
				for(String s : tmpArray){
					if(s != null && s.trim().equals(tm.get(key))){
						item = true;
						break;
					}
				}
				if(!item){
					throw new BussinessException("80015", "参数异常，"+key+"=>"+tm.get(key));
				}
			}else if("".equals(tm.get(key))){//限制参数必须有值
				//参数标识不能为空，但传入的是空串
				throw new BussinessException("80015", "参数异常，"+key+"值为空");
			}
			item = false;
			//System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
		}
	}
	
	/**
	 * 先验证默认参数是否合法，再增加额外参数验证
	 * @param orderInfo
	 * @param params 预设参数数据，key为参数名，value为参数值，参数值多个用逗号分隔，value为N时不验证实际值，
	 * 比如操作类型type的值是0和1，代表订购和退订， 如果type只能传0，则params为{type=0}
	 * @throws Exception
	 */
	public void validateAdd(OrderInfo orderInfo, HashMap<String, String> params) throws Exception {
		if(orderInfo == null){
			return;
		}
		//验证默认参数
		validate(orderInfo, null);
		if(params != null && params.size() > 0){
			//再验证补充参数
			validate(orderInfo, params);		
		}
	}
	
	/**
	 * 获取所有参数信息
	 * @param bean
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public  TreeMap<String, String> truncBean(Object bean) throws IllegalArgumentException, IllegalAccessException{
		TreeMap<String, String> map = new TreeMap<>();
		for (Field field : bean.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            //System.out.println("field=>"+field.getName()+"_"+field.getType());
            //只要String类型的参数
            if(field.get(bean) != null && field.getType().equals(java.lang.String.class)){
            	map.put(field.getName(), (String)field.get(bean));
            }
           // if(!StringUtils.isEmpty((String)field.get(bean))){
            	//map.put(field.getName(), (String)field.get(bean));
           // }
            //map.put(field.getName(), StringUtils.isEmpty((String)field.get(bean)) ? "" : (String)field.get(bean));
        }
		//System.out.println(map);
		return map;
	}
	
	
	public  String getSign(TreeMap<String, String> map) {
		if (map == null) {
			return "";
		}
		StringBuilder strb = new StringBuilder();
		for (String pama : map.keySet()) {
			if(!pama.equals("signature")) {
				strb.append("&" + pama + "=" + map.get(pama));
			}
		}
		strb.deleteCharAt(0);
		return strb.toString();
	}
	
	public static void main(String[] args) {
		OrderInfo bean = new OrderInfo();
		bean.setCpid("youtu");
		bean.setSpid("1168");
		bean.setType("0");
		bean.setTimestamp("dfafdasdfa");
		bean.setUserid("18673197465");
		bean.setChannel("hbcs");
		bean.setOrderid("2356445");
		bean.setSignature("dfdfdf");
		ParamValidate vali = new ParamValidate();
		try {
			HashMap<String, String> params =new HashMap<String, String>();
			params.put("type", "0");
			//params.put("cpid", "youtu");
			//params.put("timestamp","");
			//System.out.println(params);
			//vali.validate(bean);
			//vali.validate(bean,params);
			vali.validateAdd(bean,params);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
