package com.chinacreator.video.validate;

import java.lang.reflect.Field;
import java.util.TreeMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.util.MD5;

@Component
public class SignValidate {

	@Autowired
	private ChannelDao channelDao;
	
	/**
	 * 标准签名验证
	 * @param orderInfo
	 * @throws Exception
	 */
	public void validate(OrderInfo orderInfo) throws Exception {
		String lcalsign = getSign(orderInfo);
		lcalsign += channelDao.queryChannel(orderInfo.getChannel()).getPassword();
		lcalsign = MD5.MD5Encode(lcalsign);
		if(!lcalsign.equals(orderInfo.getSignature())) {
			throw new BussinessException("10006", "签名校验失败");
		}
	}
	
	/**
	 * 签名验证，
	 * 用不带PWD的签名参数串加上PWD，再MD5，与参数里的签名串对比，用于非标准签名参数验证
	 * @param orderInfo 参数数据
	 * @param signstr 不带PWD的签名参数串
	 * @throws Exception
	 */
	public void validate(OrderInfo orderInfo, String signstr) throws Exception {
		signstr += channelDao.queryChannel(orderInfo.getChannel()).getPassword();
		signstr = MD5.MD5Encode(signstr);
		if(!signstr.equals(orderInfo.getSignature())) {
			throw new BussinessException("10006", "签名校验失败");
		}
	}
	
	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);
            map.put(field.getName(), StringUtils.isEmpty((String)field.get(bean)) ? "" : (String)field.get(bean));
            }
		return map;
	}
	
	/**
	 * 拼接签名信息 cpid+spid+userid+type+channel+timestamp
	 * @param orderInfo
	 * @return
	 */
	private String getSign(OrderInfo orderInfo) {
		if (orderInfo == null) {
			return "";
		}
		StringBuilder strb = new StringBuilder();
		if(orderInfo.getOrderid() != null && !"".equals(orderInfo.getOrderid())){
			strb.append(orderInfo.getOrderid());
		}
		strb.append(orderInfo.getCpid());
		strb.append(orderInfo.getSpid());
		strb.append(orderInfo.getUserid());
		strb.append(orderInfo.getType());
		strb.append(orderInfo.getChannel());
		strb.append(orderInfo.getTimestamp());
		return strb.toString();
	}
	
	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();
	}
}
