package com.chinacreator.video.restful.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

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.MD5;
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 20190618
 */
@Component
public class TenDrawService {
	
	@Autowired
	private BusiValidate busiVali;
	
    @Autowired
    private ChannelDao channelDao;
    
    @Autowired
    private TenDrawDao tenDrawDao;
    
	@Autowired
	private DictionaryDao dictionaryDao;
	
	private static Logger logger = Logger.getLogger(TenDrawService.class);
	
	private static Logger log = Logger.getLogger("tendraw");
	
	public void busiCheck(JSONObject inputObj, String invokename) throws Exception{
		
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setChannel("tendraw");
		busiVali.valiIp(orderInfo);
		paramValidate(inputObj,invokename);
		orderInfo.setTimestamp(inputObj.getString("timestamp"));
		busiVali.valiTime(orderInfo);
		
		//签名验证
		signValidate(inputObj,invokename);
		if("prizeauth".equals(invokename) && "0".equals(inputObj.getString("type"))){
			//手机号码验证
			mobValidate(inputObj.getString("account"));
		}else if("prizesend".equals(invokename)){
			//手机号码验证
			mobValidate(inputObj.getString("userid"));
			//valiPrizesend(inputObj);
		}
	}
	
	/**
	 * 验证手机号码与映射ID是否匹配
	 * @param inputObj
	 * @throws Exception
	 */
	private void valiPrizesend(JSONObject inputObj)throws Exception{
		String userid = inputObj.getString("userid"); 
		String mappid = inputObj.getString("mappid");
		String reuserid = tenDrawDao.getUser(mappid);
		if(!userid.equals(reuserid)){
			throw new BussinessException("9021","手机号码与映射ID不匹配");
		}
	}
	
	private void paramValidate(JSONObject inputObj, String invokename) throws Exception{
       if("prizeauth".equals(invokename)){
    	   if(inputObj.getString("account") == null || "".equals(inputObj.getString("account")) 
    			|| inputObj.getString("type") == null || "".equals(inputObj.getString("type")) 
    			||(!"0".equals(inputObj.getString("type")) && !"1".equals(inputObj.getString("type")))){
    		   throw new BussinessException("80015", "参数异常，");
    	   }
       }else if("prizesend".equals(invokename)){
    	   if(inputObj.getString("userid") == null || "".equals(inputObj.getString("userid")) 
    			//|| inputObj.getString("mappid") == null || "".equals(inputObj.getString("mappid")) 
    			|| inputObj.getString("prizetime") == null || "".equals(inputObj.getString("prizetime")) 
    			|| inputObj.getString("prizename") == null || "".equals(inputObj.getString("prizename"))){
    		   throw new BussinessException("80015", "参数异常，");
    	   }
       }else if("prizeqry".equals(invokename)){

       }
       if(inputObj.getString("timestamp") == null || "".equals(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("tendraw").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("prizeauth".equals(invokename)){
        	 strb.append(inputObj.getString("account"));
        	 strb.append(inputObj.getString("type"));
        }else if("prizesend".equals(invokename)){
       	 	strb.append(inputObj.getString("userid"));
	       	strb.append(inputObj.getString("mappid"));
	       	strb.append(inputObj.getString("prizetime"));
	    	strb.append(inputObj.getString("prizename"));
        }else if("prizeqry".equals(invokename)){

        }
        strb.append(inputObj.getString("timestamp"));
        return strb.toString();
    }
    
    /**
     * 接收中奖信息
     * @param inputObj
     * @throws Exception
     */
    public void prizesend(JSONObject inputObj)throws Exception{
    	HashMap<String, String> prize = new HashMap<String, String>();
    	prize.put("USERID",inputObj.getString("userid"));
    	prize.put("MAPPID",inputObj.getString("mappid")); 
		prize.put("PRIZETIME",inputObj.getString("prizetime")); 
		prize.put("PRIZENAME",inputObj.getString("prizename"));
    	tenDrawDao.addPrize(prize);
    }
    
    /**
     * 查询中奖信息，用于页面中奖信息轮换
     * @param inputObj
     * @return
     * @throws Exception
     */
    public List<HashMap> prizeQry(JSONObject inputObj) throws Exception{
    	List<HashMap> prizeList = tenDrawDao.getPrizeList();
    	return prizeList;
    }
    
    /**
     * 
     * @param inputObj
     * @throws Exception
     */
    public String prizeauth(JSONObject inputObj)throws Exception{
    	this.valiEndtime();
    	String res = ""; //type为0时，返回映射ID，type为1时返回手机号码
    	String type = inputObj.getString("type");
    	String account = inputObj.getString("account");
		List<HashMap> orderList = null;
		//0：通过手机号码查询，1：通过映射ID查询
		if("0".equals(type)){
			orderList = tenDrawDao.getOrderRel(account);
		}else{
			String userid = tenDrawDao.getUseridById(account);
			if(userid == null || userid.length() != 11){
				throw new BussinessException("9024","映射ID错误或者已失效");
			}
			orderList = tenDrawDao.getOrderRel(userid);
		}
		if(orderList != null && orderList.size()>0 ){ //当前是订购状态
			HashMap orderMap = orderList.get(0);
			String status = orderMap.get("STATUS").toString();
			if("0".equals(status)){//是订购
				//验证订购月份是否指定范围内
				//20201104，取消订购月份判断
				//valiOrdertime(orderMap.get("ORDERTIME").toString());
		    	if("0".equals(inputObj.getString("type"))){ //通过手机号码查询(H5页面调用)
		    		String mappid = tenDrawDao.getNo();
		    		tenDrawDao.addUserMapp(mappid, account);
		    		res = mappid;
		    	}else{//通过映射ID查询  	
		    		res = orderMap.get("USERID").toString();
		    	}
			}else if("1".equals(status)){ //已退订
				 throw new BussinessException("9026", "已退订");
			}else{//已失效
				 throw new BussinessException("9027", "订购关系已失效");
			}
		}else{
			 throw new BussinessException("9025","无订购关系");
		}
		
		return res;
    }
    
    /**
     * 判断活动是否已结束
     * @throws Exception
     */
    private void valiEndtime()throws Exception{
    	SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
    	String currtime = dateformat.format(new Date());
    	String tendrawendtime =  dictionaryDao.getValue("tendrawendtime");
    	if(Long.parseLong(currtime) > Long.parseLong(tendrawendtime)){
    		 throw new BussinessException("9028","活动已经结束");
    	}
    }
    
    /**
     * 验证订购时间是否合法
     * @param ordertime
     * @return true订购日期在指定的月份，反之，不在
     */
    private void valiOrdertime(String ordertime)throws Exception{
		String ordermonth = ordertime.substring(0,6);
		String tendrawmonths = dictionaryDao.getValue("tendrawmonths");
		if(!tendrawmonths.contains(ordermonth)){
			 throw new BussinessException("9029","非指定月份订购");
		}
    }
	
    /**
     * 手机号码验证
     * @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","手机号码不合法");
        }     	       	    
	}
}
