package com.chinacreator.video.restful.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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.CommConfDao;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.mapper.FlowLimitDao;
import com.chinacreator.video.service.CommonService;
import com.chinacreator.video.util.AESUtil;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.OtherProperties;
import com.chinacreator.video.util.URLUtil;
import com.chinacreator.video.validate.BusiValidate;

/**
 * 流量查询
 * @author xu.zhou
 * @date 20200618
 */
@Component
public class FlowlimitService {
	
	@Autowired
	private BusiValidate busiVali;
	
    @Autowired
    private ChannelDao channelDao;
    
	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Autowired
	private FlowLimitDao flowLimitDao;
	
	@Autowired
	private CommConfDao commConfDao;
	
    @Autowired
    private OtherProperties otherProperties;
    
    @Autowired
    private CommonService commonService;
	
	private static Logger log = Logger.getLogger("flowlimit");
	
	public void busiCheck(JSONObject inputObj, String invokename) throws Exception{
		if("qryfbyproductid".equals(invokename)){
			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setChannel(inputObj.getString("channel"));
			//IP验证
			busiVali.valiIp(orderInfo);
			//参数验证
			paramValidate(inputObj,invokename);
			orderInfo.setTimestamp(inputObj.getString("timestamp"));
			//时间戳验证
			busiVali.valiTime(orderInfo);
			//签名验证
			signValidate(inputObj,invokename);			
			//手机号码验证
			mobValidate(inputObj);
		}else if("qryflowspid".equals(invokename)){
			//参数验证
			paramValidate(inputObj,invokename);
			
			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setChannel(inputObj.getString("channel"));
			orderInfo.setCpid("0");
			orderInfo.setSpid(inputObj.getString("spid"));
			orderInfo.setInvokeface(invokename);
			//SPID验证
			busiVali.valiCpSp(orderInfo);
			//用于区分IP免流和非IP免流
			inputObj.put("cpid", orderInfo.getCpid());
			if("kc".equals(orderInfo.getChannel())){
				String spid = orderInfo.getSpid();
				String cpid = orderInfo.getCpid();
				orderInfo.setCpid("qryflowspid");
				orderInfo.setSpid("qryflowspid");
				//IP验证
				busiVali.valiIp(orderInfo);
				orderInfo.setSpid(spid);
				orderInfo.setCpid(cpid);
			}else {
				//IP验证
				busiVali.valiIp(orderInfo);
			}
			orderInfo.setTimestamp(inputObj.getString("timestamp"));
			//时间戳验证
			busiVali.valiTime(orderInfo);
			//签名验证
			signValidate(inputObj,invokename);			
			//手机号码验证
			mobValidate(inputObj);
		}else if("qryflowfeeset".equals(invokename)){
			//参数验证
			paramValidate(inputObj,invokename);
			
			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setChannel(inputObj.getString("channel"));
			orderInfo.setCpid(invokename);
			orderInfo.setSpid(invokename);
			orderInfo.setInvokeface(invokename);
			orderInfo.setTimestamp(inputObj.getString("timestamp"));
			//时间戳验证
			busiVali.valiTime(orderInfo);
			//IP验证
			busiVali.valiIp(orderInfo);
			//签名验证
			signValidate(inputObj,invokename);
			//手机号码验证
			mobValidate(inputObj);
			//访问次数验证
			commonService.valiVisitLimit(orderInfo);
			//设置访问次数
			commonService.setVisitcount(orderInfo);
		}else if("qryflowunify".equals(invokename)){//流量查询整合接口
			//参数验证
			paramValidate(inputObj,invokename);
			
			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setChannel(inputObj.getString("channel"));
			orderInfo.setCpid(invokename);
			orderInfo.setSpid(invokename);
			orderInfo.setInvokeface(invokename);
			orderInfo.setTimestamp(inputObj.getString("timestamp"));
			//时间戳验证
			busiVali.valiTime(orderInfo);
			//IP验证
			busiVali.valiIp(orderInfo);
			//签名验证
			signValidate(inputObj,invokename);
			//手机号码验证
			mobValidate(inputObj);
			//访问次数验证
			commonService.valiVisitLimit(orderInfo);
			//设置访问次数
			commonService.setVisitcount(orderInfo);
		}
	}
	
	/**
	 * 参数验证
	 * @param inputObj
	 * @param invokename
	 * @throws Exception
	 */
	private void paramValidate(JSONObject inputObj, String invokename) throws Exception{
       if("qryfbyproductid".equals(invokename)){
    	   if(!StringUtils.isNotEmpty(inputObj.getString("userid")) 
    			|| !StringUtils.isNotEmpty(inputObj.getString("channel"))
    			|| !StringUtils.isNotEmpty(inputObj.getString("signature"))
    			|| !StringUtils.isNotEmpty(inputObj.getString("timestamp"))
    					){
    		   throw new BussinessException("80015", "参数异常，");
    	   }
    	   
           if(inputObj.getJSONArray("productids") == null || inputObj.getJSONArray("productids").size() == 0){
        	   throw new BussinessException("80015", "参数异常，productids=>"+inputObj.getJSONArray("productids"));
           }
           JSONArray prodarray = inputObj.getJSONArray("productids");
   		   List productids = new ArrayList();
   		   for(int i = 0; i < prodarray.size(); i++){
   			   productids.add(prodarray.get(i).toString());
   		   }
  
           List<HashMap> confHMList = flowLimitDao.getSpAopConf(productids);
           if(confHMList == null || confHMList.size() == 0){
        	   throw new BussinessException("9012", "未找到产品配置信息，"+productids);
           }
           HashMap<String, String> confMap = new HashMap<String, String>();
           //获取产品ID与SPID的关系，KEY为SPID,值为产品ID
           for(HashMap hm : confHMList){
        	   if(!confMap.containsKey(hm.get("SP_ID"))){
        		   confMap.put((String)hm.get("SP_ID"),(String)hm.get("PRODUCT_ID"));
        	   }
           }
           inputObj.put("confMap", confMap);
           	//confMap=>{142=90723765, 141=90723762}
           log.info("confMap=>"+confMap);
       }else if("qryflowspid".equals(invokename)){
    	   if(!StringUtils.isNotEmpty(inputObj.getString("userid")) 
    			|| !StringUtils.isNotEmpty(inputObj.getString("channel"))
    			|| !StringUtils.isNotEmpty(inputObj.getString("signature"))
    			|| !StringUtils.isNotEmpty(inputObj.getString("timestamp"))
    			|| !StringUtils.isNotEmpty(inputObj.getString("spid"))
    					){
    		   throw new BussinessException("80015", "参数异常，");
    	   }
       }else if("qryflowfeeset".equals(invokename)){
    	   if(!StringUtils.isNotEmpty(inputObj.getString("userid")) 
    			|| !StringUtils.isNotEmpty(inputObj.getString("channel"))
    			|| !StringUtils.isNotEmpty(inputObj.getString("signature"))
    			|| !StringUtils.isNotEmpty(inputObj.getString("timestamp"))
    					){
    		   throw new BussinessException("80015", "参数异常，");
    	   }
       }else if("qryflowunify".equals(invokename)){
    	   if(!StringUtils.isNotEmpty(inputObj.getString("userid")) 
    			|| !StringUtils.isNotEmpty(inputObj.getString("channel"))
    			|| !StringUtils.isNotEmpty(inputObj.getString("signature"))
    			|| !StringUtils.isNotEmpty(inputObj.getString("timestamp"))
    					){
    		   throw new BussinessException("80015", "参数异常，");
    	   }
       }
	}
	
    /**
     * 签名验证
     * @param orderInfo
     * @throws Exception
     */
    public void signValidate(JSONObject inputObj, String invokename) throws Exception{
        String lcalsign = getSign(inputObj,invokename);
        lcalsign += channelDao.queryChannel(inputObj.getString("channel")).getPassword();
        lcalsign = MD5.MD5Encode(lcalsign);
        if(!lcalsign.equals(inputObj.getString("signature"))) {
            throw new BussinessException("10006", "签名校验失败");
        }
    }
    
    /**
     * 拼接签名信息 orderid+channel+timestamp
     * @param orderInfo
     * @return
     */
    public String getSign(JSONObject inputObj, String invokename){
    	StringBuilder strb = new StringBuilder();
        if("qryfbyproductid".equals(invokename)){
        	 strb.append(inputObj.getString("userid"));
        	 strb.append(inputObj.getString("productids"));
        	 strb.append(inputObj.getString("channel"));
             strb.append(inputObj.getString("timestamp"));
        }else if("qryflowspid".equals(invokename)){
        	//Md5(channel+userid+spid+timestamp+pwd)
	       	 strb.append(inputObj.getString("channel"));
	       	 strb.append(inputObj.getString("userid"));
	       	 strb.append(inputObj.getString("spid"));
             strb.append(inputObj.getString("timestamp"));
        }else if("qryflowfeeset".equals(invokename)){
        	//Md5(channel+userid+timestamp+pwd)
	       	 strb.append(inputObj.getString("channel"));
	       	 strb.append(inputObj.getString("userid"));
             strb.append(inputObj.getString("timestamp"));
        }else if("qryflowunify".equals(invokename)){
        	//Md5(channel+userid+timestamp+pwd)
	       	 strb.append(inputObj.getString("channel"));
	       	 strb.append(inputObj.getString("userid"));
             strb.append(inputObj.getString("timestamp"));
        }

        return strb.toString();
    }
    
    /**
     * 业务处理
     * @param inputObj
     * @return
     * @throws Exception
     */
    public List qryfbyproductid(JSONObject inputObj) throws Exception{
    	List resData = null;
		try {
			//超时时间
			int timeout = 30 * 1000;
			//http://111.206.134.43:809/orderFlow/flowBill
			String invokeUrl = dictionaryDao.getValue("flowBillUrl");
			invokeUrl = invokeUrl + "?" + this.getParams(inputObj.getString("usermob"));
			log.info("调用接口地址及参数："+invokeUrl);
			String result = URLUtil.get(invokeUrl, timeout);
			//result = "{\"resultCode\":\"0\",\"resultInfo\":\"ok\",\"userid\":\"4C4BF3A8AC1FE30121C453E4634FD973\",\"data\":[{\"cpid\":\"aiqy\",\"spid\":\"141\",\"spname\":\"WO+视频爱奇艺定向流量包月\",\"maxflow\":\"15360\",\"flow\":\"0\",\"useflow\":\"15360\",\"stime\":\"20200601000001\",\"etime\":\"20200630235959\",\"isold\":\"1\",\"islimit\":\"1\"},{\"cpid\":\"aiqy\",\"spid\":\"142\",\"spname\":\"爱奇艺定向流量会员包（前向）\",\"maxflow\":\"10240\",\"flow\":\"0\",\"useflow\":\"10240\",\"stime\":\"20200601000001\",\"etime\":\"20200630235959\",\"isold\":\"1\",\"islimit\":\"1\"}]}";
			log.info("调接口返回信息："+result);
			resData = parseResObj(inputObj, result);
		} catch (Exception e) {
			log.error("获取流量账单出现异常，"+e.getMessage());
			if(e instanceof BussinessException) {
				throw e;
			}else{
				e.printStackTrace();
				throw new BussinessException("9011","获取流量账单出现异常，"+e.getMessage());
			}
		}
    	return resData;
    }
    
    /**
     * 查询流量
     * @param inputObj
     * @throws Exception 
     */
    public String qryflowspid(JSONObject inputObj) throws Exception{
    	String result = "";
		boolean hasipfree = false;//是否IP免流的CPID
		String invokeUrl = ""; //接口地址
		String params = ""; //调接口参数
		JSONObject data = new JSONObject();
		String cpid = inputObj.getString("cpid");
		String spid = inputObj.getString("spid");
		String userid = inputObj.getString("usermob"); //（手机号码）
    	try {    		
    		//IP免流的cpid
    		//String ipfreecpid = otherProperties.getEnv().getProperty("qryflowspid.ipfreecpid");
    		//IP免流CPID，
    		String ipfreecpid = dictionaryDao.getValue("ipfreecpid");
    		if(!StringUtils.isEmpty(ipfreecpid) && Arrays.asList(ipfreecpid.split("\\|")).contains(cpid)){
    			List<HashMap> dataList = flowLimitDao.qrySpAopConfBySpid(spid);
    			if(dataList == null || dataList.size() == 0){
    				throw new BussinessException("80015", "参数异常，spid:"+spid+"非IP免流产品");
    			}
    			//产吕ID
    			String productid = dataList.get(0).get("PRODUCT_ID")+"";
    			//是IP免流
    			hasipfree = true;
    			//http://172.16.1.81:809/shareorder/selectallow
    			invokeUrl =  dictionaryDao.getValue("shareselectallowUrl");
    			String cycleId = new SimpleDateFormat("yyyyMM").format(new Date()); //（账期）,
    			params = "cycleId="+cycleId+"&userId="+userid;
    			invokeUrl += "?"+params;
    			result = URLUtil.get(invokeUrl, 30000);
    			/*
			"FEE_POLICY_NAME": "快手12G流量月包（附属）",————套餐名称
            "ADDUP_UPPER": "12582912",————累计值上限
            "X_USED_VALUE": "50168",————已经使用的免费资源量
            "X_CANUSE_VALUE": "12532744",————剩余免费资源量
            "X_EXCEED_VALUE": "0",————超出部分使用量
            "CYCLE_ID": "202203",————查询账期
            "PRODUCT_ID": "91043174",
    			 */
    			if(!StringUtils.isEmpty(result)){
        			JSONObject resObj = new JSONObject().parseObject(result);
        			if("0".equals(resObj.get("resultCode")+"") && resObj.getJSONArray("data") != null && resObj.getJSONArray("data").size()>0){
        				JSONArray resdata = resObj.getJSONArray("data");
        				JSONObject tmpobj = null;
        	
        				for(int i = 0; i< resdata.size(); i++){
        					tmpobj = (JSONObject)resdata.get(i);
        					if(productid.equals(tmpobj.getString("PRODUCT_ID"))){
                				//最大流量
                				String maxflow = tmpobj.getString("ADDUP_UPPER");
                				//剩余流量
                				String surflow = tmpobj.getString("X_CANUSE_VALUE");
                				//已使用流量
                				String useflow = tmpobj.getString("X_USED_VALUE");               				
            					data.put("maxflow", maxflow);
                				data.put("surflow", surflow);
                				data.put("useflow", useflow); 
        						break;
        					}
        				}        			
        			}
    			}
    		}else{
    			//http://172.16.1.81:809/orderFlow/flowQuerySpid
    			invokeUrl = dictionaryDao.getValue("flowQuerySpidUrl");   			
    			String key = "create20200618kd";
    			userid = AESUtil.encrypt(userid,key); 
    			String channel = "create";
    			String timestamp = (System.currentTimeMillis())/1000+"";
    			String signature = userid+spid+channel+timestamp+key;
    			signature = MD5.MD5Encode(signature); //转换为十六进制ASCII 码字符串，共32 个字符，全小写 userid= Des(手机号码，pwd)
    			params = "userid="+URLEncoder.encode(userid,"utf-8")+"&spid="+spid+"&channel="+channel+"&timestamp="+timestamp+"&signature="+signature;
    			   			
    			invokeUrl += "?"+params;
    			result = URLUtil.get(invokeUrl, 30000);
    			if(!StringUtils.isEmpty(result)){
    				JSONObject resObj = new JSONObject().parseObject(result);
        			if("0".equals(resObj.getString("resultCode"))){
        				//最大流量
        				String maxflow = resObj.getString("maxflow");
        				if(!StringUtils.isEmpty(maxflow)){//单位由M转为KB
        					//maxflow = (Integer.parseInt(maxflow)*1024)+"";
        					maxflow = formatDouble(Double.parseDouble(maxflow)*1024);
        				}
        				//剩余流量
        				String surflow = resObj.getString("flow");
           				if(!StringUtils.isEmpty(surflow)){////单位由M转为KB
           					//surflow = (Integer.parseInt(surflow)*1024)+"";
           					surflow = formatDouble(Double.parseDouble(surflow)*1024);
           				}
        				//已使用流量
        				String useflow = "";
        				if(!StringUtils.isEmpty(maxflow) && !StringUtils.isEmpty(surflow)){
        					//useflow = (Integer.parseInt(maxflow) - Integer.parseInt(surflow)) + "";
        					useflow = formatDouble(Double.parseDouble(maxflow)-Double.parseDouble(surflow));
        					data.put("maxflow", maxflow);
            				data.put("surflow", surflow);
            				data.put("useflow", useflow);
        				}
        			}
    			}
    		}
    		//有查到数据
    		if(data.size() > 0){
    			HashMap spmap = commConfDao.findSpInfo(spid).get(0);
    			data.put("spname", spmap.get("SPNAME"));
    			data.put("ipfree", hasipfree ? "0" : "1");
    			data.put("spid", spid);
    			inputObj.put("data", data);
    		}
		} catch (Exception e) {
			e.printStackTrace();
			result = "查询流量出现异常，"+e.getMessage();
			log.error(result,e);
			if( e != null && e.getMessage().indexOf("http") != -1){
				throw new Exception("调下游查询接口出现错误");
			}else{
				throw e;
			}
			
		} finally {
			log.info(inputObj.getString("usermob")+"，"+cpid+"，"+spid+"，接口地址=>"+invokeUrl+"，执行结果=>"+result);
		}
    	
    	return result;
    }
    
    /**
     * 解析接口返回报文
     * @param inputObj
     * @param result
     * @return
     * @throws Exception
     */
    private List parseResObj(JSONObject inputObj, String result) throws Exception{
    	List resData = new ArrayList();
    	JSONObject resObj = new JSONObject().parseObject(result);
    	String resultCode = resObj.getString("resultCode");
    	String resultInfo = resObj.getString("resultInfo");
    	if("0".equals(resultCode)){
    		JSONArray data = resObj.getJSONArray("data");
    		if(data != null && data.size()>0){
    			JSONObject tmpObj = null;
    			//获取产品匹配的spid
    			HashMap<String, String> confMap = (HashMap<String, String>)inputObj.get("confMap");
    			for(int i = 0; i < data.size(); i++){
    				tmpObj = data.getJSONObject(i);
    				if(confMap.containsKey(tmpObj.getString("spid"))){
    					tmpObj.put("productid", confMap.get((String)tmpObj.getString("spid")));
    					resData.add(tmpObj);
    				}
    			}
    		}
    	}else{
    		if("8013".equals(resultCode)){
        		throw new BussinessException("9013","无订购关系");
    		}else{
    			throw new BussinessException("9014","获取流量账单失败");
    		}

    	}
    	
    	if(resData == null || resData.size() == 0 ){
    		throw new BussinessException("9015","未查到对应产品的流量数据");
    	}
    	
    	return resData;
    }
    
    /**
     * 组建调流量接口的参数
     * @param usermob
     * @return
     * @throws Exception
     */
    private String getParams(String usermob) throws Exception{
    	String params = "";
		String key = dictionaryDao.getValue("flowBillKey");
		String userid = AESUtil.encrypt(usermob,key);
		String cpid = "*";
		String channel = "univideo";
		String timestamp = (System.currentTimeMillis())/1000+"";
		String pwd = dictionaryDao.getValue("flowBillPwd");
		String signature = userid+cpid+channel+timestamp+pwd;
		//System.out.println("签名前："+signature);
		signature = MD5.MD5Encode(signature); //转换为十六进制ASCII 码字符串，共32 个字符，全小写 userid= Des(手机号码，pwd)
		 
		params = "userid="+userid+"&cpid="+cpid+"&channel="+channel+"&timestamp="+timestamp+"&signature="+signature;
    	return params; 
    }
	
    /**
     * 手机号码验证
     * @param usermob
     * @throws Exception
     */
	private void mobValidate(JSONObject inputObj)throws Exception{
		boolean res = false;
		String usermob = inputObj.getString("userid");
		String pwd = channelDao.queryChannel(inputObj.getString("channel")).getPassword();
		//解密手机号码
		usermob = DesUtil.decode(usermob, pwd);
        if (usermob != null && usermob.length() == 11) {
        	usermob = usermob.replaceAll("[\\s-]", "");
        	if(usermob.matches(".*(1\\d{10}).*")){
        		inputObj.put("usermob", usermob);
        		res = true;
        	}
        }
        if(res == false){
        	throw new BussinessException("9022","手机号码不合法");
        }     	       	    
	}
	
	/**
	 * double类型如果小数点后为零则显示整数否则保留三位小数，比如23.0，转换后为23
	 * @param d
	 * @return
	 */
	public static String formatDouble(double d) {
		String res = "";
		String tmp = "";
	    BigDecimal bg = new BigDecimal(d).setScale(4, RoundingMode.UP);
	    double num = bg.doubleValue();
//	    if (Math.round(num) - num == 0) {
//	    	tmp = String.valueOf((long) num);
//	    }else{
//	    	tmp = String.valueOf(num);
//	    }
	    //防止double值大于8位数出现科学计数法格式
		java.text.NumberFormat nf = java.text.NumberFormat.getInstance();   
		nf.setGroupingUsed(false);  
		tmp = nf.format(num);
		
		//以小数点分隔为两部分
	     String [] arry = tmp.split("\\.");
	     //如果有小数点
	     if(arry.length == 2){
	    	 //小数点前面的是0，则小数点后面的置为空，不要了
		     if("0".equals(arry[1])){
		    	 arry[1] = "";
		     }else if(arry[1].length() > 3){//小数点后面超过3位数，只要前三位
		    	 arry[1] = arry[1].substring(0,3);
		     }
		     //去除小数点后的无效0（最后一位为0，去除），执行三次，因为前面保留了最多小数点后的三位小数
		     if(arry[1].lastIndexOf("0") == arry[1].length()-1){
		    	 arry[1] = arry[1].substring(0, arry[1].length()-1);
		     }
		     if(arry[1].lastIndexOf("0") == arry[1].length()-1){
		    	 arry[1] = arry[1].substring(0, arry[1].length()-1);
		     }
		     if(arry[1].lastIndexOf("0") == arry[1].length()-1){
		    	 arry[1] = arry[1].substring(0, arry[1].length()-1);
		     }
		     //如果第二部分为空，则只返回第一部分的数据
		     if("".equals(arry[1])){
		    	 res = arry[0];
		     }else{
		    	 res = arry[0]+"."+arry[1];
		     }
	     }else{
	    	 res = tmp;
	     }
	     
		 log.info("输入参数："+d+"，解析前："+tmp+"，解析后："+res);
	     return res;   
	}
	
    /**
     * 调能力平台查询流量返回筛选后的信息
     * @param inputObj
     * @throws Exception 
     */
    public String qryflowfeeset(JSONObject inputObj) throws Exception{
    	List<JSONObject> data = new ArrayList<JSONObject>();
    	String result = "";
		String invokeUrl = ""; //接口地址
		String params = ""; //调接口参数
		String userid = inputObj.getString("usermob"); //（手机号码）
    	try {    		
			//http://172.16.1.81:809/shareorder/selectallow
			invokeUrl =  dictionaryDao.getValue("shareselectallowUrl");
			String cycleId = new SimpleDateFormat("yyyyMM").format(new Date()); //（账期）,
			params = "cycleId="+cycleId+"&userId="+userid;
			invokeUrl += "?"+params;
			result = URLUtil.get(invokeUrl, 30000);
    			/*
    			 * REAL_RESOURCE_TYPE
			"FEE_POLICY_NAME": "快手12G流量月包（附属）",————套餐名称
            "ADDUP_UPPER": "12582912",————累计值上限
            "X_USED_VALUE": "50168",————已经使用的免费资源量
            "X_CANUSE_VALUE": "12532744",————剩余免费资源量
            "X_EXCEED_VALUE": "0",————超出部分使用量
            "CYCLE_ID": "202203",————查询账期
            "PRODUCT_ID": "91043174",
			 */
			/**
			 * 1、"REAL_RESOURCE_TYPE"：01  提取条件
				2、提取FEE_POLICY_ADDUP_INFO里面"REAL_RESOURCE_TYPE"：01 的数据。
				3、"ADDUP_UPPER"  这个不为0的数据。
			 */
			if(!StringUtils.isEmpty(result)){
    			JSONObject resObj = new JSONObject().parseObject(result);
    			if("0".equals(resObj.get("resultCode")+"") && resObj.getJSONArray("data") != null && resObj.getJSONArray("data").size()>0){
    				JSONArray resdata = resObj.getJSONArray("data");
    				JSONObject tmpobj = null;
					JSONObject tmpobj2 = null;
    				JSONObject addOjb = null;
					List<JSONObject> data2 = new ArrayList<JSONObject>();

    				for(int i = 0; i< resdata.size(); i++){
    					tmpobj = (JSONObject)resdata.get(i);
    					if(
//    							"01".equals(tmpobj.getString("REAL_RESOURCE_TYPE")) && !"0".equals(tmpobj.getString("ADDUP_UPPER"))
    							(flag(tmpobj)) //限量套餐数据
						){
    						addOjb = new JSONObject();
    						addOjb.put("FEE_POLICY_NAME", tmpobj.getString("FEE_POLICY_NAME"));
    						addOjb.put("ADDUP_UPPER", tmpobj.getString("ADDUP_UPPER"));
    						addOjb.put("X_USED_VALUE", tmpobj.getString("X_USED_VALUE"));
    						addOjb.put("X_CANUSE_VALUE", tmpobj.getString("X_CANUSE_VALUE"));
    						addOjb.put("X_EXCEED_VALUE", tmpobj.getString("X_EXCEED_VALUE"));
    						addOjb.put("CYCLE_ID", tmpobj.getString("CYCLE_ID"));
    						addOjb.put("PRODUCT_ID", tmpobj.getString("PRODUCT_ID"));
    						data.add(addOjb);
    					}
    					if("I0".equals(tmpobj.getString("REAL_RESOURCE_TYPE")) && "0".equals(tmpobj.getString("ADDUP_UPPER"))) { //不限量套餐数据
							addOjb = new JSONObject();
							addOjb.put("FEE_POLICY_NAME", tmpobj.getString("FEE_POLICY_NAME"));
							addOjb.put("ADDUP_UPPER", tmpobj.getString("ADDUP_UPPER"));
							addOjb.put("X_USED_VALUE", tmpobj.getString("X_USED_VALUE"));
							addOjb.put("X_CANUSE_VALUE", tmpobj.getString("X_CANUSE_VALUE"));
							addOjb.put("X_EXCEED_VALUE", tmpobj.getString("X_EXCEED_VALUE"));
							addOjb.put("CYCLE_ID", tmpobj.getString("CYCLE_ID"));
							addOjb.put("PRODUCT_ID", tmpobj.getString("PRODUCT_ID"));
							addOjb.put("TYPE_MARK", tmpobj.getString("TYPE_MARK"));
							data2.add(addOjb);

						}
    				}
					if (data2.size()>1){
						for (int i=0;i<data2.size();i++){
							tmpobj2 = data2.get(i);
							if ("0".equals(tmpobj2.getString("TYPE_MARK"))){
								addOjb = new JSONObject();
								addOjb.put("FEE_POLICY_NAME", tmpobj2.getString("FEE_POLICY_NAME"));
								addOjb.put("ADDUP_UPPER", tmpobj2.getString("ADDUP_UPPER"));
								addOjb.put("X_USED_VALUE", tmpobj2.getString("X_USED_VALUE"));
								addOjb.put("X_CANUSE_VALUE", tmpobj2.getString("X_CANUSE_VALUE"));
								addOjb.put("X_EXCEED_VALUE", tmpobj2.getString("X_EXCEED_VALUE"));
								addOjb.put("CYCLE_ID", tmpobj2.getString("CYCLE_ID"));
								addOjb.put("PRODUCT_ID", tmpobj2.getString("PRODUCT_ID"));
								data.add(addOjb);
							}
						}
					}else if (data2.size()==1){
						data.add(data2.get(0));
					}
    			}
			}   		
		} catch (Exception e) {
			e.printStackTrace();
			result = "查询流量出现异常，"+e.getMessage();
			log.error(result,e);
			if( e != null && e.getMessage().indexOf("http") != -1){
				throw new Exception("调下游查询接口出现错误");
			}else{
				throw e;
			}
			
		} finally {
			//匹配SPID和SPNAME
			mateSpid(data);
			inputObj.put("data", data);
			log.info(userid+"，接口地址=>"+invokeUrl+"，执行结果=>"+result);
		}
    	
    	return result;
    }

	/**
	 * 限量套餐数据判断
	 * @param tmpobj
	 * @return
	 */
	private boolean flag(JSONObject tmpobj) {
    	boolean flag = false;
    	if ("0".equals(tmpobj.getString("ADDUP_UPPER"))){
    		return false;
		}
    	String typeliststr = dictionaryDao.getValue("realResourecType");
		if (!StringUtils.isEmpty(typeliststr)){
			String[] split = typeliststr.split(",");
			for (String type:split){
				if (type.equals(tmpobj.getString("REAL_RESOURCE_TYPE"))){
					return true;
				}
			}
		}
		return flag;
	}

	/**
     * 匹配SPID和SPNAME
     * @param data
     */
    private void mateSpid(List<JSONObject> data){
    	try {
        	if(data != null && data.size()>0){
        		//产品列表
            	List<String> productids = new ArrayList<String>();
        		for(JSONObject obj : data){
        			productids.add(obj.getString("PRODUCT_ID"));
        		}
        		//根据产品列表获取产品信息
            	List<HashMap> spAopConfList = flowLimitDao.getSpAopConf(productids);
            	if(spAopConfList != null && spAopConfList.size()>0){
            		for(JSONObject obj : data){
            			for(HashMap hm : spAopConfList){
            				if(hm.get("PRODUCT_ID").equals(obj.get("PRODUCT_ID"))){
            					//设置SP信息
            					obj.put("SP_ID", hm.get("SP_ID"));
            					obj.put("PRODUCT_NAME", hm.get("PRODUCT_NAME"));
            					break;
            				}
            			}
            		}
            	}
        	}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(data+"匹配SPID出现异常，"+e.getMessage());
		}
    }
    
    /**
     * 查询流量
     * @param inputObj
     * @throws Exception 
     */
    public void qryflowunify(JSONObject inputObj) throws Exception{
    	Map<String, Object> logMap = new HashMap<String,Object>();
    	String cdnresult = "";
    	String ipresult = "";
		String invokeUrl = ""; //接口地址
		String params = ""; //调接口参数
		JSONArray data = new JSONArray(); //返回列表
		String userid = inputObj.getString("usermob"); //（手机号码）
    	try {
    		JSONArray cdnflowdata = null; //本地流量平台的流量数据。
    		JSONArray ipflowdata = null; //能力平台的流量数据
    		//1. 查询用户订购列表
    		List<HashMap> orderList = commConfDao.qryEffectiveRela(userid);
    		//logMap.put("当前订购关系", orderList);
			if((orderList != null || orderList.size() > 0)) {

				//查字典表获取IP免流CPID，
				String ipfreecpid = dictionaryDao.getValue("ipfreecpid");
				List<String> ipfreecpidList = null;
				if (StringUtils.isEmpty(ipfreecpid)) {
					ipfreecpidList = new ArrayList<String>();
				} else {
					ipfreecpidList = Arrays.asList(ipfreecpid.split("\\|"));
				}
				logMap.put("配置的IP免流CPID", ipfreecpidList);
				//所有订购的SPID
				List<String> allorderspid = new ArrayList<String>();
				//用户订购的所有IP免流SPID
				List<String> ipfreespid = new ArrayList<String>();
				for (HashMap hm : orderList) {
					allorderspid.add(hm.get("SPID").toString());
					if (ipfreecpidList.contains(hm.get("CPID"))) {
						ipfreespid.add(hm.get("SPID").toString());
					}
				}
				logMap.put("当前所有订购的SPID", allorderspid);
				logMap.put("已订购的IP免流SPID", ipfreespid);
				//免流产品的产品编码与SPID的对应关系
				List<HashMap> productids = new ArrayList<HashMap>();
				if (ipfreespid != null && ipfreespid.size() > 0) {
					productids = flowLimitDao.getSpAopConfBySpids(ipfreespid);
				}
				logMap.put("已订购的IP免流SPID对应的产品ID", productids);

				//2. 查询orderFlow/flowBill接口查出所有流量信息
				//http://172.16.1.81:809/orderFlow/flowQuerySpid
				invokeUrl = dictionaryDao.getValue("flowBillUrl");
				String key = dictionaryDao.getValue("flowBillKey");
				String deuserid = AESUtil.encrypt(userid, key); //加密手机号码
				String channel = "create";
				String timestamp = (System.currentTimeMillis()) / 1000 + "";
				String cpid = "*";
				String signature = deuserid + cpid + channel + timestamp + key;
				signature = MD5.MD5Encode(signature); //转换为十六进制ASCII 码字符串，共32 个字符，全小写 userid= Des(手机号码，pwd)
				params = "userid=" + URLEncoder.encode(deuserid, "utf-8") + "&cpid=" + cpid + "&channel=" + channel + "&timestamp=" + timestamp + "&signature=" + signature;

				invokeUrl += "?" + params;
				logMap.put("查询flowBill接口参数", invokeUrl);

				//调接口查询缓存流量， /orderFlow/flowBill
				cdnresult = URLUtil.get(invokeUrl, 30000);

				logMap.put("查询flowBill接口返回报文", cdnresult);
				if (!StringUtils.isEmpty(cdnresult)) {
					JSONObject resObj = new JSONObject().parseObject(cdnresult);
					if ("0".equals(resObj.getString("resultCode"))) {
						cdnflowdata = resObj.getJSONArray("data");
					}
					logMap.put("cdnflowdata", cdnflowdata);
				}

				//有订购IP免流产品，查能力平台
				if (productids != null && productids.size() > 0) {
					//3. 查询能力平台获取IP免流流量信息
					invokeUrl = dictionaryDao.getValue("shareselectallowUrl");
					String cycleId = new SimpleDateFormat("yyyyMM").format(new Date()); //（账期）,
					params = "cycleId=" + cycleId + "&userId=" + userid;
					invokeUrl += "?" + params;
					logMap.put("查询能力平台接口参数", invokeUrl);

					ipresult = URLUtil.get(invokeUrl, 30000);

					logMap.put("查询能力平台接口返回报文", ipresult);
					if (!StringUtils.isEmpty(ipresult)) {
						JSONObject resObj = new JSONObject().parseObject(ipresult);
						if ("0".equals(resObj.get("resultCode") + "") && resObj.getJSONArray("data") != null && resObj.getJSONArray("data").size() > 0) {
							JSONArray resdata = resObj.getJSONArray("data");

							//测试==============
							/****
							 String testdata = "{\"FEE_POLICY_NAME\":\"快手12G流量月包（附属）\",\"ADDUP_UPPER\":\"12582912\",\"X_USED_VALUE\":\"50168\","+
							 "\"X_CANUSE_VALUE\":\"12532744\",\"X_EXCEED_VALUE\":\"0\",\"CYCLE_ID\":\"202203\",\"PRODUCT_ID\":\"90785307\"}";
							 JSONObject testobj = JSONObject.parseObject(testdata);
							 resdata.add(testobj);
							 ****/
							//=======================

							JSONObject tmpobj = null;
							String productid = null;
							for (int i = 0; i < resdata.size(); i++) {
								tmpobj = (JSONObject) resdata.get(i);
								productid = tmpobj.getString("PRODUCT_ID");
								//获取用户已订购的产品流量信息
								for (HashMap tmp : productids) {
									//已订购
									if (productid.equals(tmp.get("PRODUCT_ID"))) {
										tmpobj.put("SP_ID", tmp.get("SP_ID"));//填充SPID
										if (ipflowdata == null) ipflowdata = new JSONArray();
										ipflowdata.add(tmpobj);
										break;
									}
								}
							}
						}
					}
					logMap.put("ipflowdata", ipflowdata);
				}

				//4. 解析及替换流量信息。
				//解析CDN查询的流量数据，剔除IP免流产品
				if (cdnflowdata != null && cdnflowdata.size() > 0) {
					JSONObject tmpobj = null;
					for (int i = 0; i < cdnflowdata.size(); i++) {
						tmpobj = (JSONObject) cdnflowdata.get(i);
						tmpobj.put("ipfree", "1"); //设置非IP免流
						tmpobj.put("surflow", tmpobj.getString("flow"));
						//tmpobj.remove("isold");
						//tmpobj.remove("islimit");
						//tmpobj.remove("istryout");
						//不是IP免流的产品，添加到返回列表
						if (!ipfreecpidList.contains(tmpobj.get("cpid"))) {
							data.add(tmpobj);
						}
					}
				}
				//解析IP免流数据
				if (ipflowdata != null && ipflowdata.size() > 0) {
					JSONObject tmpobj = null;
					JSONObject putobj = null;
    			/*
				"FEE_POLICY_NAME": "快手12G流量月包（附属）",————套餐名称
	            "ADDUP_UPPER": "12582912",————累计值上限
	            "X_USED_VALUE": "50168",————已经使用的免费资源量
	            "X_CANUSE_VALUE": "12532744",————剩余免费资源量
	            "X_EXCEED_VALUE": "0",————超出部分使用量
	            "CYCLE_ID": "202203",————查询账期
	            "PRODUCT_ID": "91043174",
    			 */
					for (int i = 0; i < ipflowdata.size(); i++) {
						putobj = new JSONObject();
						tmpobj = (JSONObject) ipflowdata.get(i);
						String spid = tmpobj.getString("SP_ID");
						HashMap spinfo = commConfDao.findSpInfo(spid).get(0);
						;
						putobj.put("ipfree", "0"); //是否IP免流	0代表是，1代表否
						putobj.put("spid", tmpobj.getString("SP_ID"));
						putobj.put("cpid", spinfo.get("CPID").toString());//设置CPID
						putobj.put("spname", spinfo.get("SPNAME").toString());
						//最大流量
						String maxflow = tmpobj.getString("ADDUP_UPPER");
						//剩余流量
						String surflow = tmpobj.getString("X_CANUSE_VALUE");
						//已使用流量
						String useflow = tmpobj.getString("X_USED_VALUE");
						//KB转为MB
						putobj.put("maxflow", formatDouble(Double.parseDouble(maxflow) / 1024));
						putobj.put("useflow", formatDouble(Double.parseDouble(useflow) / 1024));
						putobj.put("surflow", formatDouble(Double.parseDouble(surflow) / 1024));
						putobj.put("stime", "");
						putobj.put("etime", "");
						putobj.put("istryout", "");
						putobj.put("isold", "");
						putobj.put("islimit", "");
						data.add(putobj);
					}
				}
			}

    		try {
				String touTiaoSpid = dictionaryDao.getValue("touTiaoSpid");
				String[] split = touTiaoSpid.split(",");
				String caporderUrl = dictionaryDao.getValue("caporderUrl");
				HashMap<String,String> map = new HashMap<>();
				map.put("usermob",userid);
				map.put("period",getTime());
				for (String str:split){
					String[] strings = str.split("_");
					map.put("spid",strings[0]);
					map.put("cpid",strings[1]);
					String res = URLUtil.postJson(caporderUrl+"/intensive/currencyQueryCbssFlow", JSON.toJSONString(map));
					JSONObject object = JSON.parseObject(res);
					if ("0".equals(object.getString("resultcode"))){
						JSONArray array = object.getJSONArray("data");
						if (array!=null){
							JSONObject jsonObject = array.getJSONObject(0);
							boolean flag = true;
							for (int i =0;i<data.size();i++){
								if (data.getJSONObject(i).getString("spid").equals(strings[0])){
									data.remove(i);
									JSONObject putobj = new JSONObject();
									putobj.put("ipfree", "0"); //是否IP免流	0代表是，1代表否
									putobj.put("spid", strings[0]);
									putobj.put("cpid", strings[1]);//设置CPID
									putobj.put("spname", jsonObject.getString("productname"));
									//最大流量
									String maxflow = jsonObject.getString("maxflow");
									//剩余流量
									String surflow = jsonObject.getString("flow");
									//已使用流量
									String useflow = jsonObject.getString("useflow");
									//KB转为MB
									putobj.put("maxflow", formatDouble(Double.parseDouble(maxflow)/1024));
									putobj.put("useflow", formatDouble(Double.parseDouble(useflow)/1024));
									putobj.put("surflow", formatDouble(Double.parseDouble(surflow)/1024));
									putobj.put("stime", getTime(jsonObject.getString("starttime")));
									putobj.put("etime", getTime(jsonObject.getString("endtime")));
									putobj.put("istryout", "1");
									putobj.put("isold", "1");
									putobj.put("islimit", "1");
									data.add(putobj);
									flag =false;
									break;
								}
							}
							if (flag){
								JSONObject putobj = new JSONObject();
								putobj.put("ipfree", "0"); //是否IP免流	0代表是，1代表否
								putobj.put("spid", strings[0]);
								putobj.put("cpid", strings[1]);//设置CPID
								putobj.put("spname", jsonObject.getString("productname"));
								//最大流量
								String maxflow = jsonObject.getString("maxflow");
								//剩余流量
								String surflow = jsonObject.getString("flow");
								//已使用流量
								String useflow = jsonObject.getString("useflow");
								//KB转为MB
								putobj.put("maxflow", formatDouble(Double.parseDouble(maxflow)/1024));
								putobj.put("useflow", formatDouble(Double.parseDouble(useflow)/1024));
								putobj.put("surflow", formatDouble(Double.parseDouble(surflow)/1024));
								putobj.put("stime", getTime(jsonObject.getString("starttime")));
								putobj.put("etime", getTime(jsonObject.getString("endtime")));
								putobj.put("istryout", "1");
								putobj.put("isold", "1");
								putobj.put("islimit", "1");
								data.add(putobj);
							}
						}
					}
				}
			}catch (Exception e){
				e.printStackTrace();
			}
    		
    		logMap.put("返回流量消耗列表", data);

			if((data ==null||data.size() ==0)){
				throw new BussinessException("8013","无订购关系");
			}
		} catch (Exception e) {
			e.printStackTrace();
			if( e != null && e.getMessage().indexOf("http") != -1){
				throw new Exception("调查询接口出现错误");
			}else{
				throw e;
			}			
		} finally {
			inputObj.put("data", data);
			log.info(logMap);
		}
    }
    
    private String convertMB(String flowval){
    	String res = "";
    	double d = 0.200;
    	DecimalFormat df = new DecimalFormat("0.000");System.out.println(df.format(d));
    	return res;
    }

    public static String getTime(){
		SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
		return format.format(new Date());
	}

	public static String getTime(String date) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date parse = format2.parse(date);
		return format.format(parse);
	}


}
