package com.chinacreator.video.restful.service;

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.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 MappUserService {
	
	@Autowired
	private BusiValidate busiVali;
	
    @Autowired
    private ChannelDao channelDao;
    
	@Autowired
	RedisService redisService;
	
    @Autowired
    private OtherProperties otherProperties;
	
	private static Logger log = Logger.getLogger("tendraw");
	
	public void busiCheck(JSONObject inputObj, String invokename) throws Exception{
		
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setCpid("mappuser");//预设CPID用于权限验证
		orderInfo.setChannel(inputObj.getString("channel"));
		orderInfo.setInvokeface(invokename);
		busiVali.valiIp(orderInfo);
		paramValidate(inputObj,invokename);
		orderInfo.setTimestamp(inputObj.getString("timestamp"));
		busiVali.valiTime(orderInfo);
		
		//签名验证
		signValidate(inputObj,invokename);
	}
	
	/**
	 * 参数验证
	 * @param inputObj
	 * @param invokename
	 * @throws Exception
	 */
	private void paramValidate(JSONObject inputObj, String invokename) throws Exception{
	   if(StringUtils.isEmpty(inputObj.getString("account"))
			|| StringUtils.isEmpty(inputObj.getString("channel")) 
			||StringUtils.isEmpty(inputObj.getString("timestamp"))){
		   throw new BussinessException("80015", "参数异常，");
	   }
	    //解密手机号码
		if("qrymappid".equals(invokename)){
			String password = channelDao.queryChannel(inputObj.getString("channel")).getPassword();
			String account = DesUtil.decode(inputObj.getString("account"), password);
			//手机号码验证
			mobValidate(account);
			inputObj.put("userid", account);
		}
	}
	
    /**
     * 签名验证
     * @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("account"));
        strb.append(inputObj.getString("channel"));
        strb.append(inputObj.getString("timestamp"));
        return strb.toString();
    }
    
    /**
     * 根据手机号码获取映射ID
     * @param inputObj
     * @throws Exception
     */
    public void qrymappid(JSONObject inputObj)throws Exception{
    	String userid = inputObj.getString("userid");
    	String pex = "usermapp_";
    	String mappid = UUID.randomUUID().toString().replaceAll("-", "");
		long expireTime = 300;
		try{
		    //访问过期 时间，单位秒
		    expireTime = Long.parseLong(otherProperties.getEnv().getProperty("usermapp_expireTime"));
		}catch(Exception e){
		    expireTime = 300;
		}
		redisService.set(pex+mappid, userid, expireTime);
		if(!userid.equals(redisService.get(pex+mappid))){
			throw new BussinessException("9021", "缓存异常，设置失败");
		}
		inputObj.put("mappid", mappid);
		inputObj.put("userid", inputObj.getString("account"));
    }
    
    /**
     * 根据映射ID获取手机号码
     * @param inputObj
     * @throws Exception
     */
    public void qryuserid(JSONObject inputObj)throws Exception{
    	String pex = "usermapp_";
    	String userid = (String)redisService.get(pex+inputObj.getString("account"));
    	//判断是否取到了手机号码
		if(userid != null && userid.length() == 11){
			userid = DesUtil.encode(userid, channelDao.queryChannel(inputObj.getString("channel")).getPassword());
			inputObj.put("userid", userid);
			inputObj.put("mappid", inputObj.getString("account"));
		}else{
			throw new BussinessException("9024", "映射ID已失效");
		}
    }
	
    /**
     * 手机号码验证
     * @param usermob
     * @throws Exception
     */
	private void mobValidate(String usermob)throws Exception{
		boolean res = false;
        if (usermob != null && usermob.length() == 11) {
        	usermob = usermob.replaceAll("[\\s-]", "");
        	res =  usermob.matches(".*(1\\d{10}).*");
        }
        if(res == false){
        	throw new BussinessException("9022","手机号码不合法");
        }     	       	    
	}
}
