package com.yihu.jw.sms.service;

import com.jasson.im.api.APIClient;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 * 中山医院短信网关
 * @author huangwenjie
 */
@Service
public class ZhongShanSMSService {
	private String url = "wap.sohu.com";
	private String host = "172.16.1.35";
	private String dbName = "mas";
	private String apiId = "jkzl";
	private String name = "jkzl";
	private String pwd = "jkzl";
	private APIClient handler = new APIClient();
	
	public void init()
	{
		int connectRe = handler.init(host, name, pwd, apiId,dbName);
		if(connectRe == APIClient.IMAPI_SUCC)
			info("初始化成功");
		else if(connectRe == APIClient.IMAPI_CONN_ERR)
			info("连接失败");
		else if(connectRe == APIClient.IMAPI_API_ERR)
			info("apiID不存在");
		if(connectRe != APIClient.IMAPI_SUCC)
		{
			usage();
			System.exit(-1);
		}
	}
	
	/**
	 * 中山医院发送短信
	 * @param mobileStr 手机号（多个以英文逗号相连）
	 * @param content 短信内容
	 * @return
	 */
	public int ZhongShangSendSMS (String mobileStr,String content){
		init();
		
		int result = 0;
		
		//处理手机号
		Vector mobileList = new Vector();
		StringTokenizer st = new StringTokenizer(mobileStr, ",");
		while(st.hasMoreElements())
		{
			String tmp = (String)st.nextElement();
			if( tmp.indexOf("-") != -1 )
			{
				long min = Long.parseLong(tmp.substring(0, tmp.indexOf("-")));
				long max = Long.parseLong(tmp.substring(tmp.indexOf("-") + 1));
				
				long i  = min;
				while(i <= max)
				{
					mobileList.addElement(Long.toString(i));
					i ++;
				}
			}
			else
			{
				mobileList.addElement(tmp);
			}
		}
		int len = mobileList.size();
		String[] mobiles = new String[len];
		for(int i = 0 ; i < len ; i++)
		{
			mobiles[i] = (String)mobileList. elementAt(i);
		}
		Random random = new Random();
//		result = handler.sendSM(mobiles, content, smId, Long.parseLong(tmpSrcID));
		result = handler.sendSM(mobiles, content, 0, random.nextInt(100));
		
		if(result == APIClient.IMAPI_SUCC)
		{
			System.out.println("发送成功\n");
		}
		else if(result == APIClient.IMAPI_INIT_ERR)
			System.out.println("未初始化");
		else if(result == APIClient.IMAPI_CONN_ERR)
			System.out.println("数据库连接失败");
		else if(result == APIClient.IMAPI_DATA_ERR)
			System.out.println("参数错误");
		else if(result == APIClient.IMAPI_DATA_TOOLONG)
			System.out.println("消息内容太长");
		else if(result == APIClient.IMAPI_INS_ERR)
			System.out.println("数据库插入错误");
		else
			System.out.println("出现其他错误");
		
		return result;
	}
	
	public void info(Object obj)
	{
		System.out.println(obj);
	}
	
	public void usage()
	{
		info("Usage : java ApiTestDemo [-h host] [-n name] [-p password] [-i apiCode]");
		info("\t-h host        信息机地址");
		info("\t-n name        API登陆名");
		info("\t-p password    API登陆密码");
		info("\t-i apiCode     API编码");
		
	}
}
