package com.chinacreator.video.restful.service;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSON;
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.TenDrawDao;
import com.chinacreator.video.restful.bean.OrderLog;
import com.chinacreator.video.restful.util.RequestUtil;
import com.chinacreator.video.service.CommonService;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.OtherProperties;
import com.chinacreator.video.util.RedisService;
import com.chinacreator.video.util.URLUtil;
import com.chinacreator.video.validate.BusiValidate;
import com.chinacreator.video.validate.ChannelValidate;
import com.chinacreator.video.validate.IpValidate;
import com.chinacreator.video.validate.MobValidate;
import com.chinacreator.video.validate.ParamValidate;
import com.chinacreator.video.validate.SignValidate;
import com.chinacreator.video.validate.TimetampValidate;

/**
 * 手机号码映射
 * @author xu.zhou
 * @date 20200722
 */
@Component
public class ShortAddrService {
	
	@Autowired
	private BusiValidate busiVali;
	
    @Autowired
    private ChannelDao channelDao;
    
	@Autowired
	CommonService commonService;
	
    @Autowired
    private DictionaryDao dictionaryDao;
	
	private static Logger log = Logger.getLogger("tendraw");
	
	public void busiCheck(JSONObject inputObj, String invokename) throws Exception{
		
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setInvokeface("shortaddr");
		orderInfo.setCpid("shortaddr");//预设CPID用于权限验证
		orderInfo.setChannel(inputObj.getString("channel"));
		busiVali.valiIp(orderInfo);
		paramValidate(inputObj,invokename);
		orderInfo.setTimestamp(inputObj.getString("timestamp"));
		busiVali.valiTime(orderInfo);
		
		//签名验证
		signValidate(inputObj,invokename);
		//并发控制
		vistVali(inputObj, invokename);
	}
	
    /**
     * 并发控制，一分钟内不允许重复请求
     * @param inputObj
     * @param invokename
     * @throws Exception
     */
	private void vistVali(JSONObject inputObj, String invokename) throws Exception{
		String [] params = new String [2];
		params[0] = inputObj.getString("channel");
		params[1] = invokename;
		if(commonService.vistVali2(params, invokename)){
			throw new BussinessException("8001", "指定时间内重复请求");
		}
	}
	
	/**
	 * 参数验证
	 * @param inputObj
	 * @param invokename
	 * @throws Exception
	 */
	private void paramValidate(JSONObject inputObj, String invokename) throws Exception{
		   //是否覆盖，值为true/false
		   String cover = inputObj.getString("cover");
		   //短地址编码
		   String shortcode = inputObj.getString("shortcode");
		   String channel = inputObj.getString("channel");
		   if(StringUtils.isEmpty(inputObj.getString("longurl"))
				|| StringUtils.isEmpty(channel) 
				||StringUtils.isEmpty(inputObj.getString("timestamp"))){
			   throw new BussinessException("80015", "参数异常");
		   }
	
		   if(!StringUtils.isEmpty(shortcode)){
			   String regex = "[0-9a-zA-Z]{4,8}"; //短号地址编码只能是6至10位的数字大小写字母
			   if(!shortcode.matches(regex)){
				   throw new BussinessException("80015", "参数异常，shortcode");
			   }
		   }
		   if(!StringUtils.isEmpty(cover) && !"0".equals(cover) && !"1".equals(cover)){
			   throw new BussinessException("80015", "参数异常，cover");
		   }
		   //是否覆盖为0，但短地址编码为空，
		   if("0".equals(cover) && StringUtils.isEmpty(shortcode)){
			   throw new BussinessException("80015", "参数异常，");
		   } 
		   
		   //设置覆盖
		   if("0".equals(cover)){
			   //默认所有渠道无覆盖功能
			   boolean haspass = false;
			   //获取有权限使用覆盖的渠道，多个渠道用|分隔
			   String converchannel = dictionaryDao.getValue("shortcoverchannel");
			   if(!StringUtils.isEmpty(converchannel)){
				   String [] arraytmp = converchannel.split("\\|");				 
				   for(String str : arraytmp){
					   if(channel.equals(str)){
						   haspass = true;
						   break;
					   }
				   }
			   }
			   
			   if(!haspass){
				   throw new BussinessException("10011", "无权限使用覆盖功能");
			   }
		   }
	}
	
    /**
     * 签名验证
     * @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", "签名校验失败");
        }
    }
    
    /**
     * 拼接签名信息 account+channel+timestamp
     * @param orderInfo
     * @return
     */
    public String getSign(JSONObject inputObj, String invokename){
    	StringBuilder strb = new StringBuilder();
        strb.append(inputObj.getString("longurl"));
        strb.append(inputObj.getString("channel"));
        strb.append(inputObj.getString("timestamp"));
        return strb.toString();
    }
    
    public String process(JSONObject inputObj) throws Exception{
    	String shorturl = dictionaryDao.getValue("shorturl");
    	String params = getParams(inputObj);
    	log.info("调接口地址及请求参数："+shorturl+"&"+params);
    	String res = URLUtil.get(shorturl+"?"+params,0);
    	log.info("调接口响应报文："+res);
    	return res;
    }
    
    /**
     * 拼接调接口参数
     * @param inputObj
     * @return
     * @throws Exception
     */
    private String getParams(JSONObject inputObj) throws Exception{
    	String params = "";
    	String url = inputObj.getString("longurl");
    	String shortCode = inputObj.getString("shortcode");
    	String cover = inputObj.getString("cover");
    	if(StringUtils.isEmpty(cover)){
    		cover = "false";
    	}else{
    		//cover值转换
    		cover = "0".equals(cover) ? "true" : "false";
    	}
    	if(!StringUtils.isEmpty(shortCode)){
    		params = "url="+URLEncoder.encode(url, "UTF-8")+"&shortCode="+shortCode+"&cover="+cover;
    	}else{
    		params = "url="+URLEncoder.encode(url, "UTF-8")+"&cover="+cover;
    	}
    	
    	return params;
    }
}
