package com.chinacreator.video.restful.service;

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.DictionaryDao;
import com.chinacreator.video.mapper.TenDrawDao;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.validate.BusiValidate;
import org.apache.commons.lang.StringUtils;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 *奇艺20、腾讯20
 * 限时5元领15元话费活动时间服务类
 *
 */
@Component
public class EventDrawService {
	
	@Autowired
	private BusiValidate busiVali;
	
    @Autowired
    private ChannelDao channelDao;
    
    @Autowired
    private TenDrawDao tenDrawDao;
    
	@Autowired
	private DictionaryDao dictionaryDao;
	
	private static Logger logger = Logger.getLogger(EventDrawService.class);
	
	private static Logger log = Logger.getLogger("tendraw");
	
	public void busiCheck(JSONObject inputObj, String invokename) throws Exception{

		paramValidate(inputObj,invokename);
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setChannel(inputObj.getString("channel"));
		orderInfo.setCpid(inputObj.getString("cpid"));
		orderInfo.setSpid(inputObj.getString("spid"));
		orderInfo.setTimestamp(inputObj.getString("timestamp"));
		busiVali.valiIp(orderInfo);
		busiVali.valiTime(orderInfo);
		
		//签名验证
		signValidate(inputObj,invokename);
		if("prizeauth".equals(invokename)){
			//手机号码验证
			String password = channelDao.queryChannel(inputObj.getString("channel")).getPassword();
			String userid = DesUtil.decode(inputObj.getString("userid"), password);
			mobValidate(userid);
		}
	}

	
	private void paramValidate(JSONObject inputObj, String invokename) throws Exception{
       if("prizeauth".equals(invokename)){
    	   if(StringUtils.isEmpty(inputObj.getString("userid")) ||
				   StringUtils.isEmpty(inputObj.getString("cpid"))||
				   StringUtils.isEmpty(inputObj.getString("spid"))||
				   StringUtils.isEmpty(inputObj.getString("signature"))||
				   StringUtils.isEmpty(inputObj.getString("channel"))){
    		   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( StringUtils.isEmpty(inputObj.getString("timestamp"))){
    	   throw new BussinessException("80015", "参数异常，");
       }
	}
	
    /**
     * 签名验证
     * @param
     * @throws Exception
     */
    public void signValidate(JSONObject inputObj, String invokename) throws Exception{
        String lcalsign = getSign(inputObj,invokename);
		String pwd = channelDao.queryChannel(inputObj.getString("channel")).getPassword();
		lcalsign +=pwd;
        lcalsign = MD5.MD5Encode(lcalsign);
        if(!lcalsign.equals(inputObj.getString("signature"))) {
            throw new BussinessException("10006", "签名校验失败");
        }
    }
    
    /**
     * 拼接签名信息 orderid+channel+timestamp
     * @param
     * @return
     */
    public String getSign(JSONObject inputObj, String invokename){
    	StringBuilder strb = new StringBuilder();
        if("prizeauth".equals(invokename)){
        	 strb.append(inputObj.getString("userid"));
			 strb.append(inputObj.getString("channel"));
			 strb.append(inputObj.getString("cpid"));
			 strb.append(inputObj.getString("spid"));
        }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();
    }

	/**
	 *  爱奇艺20、腾讯20
	 * 限时5元领15元话费活动资格
	 * @param inputObj
	 * @return
	 */
    public Map<String, Object> eventStatus(JSONObject inputObj) throws Exception {
		valiEndtime();
		//手机号码验证
		String password = channelDao.queryChannel(inputObj.getString("channel")).getPassword();
		String userid = DesUtil.decode(inputObj.getString("userid"), password);
		String spid = inputObj.getString("spid");
		String cpid = inputObj.getString("cpid");
		//查询该用户是否已经领取
		 List<Map<String,Object>> list=tenDrawDao.findByUser(userid,spid,cpid);
		 if (list!=null && list.size()>0){
			 throw  new BussinessException("9030","已领取");
		 }
		//获取符合资格的名单
		List<Map<String,Object>> eventList=tenDrawDao.findByPhone(userid,spid,cpid);
		if (eventList==null || eventList.size()==0){
			List<Map<String,Object>> orderList=tenDrawDao.findOrderCoode(userid,spid,cpid);
			if (orderList!=null && orderList.size()>0){
				String code = orderList.get(0).get("CODE")+"";
				if ("0".equals(code)){
					throw  new BussinessException("9092","非指定月份订购");
				}else if ("1".equals(code)){
					throw  new BussinessException("9026","已退订");
				}else {
					throw  new BussinessException("9027","订购关系已失效");
				}
			}else{
				throw  new BussinessException("9025","无订购关系");
			}
		}else{
			return eventList.get(0);
		}
	}

	/**
	 * 插入已领取名单
	 * @param map
	 */
	public void insertActivity(Map<String,Object> map){
    	map.put("STATUS",0);
    	tenDrawDao.insertActivity(map);
	}
    /**
     * 判断活动是否已结束
     * @throws Exception
     */
    private void valiEndtime()throws Exception{
    	SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
    	String currtime = dateformat.format(new Date());
    	String tendrawendtime =  dictionaryDao.getValue("aiqy2021starttime");
    	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","手机号码不合法");
        }     	       	    
	}
}
