package com.chinacreator.process.service;

import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.common.util.MD5;
import com.chinacreator.process.dao.CommonDao;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.MqSmsTempConfDao;
import com.chinacreator.process.util.DesUtil;
import com.chinacreator.process.util.HttpInvoke;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.process.util.SHAUtil;

/**
 * 订购退订短信模板服务类
 * @author xu.zhou
 * @date 20220902
 */
@Component
public class CShandleSmsTempService {
	
	private Logger logger = Logger.getLogger("cssms");
	
	@Autowired
	private CommonDao commonDao;
	
    @Autowired
    private MqSmsTempConfDao mqSmsConfDao;
    
    @Autowired
    private DictionaryDao dictionaryDao;
	
	/**
	 * 获取调短信接口的模板参数
	 * @param mqsmsconf
	 * @param bodyparams
	 * @param tmplogmap 日志对象
	 * @return
	 */
	public HashMap<String, String> getInvokeparams(HashMap mqsmsconf, HashMap<String, String> bodyparams, HashMap tmplogmap) throws Exception{
    	//短信参数
    	String [] smsparamsArray = mqsmsconf.get("PARAMS").toString().split("\\|");
    	//短信参数映射
    	String [] smsparamsmappArray = mqsmsconf.get("PARAMSMAPP").toString().split("\\|");
    	//获取mq表的参数映射
    	String mqparamsmapp = (String)mqsmsconf.get("MQPARAMSMAPP");
    	//有个性化配置映射，优先级高于TB_SMSTEMP_CONF的MQPARAMSMAPP配置
    	if(!StringUtils.isEmpty(mqparamsmapp)){
    		smsparamsmappArray = mqparamsmapp.split("\\|");
    	}
		//调接口模板参数
    	HashMap<String, String> invokeparams = new HashMap<String, String>();
    	String param1 = bodyparams.get("param1");
    	String param2 = bodyparams.get("param2");
    	String param3 = bodyparams.get("param3");
    	String userid = bodyparams.get("userid");
    	String param = "";
    	//组建调接口模板参数
    	for(int p = 0; p < smsparamsArray.length; p++){
    		param = smsparamsArray[p];
    		if("param1".equals(param)){ //自定义预留参数1
    			if(!param.equals(smsparamsmappArray[p])){
        			invokeparams.put(param, smsparamsmappArray[p]);
    			}else{
        			invokeparams.put(param, fullNullStr(param1));
    			}
    		}else if("param2".equals(param)){//自定义预留参数2
    			if(!param.equals(smsparamsmappArray[p])){
        			invokeparams.put(param, smsparamsmappArray[p]);
    			}else{
    				invokeparams.put(param, fullNullStr(param2));
    			}
    		}else if("param3".equals(param)){//自定义预留参数3
    			if(!param.equals(smsparamsmappArray[p])){
        			invokeparams.put(param, smsparamsmappArray[p]);
    			}else{
    				invokeparams.put(param, fullNullStr(param3));
    			}
       		}else if("oriuserid".equals(param)){//原始手机号码
    			invokeparams.put(param, userid);                    			
    		}else if("userid".equals(param)){
    			//模糊化
    			String fulluserid = userid.substring(0, 3)+"****"+userid.substring(7);
    			invokeparams.put(param, fulluserid);
    		}else if("mm".equals(param)){
    			invokeparams.put(param, DateFormatUtils.format(new Date(), "MM"));
    		}else if("dd".equals(param)){
    			invokeparams.put(param, DateFormatUtils.format(new Date(), "dd"));
    		}else if("spname".equals(param)){
    			if(!param.equals(smsparamsmappArray[p])){
        			invokeparams.put(param, smsparamsmappArray[p]);
    			}else{
        			invokeparams.put(param, (String)mqsmsconf.get("SPNAME"));
    			}
    		}else if("price".equals(param)){
    			if(!param.equals(smsparamsmappArray[p])){
        			invokeparams.put(param, smsparamsmappArray[p]);
    			}else{
    				invokeparams.put(param, (String)mqsmsconf.get("PRICE"));
    			}
    		}else if("cpname".equals(param)){
    			if(!param.equals(smsparamsmappArray[p])){
        			invokeparams.put(param, smsparamsmappArray[p]);
    			}else{
    			    invokeparams.put(param, fullNullStr((String)mqsmsconf.get("SMSCPNAME")));
    			}
    		}else if("maxflow".equals(param)){
    			if(!param.equals(smsparamsmappArray[p])){
        			invokeparams.put(param, smsparamsmappArray[p]);
    			}else{
    				String maxflow = (String)mqsmsconf.get("MAXFLOW");
    				if(!StringUtils.isEmpty(maxflow)){
    					try {
    						//转为G
    						maxflow = (Integer.parseInt(maxflow)/1024)+"";
						} catch (Exception e) {
							e.printStackTrace();
						}
    				}
    				invokeparams.put(param, maxflow);
    			}
    		}else if(param.indexOf("expdate") != -1){
    			if(!param.equals(smsparamsmappArray[p])){
        			invokeparams.put(param, smsparamsmappArray[p]);
    			}else{
        			if(param.split("-").length == 2){
        				//计算当天时间加上多少天，含多少天，显示开始时间和结束时间
        				SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        				//当前时间加多少天
        				int day = Integer.parseInt(param.split("-")[1]);
        				day = day - 1; //当天也包含
        			    Date currdate = new Date();
        			    Calendar ca = Calendar.getInstance();
        			    ca.setTime(currdate);
        			    ca.add(Calendar.DATE, day);
        			    Date enddate = ca.getTime();	                    		        
                        invokeparams.put(param, sdf.format(new Date())+"-"+sdf.format(enddate));
        			}else{                   			
        				invokeparams.put(param, DateFormatUtils.format(new Date(), "yyyyMMdd"));
        			}
    			}
    		}else if("mappid".equals(param)){//映射ID
    			if(!param.equals(smsparamsmappArray[p])){
        			invokeparams.put(param, smsparamsmappArray[p]);
    			}else{
    				//调接口获取mappid
    				String mappid = fullNullStr(getMappidByUserid(userid, tmplogmap));
    				invokeparams.put(param, mappid);
    			}
    		}else if("tranchannel".equals(param)){//办理渠道
    			if(!param.equals(smsparamsmappArray[p])){
        			invokeparams.put(param, smsparamsmappArray[p]);
    			}else{
    				//调接口获取mappid
    				String tranchannel = fullNullStr(getTranchannel(mqsmsconf.get("BUSITYPE").toString()));
    				invokeparams.put(param, tranchannel);
    			}    			
    		}else{//按配置的信息设置
    			invokeparams.put(param, fullNullStr(smsparamsmappArray[p]));
    		}
    	}
    	
    	return invokeparams;
	}
	
	/**
	 * 获取办理渠道的名称
	 * @param busitype
	 * @return
	 * @throws SQLException
	 */
	private String getTranchannel(String busitype) throws Exception{
		String tranchannel = "";
		HashMap confMap = mqSmsConfDao.getChannelConfByBusitype(busitype);
		if(confMap != null && confMap.size() > 0){
			tranchannel = (String)confMap.get("CHANNLE");
		}
		
		return tranchannel;
	}
	
    /**
     * 为空时返回一个空格，短信接口传空串会报错
     * @param p
     * @return
     */
    private String fullNullStr(String p){
    	if(StringUtils.isEmpty(p)){
    		return " ";
    	}else{
    		return p;
    	}
    }
	
	/***
	 * 按排序验证配置数据
	 * busitype必须相同
	 * 获取配置信息排序：
	 * 配置字段：CHANNEL, SUBCHANNEL, PROVCINCE, STARTTIME, ENDTIME
	 * 
	 * 1. CHANNEL,SUBCHANNEL,PROVINCE,STARTTIME,ENDTIME有配置
	 * 2. CHANNEL,SUBCHANNEL,PROVINCE有配置，但STARTTIME,ENDTIME无配置
	 * 3. CHANNEL,PROVINCE,STARTTIME,ENDTIME有配置，SUBCHANNEL无配置
	 * 4. CHANNEL,PROVINCE有配置，SUBCHANNEL,STARTTIME,ENDTIME无配置
	 * 5. PROVINCE,STARTTIME,ENDTIME有配置，CHANNEL,SUBCHANNEL无配置
	 * 6. PROVINCE有配置，CHANNEL,SUBCHANNEL,STARTTIME,ENDTIME无配置
	 * 7. CHANNEL,SUBCHANNEL,STARTTIME,ENDTIME有配置,PROVINCE无配置
	 * 8. CHANNEL,SUBCHANNEL有配置，,PROVINCE,STARTTIME,ENDTIME无配置
	 * 9. CHANNEL,STARTTIME,ENDTIME有配置,PROVINCE,SUBCHANNEL无配置
	 * 10. CHANNEL有配置，,PROVINCE,SUBCHANNEL,STARTTIME,ENDTIME无配置                		 
	 * 11. STARTTIME,ENDTIME有配置,CHANNEL,SUBCHANNEL,PROVINCE无配置
	 * 12. 全都无配置
	 */
    public HashMap getMqSmsConfBySort(List<HashMap> confList, HashMap<String, String> bodyparams, HashMap logmap){
    	HashMap mqsmsconf = null;
    	//配置不能为空的参数
    	List<String> notnullparams = new ArrayList<String>();
    	//配置要为空的参数
    	List<String> nulllparams = new ArrayList<String>();
    	if(mqsmsconf == null){
    		//* 1. CHANNEL,SUBCHANNEL,PROVINCE,STARTTIME,ENDTIME有配置
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{"CHANNEL","SUBCHANNEL","PROVINCE","STARTTIME","ENDTIME"});
    		nulllparams = Arrays.asList(new String[]{});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	if(mqsmsconf == null){
    		//* 2. CHANNEL,SUBCHANNEL,PROVINCE有配置，但STARTTIME,ENDTIME无配置
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{"CHANNEL","SUBCHANNEL","PROVINCE"});
    		nulllparams = Arrays.asList(new String[]{"STARTTIME","ENDTIME"});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	if(mqsmsconf == null){
    	//* 3. CHANNEL,PROVINCE,STARTTIME,ENDTIME有配置，SUBCHANNEL无配置
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{"CHANNEL","PROVINCE","STARTTIME","ENDTIME"});
    		nulllparams = Arrays.asList(new String[]{"SUBCHANNEL"});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	if(mqsmsconf == null){
    	//* 4. CHANNEL,PROVINCE有配置，SUBCHANNEL,STARTTIME,ENDTIME无配置
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{"CHANNEL","PROVINCE"});
    		nulllparams = Arrays.asList(new String[]{"SUBCHANNEL","STARTTIME","ENDTIME"});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	if(mqsmsconf == null){
    	//* 5. PROVINCE,STARTTIME,ENDTIME有配置，CHANNEL,SUBCHANNEL无配置
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{"PROVINCE","STARTTIME","ENDTIME"});
    		nulllparams = Arrays.asList(new String[]{"CHANNEL","SUBCHANNEL"});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	if(mqsmsconf == null){
    	//* 6. PROVINCE有配置，CHANNEL,SUBCHANNEL,STARTTIME,ENDTIME无配置
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{"PROVINCE"});
    		nulllparams = Arrays.asList(new String[]{"CHANNEL","SUBCHANNEL","STARTTIME","ENDTIME"});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	if(mqsmsconf == null){
    	//* 7. CHANNEL,SUBCHANNEL,STARTTIME,ENDTIME有配置,PROVINCE无配置
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{"CHANNEL","SUBCHANNEL","STARTTIME","ENDTIME"});
    		nulllparams = Arrays.asList(new String[]{"PROVINCE"});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	if(mqsmsconf == null){
    	//* 8. CHANNEL,SUBCHANNEL有配置，,PROVINCE,STARTTIME,ENDTIME无配置
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{"CHANNEL","SUBCHANNEL"});
    		nulllparams = Arrays.asList(new String[]{"PROVINCE","STARTTIME","ENDTIME"});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	if(mqsmsconf == null){
    	//* 9. CHANNEL,STARTTIME,ENDTIME有配置,PROVINCE,SUBCHANNEL无配置
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{"CHANNEL","STARTTIME","ENDTIME"});
    		nulllparams = Arrays.asList(new String[]{"SUBCHANNEL","PROVINCE"});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	if(mqsmsconf == null){
    	//* 10. CHANNEL有配置，,PROVINCE,SUBCHANNEL,STARTTIME,ENDTIME无配置
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{"CHANNEL"});
    		nulllparams = Arrays.asList(new String[]{"SUBCHANNEL","PROVINCE","STARTTIME","ENDTIME"});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	if(mqsmsconf == null){
    	//* 11. STARTTIME,ENDTIME有配置,CHANNEL,SUBCHANNEL,PROVINCE无配置
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{"STARTTIME","ENDTIME"});
    		nulllparams = Arrays.asList(new String[]{"CHANNEL","SUBCHANNEL","PROVINCE"});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	if(mqsmsconf == null){
    	//* 12. 全都无配置		
    		notnullparams = new ArrayList<String>();
    		nulllparams = new ArrayList<String>();
    		notnullparams = Arrays.asList(new String[]{});
    		nulllparams = Arrays.asList(new String[]{"CHANNEL","SUBCHANNEL","PROVINCE","STARTTIME","ENDTIME"});
    		mqsmsconf = getMqSmsConf(confList, bodyparams, notnullparams, nulllparams, logmap);
    	}
    	return mqsmsconf;
    }
    
    /**
     * 获取短信配置数据
     * @param confList 配置列表
     * @param bodyparams 输入参数
     * @param notnullparams 不能为空的参数
     * @param nulllparams 要为空的参数
     * @param logmap
     * @return
     */
    private HashMap getMqSmsConf(List<HashMap> confList, HashMap<String, String> bodyparams, List<String> notnullparams, List<String> nulllparams, HashMap logmap){
    	HashMap mqsmsconf = null;
    	String confbusitype = null;
		for(HashMap tmphm : confList){
  			 confbusitype = tmphm.get("BUSITYPE").toString();
			//busiType完全相同
			if(confbusitype.equals(bodyparams.get("busiType")) 
					&& notNullVali(bodyparams,notnullparams,tmphm)
					&& nullVali(bodyparams,nulllparams,tmphm) 
					){   
				//验证当前是否在配置的发送时间内
				if(valisendtime(tmphm)){
					mqsmsconf = tmphm;
					//跳出循环
					break;
				}else{
					logmap.put("valitime", "当前时间不在配置范围内");
				}
			}
  	    }
    	return mqsmsconf;
    }
    
    /**
     * 参数不能为空的验证
     * @param bodyparams
     * @param notnullparams
     * @param tmpconf
     * @return
     */
    private boolean notNullVali(HashMap<String, String> bodyparams, List<String> notnullparams, HashMap tmpconf){
    	boolean res = true;
    	if(notnullparams == null || notnullparams.size() == 0){
    		return res;
    	}
    	String busiType = bodyparams.get("busiType"); //业务类型
        String channel = bodyparams.get("channel"); //渠道
        String subchannel = bodyparams.get("subchannel");//子渠道
        String province = bodyparams.get("province"); //省份
    	for(String param : notnullparams){
    		if("PROVINCE".equals(param) && (tmpconf.get("PROVINCE") == null || !tmpconf.get("PROVINCE").equals(province))){
    			res = false;
    			break;
    		}
    		if("SUBCHANNEL".equals(param) && (tmpconf.get("SUBCHANNEL") == null || !tmpconf.get("SUBCHANNEL").equals(subchannel))){
    			res = false;
    			break;
    		} 
    		if("CHANNEL".equals(param) && (tmpconf.get("CHANNEL") == null || !tmpconf.get("CHANNEL").equals(channel))){
    			res = false;
    			break;
    		} 
    		//STARTTIME和ENDTIME都为空，验证不通过
    		if(("STARTTIME".equals(param) || "ENDTIME".equals(param)) && (tmpconf.get("STARTTIME") == null && tmpconf.get("ENDTIME") == null )){
    			res = false;
    			break;
    		}      		
    	}
    	return res;
    }
    
    /**
     * 参数可以为空的验证
     * @param bodyparams
     * @param nullparams
     * @param tmpconf
     * @return
     */
    private boolean nullVali(HashMap<String, String> bodyparams, List<String> nullparams, HashMap tmpconf){
    	boolean res = true;
    	if(nullparams == null || nullparams.size() == 0){
    		return res;
    	}
    	for(String param : nullparams){
    		if("PROVINCE".equals(param) && tmpconf.get("PROVINCE") != null){
    			res = false;
    			break;
    		}
    		if("SUBCHANNEL".equals(param) && tmpconf.get("SUBCHANNEL") != null){
    			res = false;
    			break;
    		} 
    		if("CHANNEL".equals(param) && tmpconf.get("CHANNEL") != null){
    			res = false;
    			break;
    		} 
    		if("STARTTIME".equals(param) && tmpconf.get("STARTTIME") != null){
    			res = false;
    			break;
    		} 
    		if("ENDTIME".equals(param) && tmpconf.get("ENDTIME") != null){
    			res = false;
    			break;
    		} 
    	}
    	return res;
    }
    
    /**
     * 判断当前时间是否在配置的时间范围内，如果有配置
     * @param mqsmsconf
     * @return  true 未限制，false被限制
     */
    private boolean valisendtime(HashMap mqsmsconf){
    	//默认为成功
    	boolean res = true;
    	//发送时间验证
		String sendstarttime = (String)mqsmsconf.get("STARTTIME");
		String sendendtime = (String)mqsmsconf.get("ENDTIME");		
		String currtime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		//有配置短信发送开始时间，但当前时间小于开始时间
		if(!StringUtils.isEmpty(sendstarttime) && Long.parseLong(currtime) < Long.parseLong(sendstarttime)){
			res = false;
		}
		//有配置短信发送结束时间，但当前时间大于结束时间
		if(!StringUtils.isEmpty(sendendtime) && Long.parseLong(currtime) > Long.parseLong(sendendtime)){
			res = false;
		}

    	return res;
    }
    
    /**
     * 根据手机号码获取映射ID，用于页面自动登录
     * @param userid
     * @return
     */
    private String getMappidByUserid(String userid, HashMap<String, Object> logmap){
    	String mappid = "";
    	String resultcode = "5000";
    	String errorinfo = "";
    	HashMap<String, Object> tmplogmap = new HashMap<String, Object>();
    	try {   		
			HashMap confhm = commonDao.getInvokeUrlInfo("univideo", "usermappqrymappid", "2");
			if(confhm == null || confhm.size() == 0){
				throw new BusinessException("9012","无接口配置信息");
			}
			
			String url = confhm.get("INVOKEURL").toString();
			JSONObject params1 = JSONObject.parseObject((String)confhm.get("PARAM1"));
			String method = params1.getString("METHOD");
			int timeout = params1.getInteger("TIMEOUT");
			String tls = params1.getString("TLS");
			String contentttype = params1.getString("CONTENTTYPE");
			String channel = params1.getString("CHANNEL");
			//加密KEY
			String pwd = params1.getString("PWD");
			Map reqProperty = new HashMap();
			if(!StringUtils.isEmpty(contentttype)){
				reqProperty.put("Content-type", contentttype);
			}
    		String account = userid;
    		String timestamp = (System.currentTimeMillis())/1000+"";
    		account = DesUtil.encode(account, pwd);
    		String signature = account+channel+timestamp+pwd;
    		signature = MD5.MD5Encode(signature);
    		JSONObject params = new JSONObject();
    		params.put("account", account);
    		params.put("channel", channel);
    		params.put("timestamp", timestamp);
    		params.put("signature", signature);
    		tmplogmap.put("invokeparams", params.toJSONString());
    		String res = "";
    		if(url.startsWith("https")){
    			res = HttpInvoke.sendhttpsReqAll(method, url, params.toJSONString(), reqProperty, timeout*1000, tls);
    		}else{
    			res = HttpInvoke.sendHttpByPost(method, url, params.toJSONString(), reqProperty, timeout*1000);
    		}
    		
			tmplogmap.put("invokeres", res);
			/**
			 {
			    "resultcode":"0",
			    "errorinfo":"ok",
			    "data":{
			        "userid":"UooUmz1MQgSRsKdMZVpGIQ==",
			        "mappid":"9e888164125f44359943d48b566355da"
			    }
			}
			**/
			if(!StringUtils.isEmpty(res)){
				JSONObject tmp = JSONObject.parseObject(res);
				resultcode = tmp.getString("resultcode");
				errorinfo = tmp.getString("errorinfo");
				if(tmp.getJSONObject("data") != null){
					mappid = tmp.getJSONObject("data").getString("mappid");
				}
			}
		} catch (Exception e) {
			if (e instanceof BusinessException) {
				resultcode = ((BusinessException)e).getCode();
				errorinfo = ((BusinessException)e).getMessage();
			}else{
				e.printStackTrace();
				resultcode = "8000";
				errorinfo = "获取映射ID出现异常，"+e.getMessage();
			}
		} finally {
			tmplogmap.put("resultcode", resultcode);
			tmplogmap.put("errorinfo", errorinfo);	
			logmap.put("getMappidByUserid", tmplogmap);
		}
    	
    	return mappid;
    }
    
    /**
     * 发送退订营销短信
     * @param userid 手机嘎巴
     * @param spid spid
     * @param busitype 业务类型
     * @param mainlogmap 主日志对象
     */
    public void sendCancelYxSms(HashMap<String, String> bodyparams, HashMap mainlogmap){
    	String userid = bodyparams.get("userid");
    	String spid = bodyparams.get("spid");
    	String busitype = bodyparams.get("busiType");
    	if(busitype.indexOf("cancel_succ") == -1){
    		return;
    	}
    	String resultcode = "5000";
    	String errorinfo = "";
    	String phcpid = "";	//偏好CPID
    	String hyspid = ""; //合约产品SPID
    	HashMap<String, Object> tmplogmap = new HashMap<String, Object>();
    	HashMap<String, String> vargs = null;
    	try {
			List<HashMap> dataList = mqSmsConfDao.qryCancelYxConf(busitype);
			if(dataList == null || dataList.size() == 0){
				throw new BusinessException("9002","业务类型【"+busitype+"】无营销配置");
			}
			tmplogmap.put("hasconf", "0");//是否有配置
			tmplogmap.put("userid", userid);
			tmplogmap.put("busitype", busitype);
			
			//调柏源用户偏好接口
			String res = this.invokeCancelyx(userid, tmplogmap);
			//res = "{\"code\":200,\"success\":true,\"data\":\"aiqy\",\"msg\":\"操作成功\"}";
			JSONObject resobj = JSONObject.parseObject(res);
			if(resobj.get("code") != null && resobj.getInteger("code") == 200 
					&& resobj.getBoolean("success") == true){ //调接口成功
				phcpid = resobj.getString("data");
			}
			//得到了偏好CP
			if(!StringUtils.isEmpty(phcpid)){
				//用户是否已订购偏好CP产品
				List<HashMap> relList = commonDao.qryRealByUserid(userid, phcpid, null,"2");
				//芒果CPID特殊处理，多一次查询
				if(relList == null || relList.size() == 0){
					//是mangtv，则再查一次mangtv16
					if("mangtv".equals(phcpid)){
						relList = commonDao.qryRealByUserid(userid, "mangtv16", null,"2");
					}else if("mangtv16".equals(phcpid)){//是mangtv16，则再查一次mangtv
						relList = commonDao.qryRealByUserid(userid, "mangtv", null,"2");
					}
				}		
				
				//判断是否订购了后向产品，如果是，则剔除
				if(relList != null && relList.size()>0){
					Iterator<HashMap> it = relList.iterator();;
					HashMap hm = null;
					HashMap backconf = null;
					while(it.hasNext()){
						hm = it.next();
						//查询是否为后向产品
						backconf = commonDao.qryBackBusiBySpid((String)hm.get("SPID"));
						if(backconf != null && backconf.size() > 0){
							logger.info("后向产品不参与统计=>" + hm.get("SPID"));
							it.remove(); //移除对象
						}
					}
					//再次判断
					if(relList != null && relList.size()>0){
						throw new BusinessException("9013","已有【"+phcpid+"】订购关系");
					}
				}
				
				HashMap cancelyxconf = null;
				for(HashMap tmp : dataList){				
					if(phcpid.equals(tmp.get("PHCPID"))){//有偏好CP配置
						cancelyxconf = tmp;
						break;
					}			
				}
				
				//有营销配置
				if(cancelyxconf != null){
					tmplogmap.put("cancelyxconf", cancelyxconf);
					hyspid = cancelyxconf.get("HYSPID").toString();
					//获取合约产品的合约期
					HashMap hymap = commonDao.qryHyProduct(hyspid);
					if(hymap == null || hymap.size() == 0){
						throw new BusinessException("9014","合约产品【"+hyspid+"】无有效期配置");
					}
					int month = Integer.parseInt(hymap.get("MONTH").toString());
					//查询是否订购了合约产品
					List<HashMap> relList2 = commonDao.qryRealByUserid(userid, null, hyspid, null);
					//订购了合约主品，已失效
					if(relList2 != null && relList2.size()>0){
						boolean hasRetryOrder = mqSmsConfDao.hasRetryOrder(userid, hyspid, month);
						if(!hasRetryOrder){
							throw new BusinessException("9015","上次订购合约产品的合约期未到期，hyspid【"+hyspid+"】，month【"+month+"】");
						}
					}
					//是否成功发送过营销短信，且已超过合约期的月份
					/**
					boolean hasRetrySendSms = mqSmsConfDao.hasRetrySendSms(userid, hyspid, month);
					if(!hasRetrySendSms){
						throw new BusinessException("9016","上次发送营销短信未超过合约期，hyspid【"+hyspid+"】，month【"+month+"】");
					}
					**/
					//获取调接口参数
					vargs = this.getInvokeparams(cancelyxconf, bodyparams, tmplogmap);
					tmplogmap.put("vars", vargs);
					if(vargs == null || vargs.size() == 0){
						throw new BusinessException("9008","退订营销短信无模板参数匹配");
					}
					//模板ID
					String smstempid = (String)cancelyxconf.get("SMSTEMPID");
					tmplogmap.put("营销模板ID", smstempid);
					tmplogmap.put("smstype", "smsjh");
					//调短信发送接口
					String smsres = sendSMS(userid,smstempid,JsonUtil.objectToJson(vargs),"smsjh",tmplogmap);
					//smsres = "{\"resultcode\":\"0\",\"errorinfo\":\"\",\"taskid\":\"202208191529181184600\",\"ssmsid\":null}";
					tmplogmap.put("sendsmsres", smsres);
					JSONObject smsresobj = JSONObject.parseObject(smsres);
					if("0".equals(smsresobj.getString("resultcode"))){
				    	resultcode = "0";
				    	errorinfo = "ok";
					}else{
						resultcode = "9099";
						errorinfo = "发送短信失败，" + smsres;
					}
				}else{
					throw new BusinessException("9009","偏好CP无模板配置【"+phcpid+"】");
				}
			}else{
				throw new BusinessException("9019","柏源接口无偏好CP返回");
			}
		} catch (Exception e) {
			if (e instanceof BusinessException) {
				resultcode = ((BusinessException)e).getCode();
				errorinfo = ((BusinessException)e).getMessage();
			}else{
				e.printStackTrace();
				resultcode = "8000";
				errorinfo = "出现异常，"+e.getMessage();
			}
		} finally {
			//有配置则记录数据，输出日志
			if("0".equals(tmplogmap.get("hasconf"))){
				tmplogmap.put("resultcode", resultcode);
				tmplogmap.put("errorinfo", errorinfo);				
				try {
					HashMap<String, String> params = new HashMap<String, String>();
					params.put("HYSPID", hyspid);
					params.put("SPNAME", commonDao.qrySpinfoBySpid(spid).get("SPNAME")+"");
					params.put("PHCPID", phcpid);
					params.put("USERID", userid);
					params.put("RESULTCODE", resultcode);
					params.put("ERRORINFO", errorinfo);	
					params.put("BUSITYPE", busitype);	
					params.put("SPID", spid);	
					params.put("VARGS", (vargs == null ? null : vargs.toString()));
					params.put("OUTPARAMS", (String)tmplogmap.get("invokeres"));
					boolean flag = mqSmsConfDao.addCancelyxRec(params);
					tmplogmap.put("addCancelyxRec", flag);
				} catch (Exception e) {
					e.printStackTrace();
					tmplogmap.put("addCancelyxRec", "false "+e.getMessage());
				}
				//输出日志
				//logger.info(logmap);
				mainlogmap.put("cancelyxsms", tmplogmap);
			}
		}
    }

    /**
     * 调柏源用户偏好接口
     * @param userid
     * @return
     * @throws Exception 
     */
    private String invokeCancelyx(String userid, HashMap<String, Object> logmap) throws Exception{
    	String res = "";
    	try {
			HashMap confhm = commonDao.getInvokeUrlInfo("activeprocess", "foreigngetCpid", "1");
			if(confhm == null || confhm.size() == 0){
				throw new BusinessException("9012","无接口配置信息");
			}
			logmap.put("invokeconf", confhm);
			String url = confhm.get("INVOKEURL").toString();
			JSONObject params1 = JSONObject.parseObject((String)confhm.get("PARAM1"));
			String method = params1.getString("METHOD");
			int timeout = params1.getInteger("TIMEOUT");
			String tls = params1.getString("TLS");
			String contentttype = params1.getString("CONTENTTYPE");
			String channel = params1.getString("CHANNEL");
			//加密KEY
			String despwd = params1.getString("DESPWD");
			Map reqProperty = new HashMap();
			if(!StringUtils.isEmpty(contentttype)){
				reqProperty.put("Content-type", contentttype);
			}
			JSONObject content = new JSONObject();
			if(StringUtils.isEmpty(despwd)){ //密钥为空，参数不加密
				content.put("phone", userid);
			}else{
				content.put("phone", DesUtil.encode(userid, despwd));
			}
			
			logmap.put("invokeCancelyxparams", userid+"=>"+content.toJSONString());
			res = HttpInvoke.sendhttpsReqAll(method, url, content.toJSONString(), reqProperty, timeout*1000, tls);
			logmap.put("invokeCancelyxres", res);
		} catch (Exception e) {
			if (e instanceof BusinessException) {
				throw e;
			}else{
				e.printStackTrace();
				throw new BusinessException("8000","调柏源用户偏好接口出现异常，"+e.getMessage());
			}
		}
    	return res;
    }
    
    /**
     * 根据短信模板发送短信
     * @param userid
     * @param tempid 模板ID
     * @param params 参数变量
     * @param smswgname 短信网关类型， sms117走117网关，smsjh走聚合网关      
     * @return
     */
    public String sendSMS(String userid, String tempid, String params, String smswgname, HashMap<String, Object> logmap) {
    	String res = "";
        try {
        	logmap.put("vars", params);
        	//获取发送短信的地址及其他配置
			HashMap confhm = commonDao.getInvokeUrlInfo("common", smswgname, "2");
			if(confhm == null || confhm.size() == 0){
				throw new BusinessException("9011","无短信接口配置信息");
			}
			String invokeurl = confhm.get("INVOKEURL").toString();
			JSONObject params1 = JSONObject.parseObject((String)confhm.get("PARAM1"));
			String smsid = params1.getString("SMSID");
			String key = params1.getString("PWD");
			String method = params1.getString("METHOD");
			int timeout = 0; 
			try {
				timeout = params1.getInteger("TIMEOUT");
			} catch (Exception e) {
				timeout = 10;
			}
			String tls = params1.getString("TLS");
            String contentid = tempid;     
            String timestamp = System.currentTimeMillis() / 1000 + "";
            String usermob = DesUtil.encode(userid, key);
            String vars = params;
            String sign = SHAUtil.shaEncode(smsid + usermob + timestamp + vars + contentid + key).toLowerCase();
            //手机号码和参数转码
            usermob = URLEncoder.encode(usermob, "utf-8");
            vars = URLEncoder.encode(vars, "utf-8");         
            String invokeparams = "userid=" + usermob + "&smsid=" + smsid + "&timestamp=" + timestamp + "&sign=" + sign + "&contentid=" + contentid + "&vars=" + vars;
            String url = invokeurl+"?"+invokeparams;
            if(invokeurl.startsWith("https")){
            	res = HttpInvoke.sendhttpsReqAll(method, url, null, null, timeout*1000, tls);
            }else{
            	res = HttpInvoke.sendHttpByGet(invokeurl,timeout*1000);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            res = "发送短信出现异常，"+e.getMessage();
        }
        return res;
    }
    
    /**
     * 发送第一条短信
     * @param bodyparams
     * @param mainlogmap
     */
    public void sendFirSms(HashMap<String, String> bodyparams, HashMap mainlogmap){
    	HashMap<String, Object> tmplogmap = new HashMap<String, Object>();
    	String resultcode = "5000";
    	String errorinfo = "";
    	try {
        	
        	String userid = bodyparams.get("userid");
        	String spid = bodyparams.get("spid");
        	String busitype = bodyparams.get("busiType");
        	//短信表配置
        	HashMap mqsmsconf = null; 
        	List<HashMap> confList = mqSmsConfDao.getConfListBySpid(spid, busitype);
        	if(confList == null || confList.size() == 0){
        		throw new BusinessException("9001","sp产品短信发送无配置");
        	}
        	//获取短信配置信息
        	mqsmsconf = this.getMqSmsConfBySort(confList, bodyparams, tmplogmap);
        	if(mqsmsconf == null || mqsmsconf.size() == 0){
        		throw new BusinessException("9003","sp产品无对应业务短信配置");
        	}
        	
        	//移除时间验证失败标记
        	tmplogmap.remove("valitime");
        	
        	//短信模板ID
        	String smstempid = (String)mqsmsconf.get("SMSTEMPID");
        	
        	if(StringUtils.isEmpty(smstempid)){
        		throw new BusinessException("9006","无模板ID配置");
        	}
        	
        	tmplogmap.put("mqsmsconf", mqsmsconf);
        	
        	//获取调短信接口的模板参数
        	HashMap<String, String> invokeparams = this.getInvokeparams(mqsmsconf, bodyparams, tmplogmap);
        	tmplogmap.put("invokeparams", JsonUtil.objectToJson(invokeparams));
        	
        	//调接口参数不为空
        	if(invokeparams != null && invokeparams.size()>0){
        		//调接口发送短信
        		tmplogmap.put("smstype", "sms117");
        		String sendres = this.sendSMS(userid,smstempid,JsonUtil.objectToJson(invokeparams),"sms117", tmplogmap);
        		tmplogmap.put("sendsmsres", sendres);
        		//华胜数据查询小时问隔
        		String huashengpushhour = dictionaryDao.getValue("huashengpushhour");
        		//更新华胜推送表数据
        		boolean updhuasheng = mqSmsConfDao.updHuaShengWaitInfo(userid, spid, busitype, huashengpushhour);
        		tmplogmap.put("updhuasheng", updhuasheng);
        	}
        	resultcode = "0";
        	errorinfo = "ok";
		} catch (Exception e) {
			if (e instanceof BusinessException) {
				resultcode = ((BusinessException) e).getCode();
				errorinfo = ((BusinessException) e).getMessage();
			}else{
				e.printStackTrace();
				resultcode = "8000";
				errorinfo = "处理出现异常，"+e.getMessage();
			}
		} finally {
			tmplogmap.put("resultcode", resultcode);
			tmplogmap.put("errorinfo", errorinfo);
			mainlogmap.put("sendFirSms", tmplogmap);
		}
    }
    
    /**
     * 发送第二条短信
     * @param bodyparams
     * @param mainlogmap
     */
    public void sendSecSms(HashMap<String, String> bodyparams, HashMap mainlogmap){
    	HashMap<String, Object> tmplogmap = new HashMap<String, Object>();
    	String resultcode = "5000";
    	String errorinfo = "";
    	try {
        	String userid = bodyparams.get("userid");
        	String spid = bodyparams.get("spid");
        	String busitype = bodyparams.get("busiType");
        	List<HashMap> confList = mqSmsConfDao.getSecConfListBySpid(spid,busitype);
        	if(confList == null || confList.size() == 0){
        		throw new BusinessException("9001","sp产品短信发送无配置");
        	}
        	HashMap mqsmsconf = getMqSmsConfBySort(confList, bodyparams, tmplogmap);
        	if(mqsmsconf == null || mqsmsconf.size() == 0){
        		throw new BusinessException("9003","sp产品无对应业务短信配置");
        	}
        	//移除时间验证失败标记
        	tmplogmap.remove("valitime");
        	
        	//短信模板ID
        	String smstempid = (String)mqsmsconf.get("SMSTEMPID");
        	
        	if(StringUtils.isEmpty(smstempid)){
        		throw new BusinessException("9006","无模板ID配置");
        	}
        	
        	tmplogmap.put("mqsmsconf", mqsmsconf);
        	
        	//获取调短信接口的模板参数
        	HashMap<String, String> invokeparams = this.getInvokeparams(mqsmsconf, bodyparams,tmplogmap);
        	
        	tmplogmap.put("invokeparams", JsonUtil.objectToJson(invokeparams));
        	//调接口参数不为空
        	if(invokeparams != null && invokeparams.size()>0){
        		String smswgname = (String)mqsmsconf.get("SMSWGNAME"); //发送短信网关名称
        		if(StringUtils.isEmpty(smswgname)){
        			smswgname =  "sms117";
        		}
        		//调接口发送短信
        		tmplogmap.put("smstype", smswgname);
        		String sendres = sendSMS(userid,smstempid,JsonUtil.objectToJson(invokeparams),smswgname,tmplogmap);
        		tmplogmap.put("sendsmsres", sendres);	
        	}
        	resultcode = "0";
        	errorinfo = "ok";
		} catch (Exception e) {
			if (e instanceof BusinessException) {
				resultcode = ((BusinessException) e).getCode();
				errorinfo = ((BusinessException) e).getMessage();
			}else{
				e.printStackTrace();
				resultcode = "8000";
				errorinfo = e.getMessage();
			}
		} finally {
			tmplogmap.put("resultcode", resultcode);
			tmplogmap.put("errorinfo", errorinfo);
			mainlogmap.put("sendSecSms", tmplogmap);
		}
    }
    
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
