package com.iamberry.wechat.service.order;

import static com.iamberry.wechat.service.ImberryConfig.INTER_SMS_KEY;
//import static com.iamberry.wechat.service.ImberryConfig.SMS_PASSWORD;
//import static com.iamberry.wechat.service.ImberryConfig.SMS_TEXT;
//import static com.iamberry.wechat.service.ImberryConfig.SMS_URL;
//import static com.iamberry.wechat.service.ImberryConfig.SMS_USERNAME;
import static com.iamberry.wechat.service.ImberryConfig.INTER_SMS_KEY;
import static com.iamberry.wechat.service.ImberryConfig.INTER_SMS_TEXT;
import static com.iamberry.wechat.service.ImberryConfig.INTER_SMS_URL;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.app.tool.util.Result;
import com.iamberry.wechat.core.entity.order.ProbationCode;
import com.iamberry.wechat.core.entity.probation.ProbationUserInfo;
import com.iamberry.wechat.face.order.CodeService;
import com.iamberry.wechat.face.order.ProbationShopOrderService;
import com.iamberry.wechat.service.ImberryConfig;
import com.iamberry.wechat.tools.ResponseJson;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

/**
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年11月1日
 * @explain	验证码业务实现类
 */
@SuppressWarnings("unused")
@Service
public class CodeServiceImpl implements CodeService {

	/*@Autowired
	private CodeMapper codeMapper;*/
	@Autowired
	private ProbationShopOrderService probationShopOrderService;
	@Autowired
	private RatFWLogger logger;
	private static String ENCODING = "UTF-8";
	private static Random rnd = new Random();
	
	@Override
	public ResponseJson sendCode(String phone) {
		// TODO Auto-generated method stub
		ResponseJson json = new ResponseJson();
		if (StringUtils.isEmpty(phone)) {
			json.setReturnCode(2);
			json.addResponseKeyValue("Phone Empty!");
			return json;
		}
		//判断是否已经存在申请记录
		ProbationUserInfo probationUserInfo	= probationShopOrderService.selectProbationOrderByTel(phone);
		if(probationUserInfo != null){
			json.setReturnCode(1);
			json.addResponseKeyValue("Phone Existing !");
			return json;
		}
		ProbationCode probationCode = 	probationShopOrderService.selectProbationCodeByTel(phone);
		if(probationCode != null){
			if(probationCode.getPuserDate().getTime() < new Date().getTime()+ 60000 
					&& probationCode.getPuserDate().getTime() > new Date().getTime() - 60000){
				json.setReturnCode(3);
				json.addResponseKeyValue("60秒内只能申请一次验证码");
				return json;
			}
		}
		
		// 获取验证码
		String code = getRandomCode(4);
		json = sendCMS(phone, code);
		if (json.getReturnCode() != 200) {
			json = sendCMS(phone, code);
		}
		//添加验证码到数据库
		ProbationCode codeBean = new ProbationCode();
		codeBean.setPuserTel(phone);
		codeBean.setPuserCode(Integer.valueOf(code));
		codeBean.setPuserDate(new Date());
		if(probationCode == null){
			probationShopOrderService.insertProbationCode(codeBean);
		}else{
			probationShopOrderService.updatePauseCode(codeBean);
		}
  		return json;
	}
	
	public ResponseJson sms(String phone) {

		// TODO Auto-generated method stub
		ResponseJson json = new ResponseJson();
		if (StringUtils.isEmpty(phone)) {
			json.setReturnCode(2);
			json.addResponseKeyValue("Phone Empty!");
			return json;
		}
		ProbationCode probationCode = 	probationShopOrderService.selectProbationCodeByTel(phone);
		if(probationCode != null){
			if(probationCode.getPuserDate().getTime() < new Date().getTime()+ 60000 
					&& probationCode.getPuserDate().getTime() > new Date().getTime() - 60000){
				json.setReturnCode(3);
				json.addResponseKeyValue("60秒内只能申请一次验证码");
				return json;
			}
		}
		
		// 获取验证码
		String code = getRandomCode(4);
		json = sendCMS(phone, code);
		if (json.getReturnCode() != 200) {
			json = sendCMS(phone, code);
		}
		//添加验证码到数据库
		ProbationCode codeBean = new ProbationCode();
		codeBean.setPuserTel(phone);
		codeBean.setPuserCode(Integer.valueOf(code));
		codeBean.setPuserDate(new Date());
		if(probationCode == null){
			probationShopOrderService.insertProbationCode(codeBean);
		}else{
			probationShopOrderService.updatePauseCode(codeBean);
		}
  		return json;
	}

	@Override
	public boolean sendRentOrderToUser(String phone, Integer duration,
			Integer pledgeMoney, Integer serviceMoney, Integer typeId) {
		// TODO Auto-generated method stub
		String text = "";
		switch (typeId) {
		case 1:
			text = MessageFormat.format(ImberryConfig.INTER_SMS_RENT_TYPE1_TEXT, duration, pledgeMoney, serviceMoney);
			break;
		case 2:
			text = MessageFormat.format(ImberryConfig.INTER_SMS_RENT_TYPE2_TEXT, duration, pledgeMoney, serviceMoney);
			break;
		case 3:
			text = MessageFormat.format(ImberryConfig.INTER_SMS_RENT_TYPE3_TEXT, serviceMoney);
			break;
		default:
			text = MessageFormat.format(ImberryConfig.INTER_SMS_RENT_TYPE1_TEXT, duration, pledgeMoney, serviceMoney);
			break;
		}
		String msg = sendOtherCMS(phone,text);
		if ("SUCCESS".equals(msg)) {
			return true;
		}
		return false;
	}

	/**
	 * 发送短信验证码 封装返回前台参数
	 * @param phone		手机号码
	 * @param code		短信验证码
	 * @return
	 */
	private ResponseJson sendCMS(String phone, String code) {
		ResponseJson json = new ResponseJson();
		json.setReturnCode(500);
		String result = null;
		try {
			String text = MessageFormat.format(INTER_SMS_TEXT, code);
			result = sendOtherCMS(phone, text);
 		} catch (Exception e) {
 			logger.info(CodeServiceImpl.class, e.getMessage());
			result = "验证码发送失败，请稍后重试";
		}
		if (StringUtils.equals(result, "SUCCESS")) {
			json.setReturnCode(200);
		}
		json.addResponseKeyValue(result);
		return json;
	}
	
	/**
	 * 向指定手机发送短信 返回发送结果
	 * @param phone	电话
	 * @param text	短信内容
	 * @return
	 */
	public String sendOtherCMS(String phone, String text) {
		String results = sendSms(text,phone);
		logger.info("向手机：" + phone + ",发送短信：" + text + ",返回结果-->>" + results);
        JSONObject json =  JSONObject.fromObject(results);
        String resultcod  = json.get("code").toString();
        if("0".equals(resultcod)){
        	return "SUCCESS";
        }else{
        	return "验证码发送失败，请稍后重试";
        }
	}
	
	/**
	 * 配置云片相关信息并发送请求
	 * @param text		发送的内容
	 * @param mobile	手机号
	 * @return
	 */
	public static String sendSms(String text, String mobile)  {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", INTER_SMS_KEY);
        params.put("text", text);
        params.put("mobile", mobile);
        return post(INTER_SMS_URL, params);
    }
	
    /** 基于HttpClient 4.3的通用POST方法
     * @param url       提交的URL
     * @param paramsMap 提交<参数，值>Map
     * @return 提交响应
     */
    public static String post(String url, Map<String, String> paramsMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
            try {
                HttpPost method = new HttpPost(url);
                if (paramsMap != null) {
                    List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                    for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                        NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
                        paramList.add(pair);
                    }
                    method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
                }
                response = client.execute(method);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    responseText = EntityUtils.toString(entity);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return responseText;
        }
	
//	/**
//	 * 创火 旧短信接口
//	 * 
//	 * @param phone
//	 * @param code
//	 * @return
//	 * @throws Exception
//	 */
//	private String sendZHCMS(String phone, String code) throws Exception {
//		CloseableHttpClient client = HttpClients.createDefault();
//		Map<String, String> params = new HashMap<String, String>();
//		CloseableHttpResponse response = null;
//		params.put("username", SMS_USERNAME);	//aibeiyuan
//		params.put("password", SMS_PASSWORD);	//aibeiyuan632
//		params.put("mobile", phone);			//phone
//		params.put("content", MessageFormat.format(SMS_TEXT, code));//text
//		HttpPost method = new HttpPost(SMS_URL);//http://115.29.44.189:8080/sms/smsInterface.do
//		if (params != null) {
//			List<NameValuePair> paramList = new ArrayList<NameValuePair>();
//			for (Map.Entry<String, String> param : params.entrySet()) {
//				NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
//				paramList.add(pair);
//			}
//			method.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
//		}
//		response = client.execute(method);
//		HttpEntity entity = response.getEntity();
//		if (entity != null) {
//			String result = EntityUtils.toString(entity);
//			XStream xs = new XStream(new StaxDriver());
//			xs.alias("result", Result.class);
//			Result object = (Result)xs.fromXML(result);
//			response.close();
//			if (0 == object.getResultcode()) {
//				return "SUCCESS";
//			} else {
//				return object.getResultcode() + ":" + object.getErrordescription();
//			}
//		}
//		return null;
//	}

	@Override
	public ResponseJson validCode(String phone, String code) {
		ResponseJson json = new ResponseJson();
		ProbationCode probationCode = probationShopOrderService.selectProbationCodeByTel(phone);
		// 校验
		if (probationCode == null) {
			// 操作有误
			json.setReturnCode(404);
			json.addResponseKeyValue("验证失败");
			return json;
		}
		Date now = new Date();
		if (now.getTime() >= (probationCode.getPuserDate().getTime() + 180000)) {
			// 验证码无效
			json.setReturnCode(404);
			json.addResponseKeyValue("验证码无效");
			return json;
		}
		// 必须 验证码正确，并且场景正确
		if (!(probationCode.getPuserCode() == (Integer.parseInt(code)))) {
			// 验证码错误
			json.setReturnCode(404);
			json.addResponseKeyValue("验证码错误");
			return json;
		}
		// 只要校验，表示本次验证码使用
		json.setReturnCode(200);
		json.addResponseKeyValue("SUCCESS");
		return json;
	}
	
	public static String getRandomCode(int len) {
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++)
			sb.append("0123456789".charAt(rnd.nextInt("0123456789".length())));
		return sb.toString();
	}

	@Override
	public boolean sendTextToUser(String phone,int days) {
		String text = "";
		switch (days) {
		case 6:				//7天内的短信提示
			text = ImberryConfig.PROBATION_SUCCESS_FIRST_TEXT;
			break;
		case 14:			//15天内的短信提示
			text = ImberryConfig.PROBATION_SUCCESS_SECOND_TEXT;
			break;
		case 20:			//21天内的短信提示
			text = ImberryConfig.PROBATION_SUCCESS_THIRD_TEXT;
			break;
		default:
			break;
		}
		//发送短信 
		String result = sendOtherCMS(phone, text);
		if("SUCCESS".equals(result)){
			return true;
		}else{
			return false;
		}
	}
}
