package com.yonge.toolset.thirdparty.message.provider;

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

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.yonge.toolset.base.exception.ThirdpartyException;
import com.yonge.toolset.thirdparty.message.MessageSenderPlugin;
import com.yonge.toolset.utils.date.DateUtil;
import com.yonge.toolset.utils.http.HttpUtil;

/**
 * 亿美短信
 */
@Service
public class YimeiSmsPlugin implements MessageSenderPlugin, InitializingBean {

	private Logger logger = LoggerFactory.getLogger(YimeiSmsPlugin.class);

	@Value("${com.properties.sms-appId:EUCP-EMY-SMS1-DX0Y9}")
	private String appId;
	@Value("${com.properties.sms-secretKey:B0C8230D0F2ACC64}")
	private String secretKey;
	@Value("${com.properties.sms-host-dev:http://bjmtn.b2m.cn}")
	private String host;

	public static String getName() {
		return "yimei";
	}

	private String getParam(String subject, String content, String receiver, String host) {
		try {
			HashMap<String, Object> param = new HashMap();
			param.put("appId", appId);
			String timestamp = DateUtil.format(new Date(), new SimpleDateFormat("yyyyMMddHHmmss"));
			param.put("timestamp", timestamp);
			param.put("sign", DigestUtils.md5Hex(appId + secretKey + timestamp));
			param.put("content", content);
			param.put("mobiles", receiver);
			
			long startTime = System.currentTimeMillis();
			String result =  HttpUtil.postForHttp(host, param);
			logger.info("调用亿美接口共消耗{}毫秒",System.currentTimeMillis() - startTime);
			
			return result;
		} catch (Exception e) {
			throw new ThirdpartyException("调用发送短信接口出现异常", e);
		}
	}

	@Override
	public boolean send(String subject, String content, String receiver, String url,String jpushType,String sound,String channelId) throws Exception {
		String result = getParam(subject, content, receiver, host + "/simpleinter/sendSMS");
		JSONObject json = JSONObject.parseObject(result);
		if ("SUCCESS".equals(json.get("code"))) {

			return true;
		} else {
			throw new Exception(json.getString("code"));
		}
	}

	@Override
	public boolean batchSend(String subject, String content, String[] receivers, String url,String jpushType,String sound,String channelId) throws Exception {
		String join = StringUtils.join(receivers, ",");
		String result = getParam(subject, content, join, host + "/simpleinter/sendSMS");
		logger.info("调用短信接口返回:{}", result);
		JSONObject json = JSONObject.parseObject(result);
		if ("SUCCESS".equals(json.get("code"))) {
			return true;
		} else {
			throw new Exception(json.getString("code"));
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {

	}
}
