package com.cesgroup.cesmonitor.service;

import java.util.ArrayList;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.esms.MOMsg;
import com.esms.MessageData;
import com.esms.PostMsg;
import com.esms.common.entity.Account;
import com.esms.common.entity.GsmsResponse;
import com.esms.common.entity.MTPack;
import com.esms.common.entity.MTPack.MsgType;

/**
 * 玄武短信接口收发器
 *
 * @author hgl
 *
 */
public class ShortMessageUtil {

    Log log = LogFactory.getLog(this.getClass());

    private Account ac = null;

    private PostMsg pm = null;

    private static ShortMessageUtil util;

    public static void init(String userName, String password, String serverHost, int cmPort, int wsPort) {
        util = new ShortMessageUtil();
        try {
            util.ac = new Account(userName, password);
            util.pm = new PostMsg();
            util.pm.getCmHost().setHost(serverHost, cmPort);//您设置的下行端口 ~~~设置网关的IP和port，用于发送信息
            util.pm.getWsHost().setHost(serverHost, wsPort);//设置网关的IP和port，用于获取账号信息、上行、状态报告等等
            //            /***
            //             * 定时读取收到的短信，由于原本的短信接收回调监听不稳定,所以自己重写个定时接收线程
            //             */
            //
            //            Thread thread = new Thread(new Runnable() {
            //
            //                @Override
            //                public void run() {
            //                    try {
            //                        while (true) {
            //                            Thread.sleep(30 * 1000);//每隔30秒轮询一次
            //                            recieveMOMsgs(pm, ac, 1000);
            //                        }
            //                    } catch (Exception e) {
            //                        e.printStackTrace();
            //                    }
            //                }
            //            });
            //            thread.start();
        } catch (final Exception e) {
            util = null;
            e.printStackTrace();
        }
    }

    /**
     * 启动玄武短信服务
     */
    public static ShortMessageUtil getInstance() {
        return util;
    }

    /**
     * 发送短信
     *
     * @param mobile
     *            获得接收者手机号码
     * @param content
     *            短信内容
     */
    public String send(String mobile, String content) {
        return this.send(new String[] { mobile }, content);
    }

    /**
     * 发送短信
     *
     * @param mobiles
     *            获得接收者手机号码
     * @param content
     *            短信内容
     */
    public String send(String[] mobiles, String content) {
        final MTPack pack = new MTPack();
        pack.setBatchID(UUID.randomUUID());
        pack.setBatchName("短信测试批次");
        pack.setMsgType(MsgType.SMS);
        pack.setSendType(MTPack.SendType.MASS);
        pack.setBizType(0);
        pack.setDistinctFlag(false);

        final ArrayList<MessageData> msgs = new ArrayList<MessageData>();
        //        String senderId = shortMessage.getSenderId();
        //        System.out.println(senderId);
        //        pack.setCustomNum(senderId);//添加扩展码

        if (mobiles.length > 0) {
            for (final String phone : mobiles) { //遍历要接收短信的手机号码
                //对手机号进行验证
                final MessageData mess = new MessageData(phone, content);//单条信息
                msgs.add(mess);
            }
        }
        pack.setMsgs(msgs);

        //发送短信
        //GsmsResponse信息包提交至网关的响应，响应结果包含信息内容及状态结果
        GsmsResponse resp = null;
        String message = null;
        try {
            resp = pm.post(ac, pack);
            resp.getResult(); //返回系统返回值 枚举类型
            //          resp.getMessage();      //系统返回值的说明   （如：返回值为0，那么说明发送成功，否则失败）

            if (resp.getResult() == 0) {
                message = "成功";
            } else if (resp.getResult() == -1) {
                message = "账号无效";
            } else if (resp.getResult() == -2) {
                message = "参数无效";
            } else if (resp.getResult() == -3) {
                message = "连接不上服务器";
            } else if (resp.getResult() == -5) {
                message = "无效的短信数据，号码格式不对";
            } else if (resp.getResult() == -6) {
                message = "用户名密码错误";
            } else if (resp.getResult() == -11) {
                message = "包号码数量超过最大限制";
            } else if (resp.getResult() == -12) {
                message = "余额不足";
            } else if (resp.getResult() == -99) {
                message = "系统内部错误";
            } else {
                message = "其它错误";
            }
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }

        //        System.out.println(resp);
        //        System.out.println("系统返回值为：" + resp.getResult());//返回系统返回值 枚举类型
        //        System.out.println(msgs);
        return message;

    }

    public Long receiveUserId(String sepcNumber) {
        //必须根据该端口号获取 发送短信userId
        //MTPack pack = new MTPack();
        new MTPack();

        return null;
    }

    //接收短信
    //  public void recieveMOMsgs() throws Exception{
    //      MOMsg[] mos = pm.getMOMsgs(ac, 1000); //获取上行信息
    //      if(mos != null&& mos.length<1000){
    //          for(MOMsg msg : mos){
    //              try {
    public void recieveMOMsgs(PostMsg pm, Account account, int pagesize) throws Exception {
        final MOMsg[] mos = pm.getMOMsgs(ac, 1000);
        if (mos != null) {
            for (final MOMsg msg : mos) {
                try {
                    final String mobieNo = msg.getPhone();//
                    final String msgText = msg.getContent();//消息内容(即获得上行信息内容-->短信内容)
                    //                    OffLineMsg offMsg = new OffLineMsg();
                    final String sepcNumber = msg.getSepcNumber();
                    //截取扩展码    即类似 电信：1069 0695 2963 37302
                    // 联通：1069 0969 2963 37302
                    // 移动：1069 0525 2963 37302
                    final String str = sepcNumber.substring(sepcNumber.indexOf("2963") + 4, sepcNumber.length());
                    final Long userId = Long.parseLong(str);//×
                    //                    if (userId != null) {//接收用户存在
                    //                        SessionInfo sessionInfo = LiveSession.getInstance().getSessionInfo(userId);
                    //                        if (sessionInfo != null) {
                    //                            //在线
                    //                            ShortMessage shortMessage = new ShortMessage();
                    //                            shortMessage.setSenderPhoneNumber(mobieNo);
                    //                            shortMessage.setContent(msgText + " (来自手机号:" + mobieNo + " 的回复)");
                    //                            shortMessage.setSendTime(String.valueOf(System.currentTimeMillis()));
                    //                            shortMessage.setReceiverIds(new String[] { String.valueOf(sessionInfo.userId) });
                    //                            log.debug("触发接收短信监听器。");
                    //                            ShortMessageReceiveEvent event = new ShortMessageReceiveEvent();
                    //                            event.setShortMessage(shortMessage);
                    //                            fireShortMessageReceiveListener(event);
                    //
                    //                        } else {
                    //                            //不在线保存为离线消息
                    //                            Long fromUserId = offMsg.queryIdFromUserDetailTableByPhoneNumber(mobieNo);
                    //                            offMsg.setFromId(fromUserId + "");
                    //                            offMsg.setToId(userId + "");
                    //                            offMsg.setFromFace("");
                    //                            offMsg.setMsgType(Const.IM_NORMAL_TEXT);
                    //                            offMsg.setMsgTime(msg.getRecevieTime());
                    //                            offMsg.setMsgTitle(String.valueOf(Const.MESSAGE_SOURCE_SMS));
                    //                            offMsg.setMsgContent(Eryptogram.DataEncrypt(msgText + " (来自手机号:" + mobieNo + "的回复)"));
                    //                            offMsg.setUrl("");
                    //                            offMsg.add();
                    //                        }
                    //                    }

                } catch (final Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
