package com.palmnest.service.estateserve.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.PushCustomMessageVo;
import com.palmnest.application.dto.SendSmsParam;
import com.palmnest.application.dto.UserInfoVo;
import com.palmnest.application.dto.WechatMessageDto;
import com.palmnest.application.dto.WxMessageConfigParam;
import com.palmnest.application.dto.WxMessageConfigVo;
import com.palmnest.application.dto.input.SMSSearchDto;
import com.palmnest.dao.notice.MobileConfigDao;
import com.palmnest.model.User;
import com.palmnest.model.notice.MobileConfigModel;
import com.palmnest.model.notice.PhoneMessageModel;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.palmnest.dao.estateserve.SmsAuthCodeDao;
import com.palmnest.model.estateserve.SmsAuthCode;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.impl.GenericManagerImpl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

@Service("smsAuthCodeManagerImpl")
public class SmsAuthCodeManagerImpl extends
		GenericManagerImpl<SmsAuthCode, Integer> implements SmsAuthCodeManager {

	private Logger LOG = Logger.getLogger(SmsAuthCodeManagerImpl.class);

	private String smsServer    = PropertiesKit.readPropertiesValue("sms_server", "wechat.properties");
	private String smsSunServer = PropertiesKit.readPropertiesValue("smsSunMei_server", "wechat.properties");
	private String password     = PropertiesKit.readPropertiesValue("smsSunMei_password", "wechat.properties");
	private String username     = PropertiesKit.readPropertiesValue("smsSunMei_username", "wechat.properties");
	
	private String newMessageUrl     = PropertiesKit.readPropertiesValue("newMessageUrl", "wechat.properties");
	
	private String newSmsMessageUrl     = PropertiesKit.readPropertiesValue("newSmsMessageUrl", "wechat.properties");
	
	private String wxMessageConfigUrl     = PropertiesKit.readPropertiesValue("wxMessageConfigUrl", "wechat.properties");

	private final String DEFAULT_CHARSET = "UTF-8";

	private SmsAuthCodeDao smsAuthCodeDao;

	@Autowired
	public void setSmsAuthCodeDao(SmsAuthCodeDao smsAuthCodeDao) {
		this.smsAuthCodeDao = smsAuthCodeDao;
		this.dao = smsAuthCodeDao;
	}

	@Autowired
	private MobileConfigDao mobileConfigDao;

	@Override
	public String sendSms(String userMobile, String content) {
//		StringBuffer params=new StringBuffer();
//		params.append("phones="+userMobile);
//		params.append("&content="+content);
//		params.append("&smstype=1");
//		params.append("&APPID=e7e0e8b007f2fa5e8de4afccfefc649703d67d4568eab5839b86b3d58163d472");// SHA256
//		LOG.info("sms send params===:"+params.toString());
//		String result=HttpKit.Post(params.toString(),smsServer);
//		LOG.info("sms send result===:"+result);
		return smsSend(userMobile, content);
	}

	@Override
	public SmsAuthCode getSmsAuthCode(String userMobile, String code,
									  String type, int minute) {
		return smsAuthCodeDao.getSmsAuthCode(userMobile, code, type, minute);
	}

	/**
	 * 发送短信方法
	 *
	 * @param userMobile
	 * @param content
	 * @return
	 */
	@Override
	public String smsSend(String userMobile, String content) {
		String result = "Fail";
		try {
			smsAuthCodeDao.updateSmsAuthCode(userMobile);
			String data = MD5.sign(password, "", DEFAULT_CHARSET);
			String postSend = MD5.sign(username, data, DEFAULT_CHARSET);
			StringBuffer params = new StringBuffer();
			params.append("username=" + username);
			params.append("&password=" + postSend);
			params.append("&mobile=" + userMobile);
			//content=content+"【尚美集团】";
			params.append("&content=" + content);
			LOG.info("sms send params===:" + params.toString());
			String res = HttpKit.Post(params.toString(), smsSunServer);
			if (StringUtils.isNotEmpty(res)) {
				result = "Sucess";
			}
			LOG.info("sms send result===:" + result);
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
		return result;
	}

	@Override
	public String smsSend(String account, String pwd, String content, String phones) {

		String result = "Fail";
		try {
			content = URLEncoder.encode(content, "UTF-8");
			String urlString = "http://sms-cly.cn/smsSend.do";
			String paramString = "username=" + account + "&password=" + pwd + "&content=" + content + "&mobile=" + phones;
			LOG.info("sms send params===:" + paramString);
			String res = HttpKit.Post(paramString, urlString);
			if (StringUtils.isNotEmpty(res)) {
				result = "Success";
			}
			LOG.info("sms send resultCode===:" + res + "; result===:" + result);

		} catch (Exception e) {
			LOG.error(e.getMessage());
		}

		return result;
	}

	/**
	 * 短信发送(旧接口)
	 *
	 * @param orgId
	 * @param content
	 * @param phones
	 * @param code
	 * @param smsType
	 * @return
	 */
//	@Override
//	public String smsSendByOrgIdOld(String orgId, String content, String phones,String code,Integer smsType) {
//		String result = "Fail";
//
//		String account = "";//短信平台账号
//		String pwd = "";//短信平台密码
//		try {
//
//			// 校验同一手机号一分钟只能发一次验证码
//			SmsAuthCode authCode = smsAuthCodeDao.getSmsAuthCode(phones, null, "1", 1);
//			if (authCode != null){
//				LOG.info("========= 发送验证码频繁,超过一分钟一次 =========");
//				return result;
//			}
//
//			if (StringUtils.isNotBlank(code)){
//				// 如果短信验证码不为空说明是验证码短信,则将此手机号上个验证码置为失效状态
//				smsAuthCodeDao.updateSmsAuthCode(phones);
//			}
//
//			List<MobileConfigModel> list = mobileConfigDao.getMobileConfigList(orgId+"");
//			if (null != list && list.size()>0){
//				//获取当前项目配置的短信账号信息 (一般情况一个项目只配置一个账号  如果有多个则取第一个)
//				MobileConfigModel model = list.get(0);
//				account = model.getMobileNum();
//				String password_platform = model.getPassword();
//				//密码加密
//				String md5temp = MD5.sign(password_platform, "", "utf-8");
//				pwd = MD5.sign(account + md5temp, "", "utf-8");
//
//				content = URLEncoder.encode(content, "UTF-8");
//				String urlString = "http://sms-cly.cn/smsSend.do";
//				String paramString = "username=" + account + "&password=" + pwd + "&content=" + content + "&mobile=" + phones;
//				LOG.info("sms send params===:"+paramString);
//				String res=HttpKit.Post(paramString,urlString);
//				//短信发送成功后,数据库保存短信验证码相关记录
//				if(StringUtils.isNotEmpty(res)&&StringUtil.isNotEmpty(phones)){
//					String [] mobileArr=phones.split(",");
//					//存在多个手机号码的时候
//					if(mobileArr!=null&&mobileArr.length>0){
//						for(int i=0;i<mobileArr.length;i++){
//							SmsAuthCode smsAuthCode=new SmsAuthCode();
//							if (StringUtils.isNotEmpty(code)){
//								smsAuthCode.setCode(code);
//							}
//							smsAuthCode.setOrgId(Integer.parseInt(orgId));
//							smsAuthCode.setContent(URLDecoder.decode(content, "UTF-8"));
//							smsAuthCode.setUserMobile(mobileArr[i]);
//							smsAuthCode.setType(smsType+"");
//							smsAuthCode.setCreateTime(new Date());
//							smsAuthCode.setIsEnabled(ElementConstant.YESORNO_1);
//							saveModel(smsAuthCode);
//						}
//						result="Success";
//					}
//				}
//				LOG.info("sms send resultCode===:"+res+"; result===:"+result);
//			}else{
//				result="3";//该项目下未配置短信账号，请联系管理员.
//				LOG.info("sms send result===:"+result + "=====:该项目下未配置短信账号，请联系管理员.");
//			}
//		}catch (Exception e){
//			LOG.error("SmsAuthCodeManagerImpl smsSendByOrgId ========> " + e.getMessage());
//		}
//		return result;
//	}
	@Override
	public String smsSendByOrgId(String orgId, String content, String phones, String code, Integer smsType) {
		String result = "Fail";
		
		if(StringUtils.isNotEmpty(newMessageUrl)){
			result=pushNewMessage(orgId,content,phones,code,smsType,newMessageUrl);
			return result;
		}else{
			try {

				// 校验同一手机号一分钟只能发一次验证码
				SmsAuthCode authCode = smsAuthCodeDao.getSmsAuthCode(phones, null, "1", 1);
				if (authCode != null) {
					LOG.info("========= 发送验证码频繁,超过一分钟一次 =========");
					return result;
				}

				if (StringUtils.isNotBlank(code)) {
					// 如果短信验证码不为空说明是验证码短信,则将此手机号上个验证码置为失效状态
					smsAuthCodeDao.updateSmsAuthCode(phones);
				}

				List<MobileConfigModel> list = mobileConfigDao.getMobileConfigList(orgId + "");
				if (null != list && list.size() > 0) {
					//获取当前项目配置的短信账号信息 (一般情况一个项目只配置一个账号  如果有多个则取第一个)
					MobileConfigModel model = list.get(0);
					String account = model.getMobileNum();
					//密码加密
					String pwd = MD5.sign(model.getPassword(), "", "utf-8");

					String msg = Base64.getUrlEncoder().encodeToString(content.getBytes("utf-8"));
					String urlString = "http://api.shgmnets.com/sms/send";
					String paramString = "user=" + account + "&pwd=" + pwd + "&msg=" + msg + "&mobile=" + phones;
					LOG.info("sms send params===:" + paramString);
					String res = HttpKit.Post(paramString, urlString);
					LOG.info("========TEST MSG result:\n{" + res + "}");
					//短信发送成功后,数据库保存短信验证码相关记录
					if (StringUtils.isNotBlank(res) && res.split(",")[1].equals("0")) {
						result = "Success";
						String[] mobileArr = phones.split(",");
						//存在多个手机号码的时候
						if (mobileArr != null && mobileArr.length > 0) {
							for (int i = 0; i < mobileArr.length; i++) {
								SmsAuthCode smsAuthCode = new SmsAuthCode();
								if (StringUtils.isNotEmpty(code)) {
									smsAuthCode.setCode(code);
								}
								smsAuthCode.setOrgId(Integer.parseInt(orgId));
								smsAuthCode.setContent(URLDecoder.decode(content, "UTF-8"));
								smsAuthCode.setUserMobile(mobileArr[i]);
								smsAuthCode.setType(smsType + "");
								smsAuthCode.setCreateTime(new Date());
								smsAuthCode.setIsEnabled(ElementConstant.YESORNO_1);
								saveModel(smsAuthCode);
							}
						}
					}
					LOG.info("sms send resultCode===:" + res + "; result===:" + result);
				} else {
					result = "3";//该项目下未配置短信账号，请联系管理员.
					LOG.info("sms send result===:" + result + "=====:该项目下未配置短信账号，请联系管理员.");
				}
			} catch (Exception e) {
				LOG.error("SmsAuthCodeManagerImpl smsSendByOrgId ========> " + e.getMessage());
			}
		}
		return result;
	}
	
	
	/**
	 * 新版本的推送
	 * @param id
	 * @param code
	 * @param url
	 * @param users
	 * @param title
	 * @param content
	 */
	public String pushNewMessage(String orgId, String content, String phones, String code, Integer smsType,String newMessageUrl){
		SendSmsParam sendParam=new SendSmsParam();
		sendParam.setCode(code);
		sendParam.setContent(content);
		sendParam.setOrgId(Integer.parseInt(orgId));
		sendParam.setSmsType(smsType);
		sendParam.setPhones(phones);
		String params=JSONArray.toJSONString(sendParam);
		try {
			LOG.info("======>短信推送-pushNewMessage-params:"+params);
			String result=HttpKit.HttpClientPost(params,newMessageUrl);
			LOG.info("======>短信推送-pushNewMessage-推送结果:"+result);
			if(StringUtils.isNotEmpty(result)){
				JSONObject jsStr = JSONObject.fromObject(result);
				if(null == jsStr || !jsStr.containsKey("code") || null == jsStr.get("code") || StringUtils.isEmpty(jsStr.get("code").toString())){
					return "发送失败，接口返回异常";
				}
				if(200 != Integer.parseInt(jsStr.get("code").toString())){
					return jsStr.getString("msg");
				}
				return "Success";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "发送失败,"+e.getMessage();
		}
		return "发送失败";
	}


	@Override
	public String Phonemsg(String orgId, String content, String phones) {

		String result = "Fail";
		try {
			List<MobileConfigModel> list = mobileConfigDao.getMobileConfigList(orgId);
			if (null != list && list.size() > 0) {
				//获取当前项目配置的短信账号信息 (一般情况一个项目只配置一个账号  如果有多个则取第一个)
				MobileConfigModel model = list.get(0);
				String account = model.getMobileNum();
				String password_platform = model.getPassword();
				//密码加密
				String md5temp = MD5.sign(password_platform, "", "utf-8");
				String pwd = MD5.sign(account + md5temp, "", "utf-8");

				content = URLEncoder.encode(content, "UTF-8");

				String urlString = "http://sms-cly.cn/smsSend.do";
				String paramString = "username=" + account + "&password=" + pwd + "&content=" + content + "&mobile=" + phones;
				LOG.info("sms send params===:" + paramString);
				String res = HttpKit.Post(paramString, urlString);
				result = "Success";
			} else {
				result = "3";//该项目下未配置短信账号，请联系管理员.
				LOG.info("sms send result===:" + result + "=====:该项目下未配置短信账号，请联系管理员.");
			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			LOG.info(e.getMessage());
		}
		return result;
	}

	@Override
	public Page findList(SMSSearchDto dto) {
		return smsAuthCodeDao.findList(dto);
	}

	@Override
	public String smsSendByOrgId(WechatMessageDto dto) {
		if(null == dto || null == dto.getOrgId() || null == dto.getSmsType() || StringUtils.isEmpty(dto.getBusinessCode()) || StringUtils.isEmpty(dto.getMobils()) || StringUtils.isEmpty(dto.getType()) || null == dto.getParamMap()){
			return "参数为空";
		}
		if(StringUtils.isEmpty(newSmsMessageUrl)){
			return "短信推送地址为空，无法发送";
		}
		LOG.info("======>短信推送-smsSendByOrgId-newSmsMessageUrl:"+newSmsMessageUrl);
		String params=com.alibaba.fastjson.JSONObject.toJSONString(dto);
		LOG.info("======>短信推送-smsSendByOrgId-params:"+params);
		String result=HttpKit.HttpClientPost(params,newSmsMessageUrl);
		LOG.info("======>短信推送-smsSendByOrgId-result:"+result);
		if(StringUtils.isNotEmpty(result)){
			JSONObject jsStr = JSONObject.fromObject(result);
			if(null == jsStr || !jsStr.containsKey("code") || null == jsStr.get("code") || StringUtils.isEmpty(jsStr.get("code").toString())){
				return "发送失败，接口返回异常";
			}
			if(200 != Integer.parseInt(jsStr.get("code").toString())){
				return jsStr.getString("msg");
			}
			return "";
		}
		return "发送失败";
	}

	@Override
	public WxMessageConfigVo getWxMessageConfig(Integer orgId,
			String businessCode) {
		if(null == orgId ||  StringUtils.isEmpty(businessCode)){
			LOG.info("获取配置信息失败:请求参数异常");
			return null;
		}
		if(StringUtils.isEmpty(wxMessageConfigUrl)){
			LOG.info("获取配置信息失败:获取地址为空");
			return null;
		}
		WxMessageConfigParam dto=new WxMessageConfigParam();
		dto.setOrgId(orgId);
		dto.setBusinessCode(businessCode);
		LOG.info("======>获取配置信息-getWxMessageConfig-wxMessageConfigUrl:"+wxMessageConfigUrl);
		String params=com.alibaba.fastjson.JSONObject.toJSONString(dto);
		LOG.info("======>获取配置信息-getWxMessageConfig-params:"+params);
		String result=HttpKit.HttpClientPost(params,wxMessageConfigUrl);
		LOG.info("======>获取配置信息-getWxMessageConfig-result:"+result);
		if(StringUtils.isNotEmpty(result)){
			JSONObject jsStr = JSONObject.fromObject(result);
			if(null == jsStr || !jsStr.containsKey("code") || null == jsStr.get("code") || StringUtils.isEmpty(jsStr.get("code").toString())){
				LOG.info("获取配置信息失败:返回值异常");
				return null;
			}
			if(200 != Integer.parseInt(jsStr.get("code").toString())){
				LOG.info("获取配置信息失败:"+jsStr.getString("msg"));
				return null;
			}
			if(!jsStr.containsKey("data") || null == jsStr.get("data") || StringUtils.isEmpty(jsStr.get("data").toString())){
				LOG.info("获取配置信息失败:返回对象为空");
				return null;
			}
			WxMessageConfigVo vo=JSON.parseObject(jsStr.get("data").toString(), WxMessageConfigVo.class);
			return vo;
		}
		LOG.info("获取配置信息失败:返回值为空");
		return null;
	}


}
