package com.chinacreator.video.restful.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.mapper.ChannelOrgDao;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.validate.ChannelValidate;
import com.chinacreator.video.validate.IpValidate;
import com.chinacreator.video.validate.TimetampValidate;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 柏源二级渠道匹配服务类
 * @author xu.zhou
 * @date 20210809
 */
@Component
public class ChannelOrgService {
	
	private static Logger logger = Logger.getLogger(ChannelOrgService.class);
	
	private static Logger log = Logger.getLogger("pointshop");
	
	@Autowired
	private TimetampValidate timetampValidate;
	
	@Autowired
	private ChannelValidate channelValidate;
	
	@Autowired
	private IpValidate ipValidate;
	
    @Autowired
    private ChannelDao channelDao;
    
    @Autowired
    private ChannelOrgDao channelOrgDao;
    
    /**
     * 业务处理
     * @param inputObj
     * @param invokeface
     * @throws Exception
     */
    public JSONArray operBusi(JSONObject inputObj, String invokeface) throws Exception {
    	//JSONObject outputObj = new JSONObject();
    	JSONArray resdata = JSON.parseArray(inputObj.getJSONArray("data").toJSONString());	
		//JSONArray data = inputObj.getJSONArray("data");	
		//resdata = data;
		if("scosetinfo".equals(invokeface)){
			JSONObject jsontmp = null;
			HashMap hmtmp;
			for(int i = 0; i < resdata.size(); i++){
				try {
					jsontmp = resdata.getJSONObject(i);
					hmtmp = jsontmp.parseObject(jsontmp.toJSONString(), HashMap.class);
					hmtmp.put("channel", inputObj.getString("channel"));
					int res = channelOrgDao.operchannelorginfo(hmtmp);
					if(res == 1){
						jsontmp.put("rescode", "0");
						jsontmp.put("resdesc", "ok");
					}else{
						jsontmp.put("rescode", "1");
						jsontmp.put("resdesc", "处理失败");
					}
				} catch (Exception e) {
					log.error("处理失败，"+e.getMessage(), e);
					jsontmp.put("rescode", "1");
					jsontmp.put("resdesc", "出现异常，"+e.getMessage());
				}			
			}
		}else{		
			JSONObject jsontmp = null;
			HashMap hmtmp;
			for(int i = 0; i < resdata.size(); i++){
				try {
					jsontmp = resdata.getJSONObject(i);
					hmtmp = channelOrgDao.getchannelorginfo(inputObj.getString("channel"), jsontmp.getString("subchannelcode"));
					if(hmtmp == null || hmtmp.size() == 0){
						jsontmp.put("rescode", "1");
						jsontmp.put("resdesc", "无此渠道配置信息");
					}else{
						jsontmp.put("subchannelname", hmtmp.get("SUBCHANNELNAME")+"");
						jsontmp.put("subchannelkey", hmtmp.get("SUBCHANNELKEY")+"");
						jsontmp.put("status", hmtmp.get("STATUS")+"");
						jsontmp.put("rescode", "0");
						jsontmp.put("resdesc", "ok");
					}
				} catch (Exception e) {
					log.error("处理失败，"+e.getMessage(), e);
					jsontmp.put("rescode", "1");
					jsontmp.put("resdesc", "出现异常，"+e.getMessage());
				}			
			}
		}
		
		return resdata;
    }
	
	/**
	 * 
	 * @param inputObj
	 * @param invokeface
	 * @throws Exception
	 */
	public void checkBusi(JSONObject inputObj, String invokeface) throws Exception {
		try {
			//查询类型，0办理业务，1查询业务
			String busitype = "";
			OrderInfo orderInfo = new OrderInfo();
			String timestamp = inputObj.getString("timestamp");
			String channel = inputObj.getString("channel");
			if(StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(channel)){
				throw new BussinessException("9064", "验证接口参数失败！");
			}
			JSONArray data = inputObj.getJSONArray("data");
			if(data == null || data.size() == 0){
				throw new BussinessException("9064", "验证接口参数失败：data");
			}
			if(data.size() > 50){
				throw new BussinessException("9064", "验证接口参数失败：data长度超过上限");
			}
			orderInfo.setInvokeface(invokeface);
			if("scosetinfo".equals(invokeface)){
				orderInfo.setCpid("scosetinfo");
				busitype = "0";
				
				JSONObject jsontmp;
				for(int i = 0; i < data.size(); i++){
					jsontmp = data.getJSONObject(i);
					if(jsontmp == null){
						throw new BussinessException("9064", "验证接口参数失败");
					}else if(StringUtils.isEmpty(jsontmp.getString("subchannelcode"))
							|| StringUtils.isEmpty(jsontmp.getString("subchannelname"))
							|| StringUtils.isEmpty(jsontmp.getString("subchannelkey"))
							|| StringUtils.isEmpty(jsontmp.getString("status"))
							|| (!"0".equals(jsontmp.getString("status")) && !"1".equals(jsontmp.getString("status")))){
						throw new BussinessException("9064", "验证接口参数失败。");
					}
				}
			}else{
				orderInfo.setCpid("scogetinfo");
				busitype = "1";
				
				JSONObject jsontmp;
				for(int i = 0; i < data.size(); i++){
					jsontmp = data.getJSONObject(i);
					if(jsontmp == null){
						throw new BussinessException("9064", "验证接口参数失败");
					}else if(StringUtils.isEmpty(jsontmp.getString("subchannelcode"))){
						throw new BussinessException("9064", "验证接口参数失败。");
					}
				}
			}
			
			//签名验证
	        String lcalsign = getSign(inputObj);
	        lcalsign += channelDao.queryChannel(channel).getPassword();
	        lcalsign = MD5.MD5Encode(lcalsign);
	        if(!lcalsign.equals(inputObj.getString("signature"))) {
	            throw new BussinessException("10006", "签名校验失败");
	        }
		
			//时间戳验证
			timetampValidate.validate(timestamp);
			//渠道验证
			channelValidate.validate(channel);
			
			orderInfo.setChannel(channel);					
			//IP验证
			ipValidate.volidate(orderInfo, busitype);
			
		} catch (Exception e) {
			logger.error("验证接口参数出错，"+e.getMessage(), e);
			//if(e instanceof BussinessException) {
				//throw e;
			//}else {
				//e.printStackTrace();
				//throw new BussinessException("9066", "业务验证出现异常，"+e.getMessage());
			//}
			throw e;
		}
	}
	
    /**
     * 拼接签名信息 account+channel+timestamp
     * @param orderInfo
     * @return
     */
    private String getSign(JSONObject inputObj){
    	StringBuilder strb = new StringBuilder();
        strb.append(inputObj.getString("channel"));
        strb.append(inputObj.getString("timestamp"));
        return strb.toString();
    }
		
	/**
	 * 判断是否为数字格式不限制位数
	 * @param o
	 *     待校验参数
	 * @return
	 *     如果全为数字，返回true；否则，返回false
	 */
	private boolean isNumber(Object o){
	    return  (Pattern.compile("[0-9]*")).matcher(String.valueOf(o)).matches();
	}
}
