package org.cs.mgr.user.service.impl;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.cs.core.service.impl.BaseService;
import org.cs.mgr.user.dao.IMgmUserDao;
import org.cs.mgr.user.dao.ISmsDao;
import org.cs.mgr.user.model.MgmUser;
import org.cs.mgr.user.model.SMS;
import org.cs.mgr.user.service.ISmsService;
 
 
import org.cs.util.RandomUtil;
import org.cs.util.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

@Service("smsService")
public class SmsService extends BaseService<SMS> implements ISmsService {
	private Logger log = Logger.getLogger(SmsService.class);

	@Autowired 
	private ISmsDao smsDao;
   
	@Autowired 
	private IMgmUserDao mgmUserDao;
   
	@Override
	@Transactional(readOnly=false)
	public JSONObject getCode(Map<String, String> map) {
		int type = Integer.parseInt(map.get("type"));  //1.注册  2.5.忘记密码
		String phone = map.get("phone");
		
		int countByDay = smsDao.countByDay(phone);
		if(countByDay>5){
			return getJson(0, "", "您今天获取的验证码太多了，请明天再试。");
		}
		
		JSONObject json = new JSONObject();
		
		String code = RandomUtil.generateNum(6);
		
    	if (type==1) {//注册,check is unique
    		MgmUser user = mgmUserDao.getByPropertie(phone,"phone");
    		if (null != user) {
    			return getJson(0, "","该手机号已被注册");
    		}
    	} else if (type==2||type==5) {//忘记密码
    		
    		MgmUser appUser = mgmUserDao.getByPropertie(phone,"phone");
    		if(appUser==null){
    			return getJson(0, "","手机号不存在");
    		}
    	}else if(type==3){
    		MgmUser user = mgmUserDao.getByPropertie(phone,"phone");
    		if (null != user) {
    			return getJson(0, "","该手机号已被绑定");
    		}
    	}
    	
    	int sendCode = SmsUtil.sendCode(phone,code,type);
		if(sendCode!=1){
			log.info("验证码获取失败,失败码:"+sendCode+"。发送目标"+phone);
			json = getJson(0 ,"","验证码获取失败");
    	}
    	 
    	SMS sms = new SMS();
		sms.setCode(code);
		sms.setPhone(phone);
        sms.setValidTime(60*1000*5);
        sms.setType(type);
        add(sms);
        
        
        
        
        json = getJson(1,"","");
        
		
    	
    	return json;
	}

	@Override
	public JSONObject checkCode(String phone,int type,String code) {
		
		JSONObject json = new JSONObject();
		
		SMS sms = smsDao.getSMSByPhone(phone,code.toLowerCase() , type);
    	
    	if (sms==null || !code.toLowerCase().equals(sms.getCode().toLowerCase())) {
    		json = getJson(0, "","验证码错误");
    	} else {
    		long nowTime = System.currentTimeMillis();
    		if ((sms.getCreateDate().getTime() + sms.getValidTime()) < nowTime) {
    			json = getJson(0, "","验证码超时，请重新获取");
    		} else {
    			json = getJson(1, "","");
    		}
    	}
		return json;
	}

	
	
}
