//package com.efounder.chat.service;
//
//import android.app.Notification;
//import android.app.NotificationManager;
//import android.app.PendingIntent;
//import android.app.Service;
//import android.content.Context;
//import android.content.Intent;
//import android.graphics.BitmapFactory;
//import android.graphics.Color;
//import android.os.IBinder;
//import android.support.v4.app.NotificationCompat;
//import android.support.v4.app.TaskStackBuilder;
//import android.util.Log;
//
//import com.efounder.chat.R;
//import com.efounder.chat.activity.New_FriendsActivity;
//import com.efounder.chat.db.WeChatDBManager;
//import com.efounder.chat.event.LiveVideoSysEvent;
//import com.efounder.chat.event.MeetingSysEvent;
//import com.efounder.chat.http.GetHttpUtil;
//import com.efounder.chat.model.ApplyGroupNotice;
//import com.efounder.chat.model.ChatListItem;
//import com.efounder.chat.model.Group;
//import com.efounder.chat.model.LogoutEvent;
//import com.efounder.chat.model.MessageEvent;
//import com.efounder.chat.model.NoticeMessageEvent;
//import com.efounder.chat.model.TaskRefreshEvent;
//import com.efounder.chat.model.UpdateBadgeViewEvent;
//import com.efounder.chat.model.UpdateResEvent;
//import com.efounder.chat.struct.StructFactory;
//import com.efounder.chat.utils.AppUtils;
//import com.efounder.chat.utils.ChatListHelper;
//import com.efounder.chat.utils.ClearUserUtil;
//import com.efounder.chat.utils.GroupAvatarHelper;
//import com.efounder.chat.utils.HttpRequestStatusUtils;
//import com.efounder.chat.utils.IMStruct002Util;
//import com.efounder.chat.utils.ImNotificationUtil;
//import com.efounder.chat.utils.JFChatStyleManager;
//import com.efounder.chat.utils.RingVibratorUtils;
//import com.efounder.chat.utils.ServiceUtils;
//import com.efounder.constant.EnvironmentVariable;
//import com.efounder.form.application.util.FormAppUtil;
//import com.efounder.frame.manager.AppAccountResDownloader;
//import com.efounder.frame.utils.Constants;
//import com.efounder.frame.utils.EFAppAccountFormUtils;
//import com.efounder.frame.utils.EFAppAccountUtils;
//import com.efounder.http.EFHttpRequest;
//import com.efounder.http.EFHttpRequest.HttpRequestListener;
//import com.efounder.interfaces.BadgeUtil;
//import com.efounder.message.manager.JFMessageListener;
//import com.efounder.message.manager.JFMessageManager;
//import com.efounder.message.struct.IMStruct002;
//import com.efounder.mobilecomps.contacts.User;
//import com.efounder.util.AppContext;
//
//import org.greenrobot.eventbus.EventBus;
//import org.json.JSONException;
//import org.json.JSONObject;
//import org.w3c.dom.Document;
//import org.w3c.dom.Element;
//import org.w3c.dom.Node;
//import org.w3c.dom.NodeList;
//
//import java.io.File;
//import java.io.UnsupportedEncodingException;
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//import javax.xml.parsers.DocumentBuilderFactory;
//
//import static com.efounder.chat.struct.MessageChildTypeConstant.live_System_Msg;
//import static com.efounder.chat.struct.MessageChildTypeConstant.meeting_System_Msg;
//import static com.efounder.chat.struct.MessageChildTypeConstant.subtype_App;
//import static com.efounder.chat.struct.MessageChildTypeConstant.subtype_AppRes;
//import static com.efounder.chat.struct.MessageChildTypeConstant.subtype_masterdata;
//import static com.efounder.chat.struct.MessageChildTypeConstant.subtype_officalAccountRes;
//import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
//import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
//
////import com.efounder.deviceadmin.DeviceInfoManager;
////import com.efounder.deviceadmin.PansoftDeviceAdminManager;
////import com.efounder.deviceadmin.PansoftDeviceAdminReceiver;
//
///**
// * 系统消息监听服务
// */
//public class SystemInfoService0502备份 extends Service {
//    private static final String TAG = "SystemInfoService";
//    private static final String TYPE_GROUPAPPLY = "TYPE_GROUPAPPLY";//加群申请，
//    private static final String TYPE_FRIENDAPPLY = "TYPE_FRIENDAPPLY";//好友申请
//
//    //用来记录是否需要请求群组成员数据的map，例如群组id是123，如果map中包含此id，就不再请求该群组的人员信息
//    public static Map<Integer, Boolean> CHATMAP = new HashMap<>();
//
//    public static volatile Integer TOPINDEX = -1;//置顶计数
//    //聊天列表以及聊天列表的map
//    public static volatile List<ChatListItem> CHATITEMLIST = Collections.synchronizedList(new ArrayList<ChatListItem>());
//    public static volatile Map<String, ChatListItem> CHATLISTMAP = Collections.synchronizedMap(new HashMap<String, ChatListItem>());
//    private ChatListHelper chatListHelper;
//
//    /**
//     * 消息管理器
//     **/
//    private JFMessageManager messageManager;
//    /**
//     * 消息监听
//     **/
//    private JFMessageListener messageListener;
//    private WeChatDBManager weChatDBManager;
//
//    /**
//     * 监听新消息来临事件
//     **/
//    private static ReceiveMessageEvent receiveMessageEvent;
//    private static NewFriendCallBack newFriendCallBack;
//
//
//    /**
//     * 群组头像生成
//     */
//    private GroupAvatarHelper helper;
//
//    @Override
//    public IBinder onBind(Intent intent) {
//        return null;
//    }
//
//    @Override
//    public void onCreate() {
//        super.onCreate();
//        Log.i(TAG, "---onCreate---");
//
////        chatListHelper = new ChatListHelper(getApplicationContext());
////        chatListHelper.initData();
//
//        if (!ServiceUtils.isServiceRunning(getApplicationContext(), MessageService.class
//                .getCanonicalName())) {
//            startService(new Intent(getApplicationContext(), MessageService.class));
//        }
//
//        try {
//            messageListener = new ChatMessageListener();
////            weChatDBManager = WeChatDBManager.getInstance();
////            helper = new GroupAvatarHelper(getApplicationContext());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        BadgeUtil.initTotal();
//        me.leolin.shortcutbadger.ShortcutBadger.applyCount(getApplicationContext(), BadgeUtil.getTotalUnReadNum());
//    }
//
//    @Override
//    public int onStartCommand(Intent intent, int flags, int startId) {
//        try {
//            chatListHelper = new ChatListHelper(getApplicationContext());
//            chatListHelper.initData();
//            // messageListener = new ChatMessageListener();
//            weChatDBManager = WeChatDBManager.getInstance();
//            helper = new GroupAvatarHelper(getApplicationContext());
//
//            messageManager = JFMessageManager.getInstance();
//            messageManager.removeMessageListener(EnvironmentVariable.getProperty(CHAT_USER_ID), messageListener);
//            messageManager.addMessageListener(EnvironmentVariable.getProperty(CHAT_USER_ID), messageListener);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return super.onStartCommand(intent, flags, startId);
//    }
//
//    /**
//     * 回话界面各种消息状态的监听
//     */
//    private class ChatMessageListener implements JFMessageListener {
//
//        @Override
//        public synchronized void onReceive(IMStruct002 imstruct002) {
//
//            Log.i(TAG, TAG + "服务正在运行--------");
//            if (imstruct002.getMessageChildType() >= 100 && imstruct002.getMessageChildType() < 200) {//系统消息区间
//                dealSystemMessage(imstruct002);
//            } else if (imstruct002.getMessageChildType() >= 200 && imstruct002.getMessageChildType() < 250) {//应用号表单自定义脚本消息区间
//                dealScriptMessage(imstruct002);
//            } else if (imstruct002.getMessageChildType() == subtype_masterdata) {
//                try {
//                    String jsons = new String(imstruct002.getBody(), "UTF-8");
//                    //主数据存储到本地文件  appAccountID 要从imstruct002中获取
//                    EFAppAccountFormUtils.saveMainData(jsons, imstruct002.getFromUserId());
//                    //FileUtils.writeTextFile(EFAppAccountUtils.getAppAccountJsonPath() + "/" + "master_data.json", jsons);
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//            } else if (imstruct002.getMessageChildType() == subtype_officalAccountRes) {
//                //{"CMD":"updateAppAccountRes","version":"0.0.3","updateNote":"1.应用号资源更新","isUpdate":true}
//                //1.判断是否需要升级
//                if (AppAccountResDownloader.isNeedUpdate(imstruct002)) {
//                    //应用号资源更新发送广播 yqs
//                    Intent intent = new Intent();
//                    intent.putExtra("num", "1");
//                    intent.putExtra("id", imstruct002.getFromUserId());
//                    intent.putExtra("type", "appaccountres");
//                    intent.setAction("com.efounder.updateres");
//                    getApplicationContext().sendBroadcast(intent);
//                }
//            } else if (imstruct002.getMessageChildType() == subtype_App) {
//                //todo APP版本更新发送广播
//                try {
//                    UpdateResEvent event = new UpdateResEvent();
//                    String json = new String(imstruct002.getBody(), "UTF-8");
//                    JSONObject jsonObject = new JSONObject(json);
//
//                    event.setId(imstruct002.getFromUserId());
//                    event.setVersion(jsonObject.getString("version"));//版本号
//                    event.setUpdateNote(jsonObject.getString("updateNote"));//更新说明
//                    event.setType("appupdate");
//                    event.setUrl(jsonObject.getString("url"));
//                    EventBus.getDefault().post(event);
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            } else if (imstruct002.getMessageChildType() == subtype_AppRes) {
//                //todo APP资源文件更新发送广播 yqs
//                try {
//                    String json = new String(imstruct002.getBody(), "UTF-8");
//                    JSONObject jsonObject = new JSONObject(json);
//                    UpdateResEvent event = new UpdateResEvent();
//
////                    Intent intent = new Intent();
////                    intent.putExtra("version", jsonObject.getString("version"));//版本号
////                    intent.putExtra("updateNote", jsonObject.getString("updateNote"));//更新说明
////                    intent.putExtra("id", imstruct002.getFromUserId());
////                    intent.putExtra("type", "appresupdate");
////                    intent.putExtra("url", "");
////                    intent.setAction("com.efounder.updateres");
////                    getApplicationContext().sendBroadcast(intent);
//
//                    event.setId(imstruct002.getFromUserId());
//                    event.setVersion(jsonObject.getString("version"));//版本号
//                    event.setUpdateNote(jsonObject.getString("updateNote"));//更新说明
//                    event.setType("appresupdate");
//                    event.setUrl("");
//                    EventBus.getDefault().post(event);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            } else if (imstruct002.getMessageChildType() == live_System_Msg) {//直播点播类型
//                EventBus.getDefault().post(new LiveVideoSysEvent(imstruct002));
//            } else if (imstruct002.getMessageChildType() == meeting_System_Msg) {//会议消息
//                EventBus.getDefault().post(new MeetingSysEvent(imstruct002));
//            } else if (imstruct002.getMessageChildType() < 100) {
//                //todo 处理聊天气泡 头像
//                JFChatStyleManager.prepareMessage(imstruct002);
//                //todo 处理积分相关消息
//                //JFChatIntegralManager.handleInTegralMessage(imstruct002,true);
//                //震动，声音
//                RingVibratorUtils.RingingAndVibrate(getApplicationContext(), imstruct002);
//
//                chatListHelper.createOrUpdateChatListItem(imstruct002);
//
//                int userId = 0;
//                if (EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("OSPMobileLiveAppTGTest")) {
//                    userId = 709;
//                } else if (EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("OSPMobileLiveAppTG")) {
//                    userId = 6392;
//                } else if (EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("ZSYGXOSPMobile")) {
//                    userId = 2299;
//                }
//                if (imstruct002.getFromUserId() == userId) {//// TODO: 17-8-3 铁工测试709，正式6392,财务共享2299
//                    //任务中心公众号，收到后刷新任务界面，并给RN传递参数
//                    EventBus.getDefault().post(new TaskRefreshEvent(imstruct002));
//                }
//
//                Log.i(TAG, "--=--imstruct002---" + imstruct002.getMessage());
//                boolean isApplicationToBackground = AppUtils.isApplicationToBackground(getApplicationContext());
//                Log.i(TAG, "---application is background:" + isApplicationToBackground);
//                if (isApplicationToBackground) {
//                    Log.i(TAG, "----line156---");
//                    if (imstruct002.getFromUserId() != Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
//                        Log.i(TAG, "---line159---" + imstruct002.getFromUserId() + "," + EnvironmentVariable.getProperty(CHAT_USER_ID));
//                        ImNotificationUtil.showNotificationIm(getApplicationContext(), imstruct002, weChatDBManager);
//
//                    }
//                }
//
//                if (BadgeUtil.getTotalUnReadNum() == -1) {
//                    BadgeUtil.initTotal();
//                } else {
//                    BadgeUtil.totalUnReadNum++;
//                }
//                me.leolin.shortcutbadger.ShortcutBadger.applyCount(getApplicationContext(), BadgeUtil.getTotalUnReadNum());
//
//            }
//
//        }
//
//        @Override
//        public synchronized void onUpdate(int i, IMStruct002 imstruct002) {
//            Log.i(TAG, "onUpdate------消息状态：" + imstruct002.getState());
//            if (imstruct002.getState()<=IMStruct002.MESSAGE_STATE_PRESEND){
//                //处理聊天气泡 头像
//                JFChatStyleManager.prepareMessage(imstruct002);
//            }
//            //处理积分相关消息
//            //JFChatIntegralManager.handleInTegralMessage(imstruct002,false);
//
//            if (imstruct002.getState() == IMStruct002.MESSAGE_STATE_READ
//                    || imstruct002.getState() == IMStruct002.MESSAGE_STATE_RECEIVE
//                    || imstruct002.getState() == IMStruct002.MESSAGE_STATE_UNREAD
//                    || imstruct002.getState() == IMStruct002.MESSAGE_STATE_DELETE || IMStruct002Util.isSystemMessage(imstruct002)) {
//                if (imstruct002.getState() == IMStruct002.MESSAGE_STATE_RECEIVE) {
//                    EventBus.getDefault().post(new NoticeMessageEvent(imstruct002.getToUserId() + "", i + ""));
//                }
//
//            } else {
//                chatListHelper.createOrUpdateChatListItem(imstruct002);
//            }
//
//        }
//
//        @Override
//        public void onFailure(int i, IMStruct002 imstruct002) {
//            Log.i(TAG, "onFailure------消息状态：" + imstruct002.getState());
//        }
//    }
//
//    @Override
//    public void onDestroy() {
//
//        Log.i(TAG, TAG + "onDestroy------");
//        super.onDestroy();
//        messageManager.removeMessageListener(EnvironmentVariable.getProperty(CHAT_USER_ID), messageListener);
//        CHATMAP.clear();
//        CHATITEMLIST.clear();
//        CHATLISTMAP.clear();
//
//    }
//
//    // 显示添加好友通知
//    @SuppressWarnings("deprecation")
//    private void showAddFriendNotification(User user, Boolean isFriend) {
//        NotificationManager mNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//
//        // 我们并不需要为 notification.flags 设置 FLAG_ONGOING_EVENT，因为
//        // 前台服务的 notification.flags 总是默认包含了那个标志位
//        if (!isFriend) {
//            Intent intent = new Intent(this, New_FriendsActivity.class);
//            TaskStackBuilder stackBuilder = TaskStackBuilder.create(AppContext.getInstance());
//            stackBuilder.addParentStack(New_FriendsActivity.class);
//            stackBuilder.addNextIntent(intent);
//            PendingIntent contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
//
//
//            long[] vibrate = {0, 100, 200, 300};
//            NotificationCompat.Builder mBuilder =
//                    new NotificationCompat.Builder(this)
//                            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.wechat_icon_launcher))
//                            .setTicker(user.getNickName() + " 请求添加您为好友")
//                            .setContentTitle("好友申请")
//                            .setContentText(user.getNickName()
//                                    + " 请求添加您为好友")
//                            .setContentIntent(contentIntent)
//                            .setDefaults(Notification.DEFAULT_LIGHTS)
//                            .setDefaults(Notification.FLAG_SHOW_LIGHTS)
//                            .setAutoCancel(true)
//                            .setVibrate(vibrate)//设置震动
//                            .setLights(0xff00ff00, 300, 1000)
//                            .setColor(Color.parseColor("#243BAE"))
//                            .setWhen(System.currentTimeMillis());
////            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
////                mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher_alpha);
////            } else {
//                mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher);
//          //  }
//            mNM.notify(0, mBuilder.build());
//        } else {
//            Intent intent = new Intent(this, New_FriendsActivity.class);
//            TaskStackBuilder stackBuilder = TaskStackBuilder.create(AppContext.getInstance());
//            stackBuilder.addParentStack(New_FriendsActivity.class);
//            stackBuilder.addNextIntent(intent);
//            PendingIntent contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
//
//            long[] vibrate = {0, 100, 200, 300};
//            NotificationCompat.Builder mBuilder =
//                    new NotificationCompat.Builder(this)
//                            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.wechat_icon_launcher))
//                            .setTicker(user.getNickName() + " 已同意您的好友申请")
//                            .setContentTitle("好友申请通过")
//                            .setContentText(user.getNickName()
//                                    + " 已同意您的好友申请")
//                            .setContentIntent(contentIntent)
//                            .setDefaults(Notification.DEFAULT_LIGHTS)
//                            .setDefaults(Notification.FLAG_SHOW_LIGHTS)
//                            .setAutoCancel(true)
//                            .setVibrate(vibrate)//设置震动
//                            .setLights(0xff00ff00, 300, 1000)
//                            .setColor(Color.parseColor("#243BAE"))
//                            .setWhen(System.currentTimeMillis());
////            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
////                mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher_alpha);
////            } else {
//                mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher);
//        //    }
//            mNM.notify(0, mBuilder.build());
//        }
//
//    }
//
//    /**
//     * 得到用户信息
//     *
//     * @param uid         用户id
//     * @param isFriend    是好友保存到本地，不是好友，不保存到本地
//     * @param messageType 消息类型，好友申请还是加群申请
//     */
//    private void getFriendInfo(int uid, final boolean isFriend, String messageType) {
//        String userid = EnvironmentVariable.getProperty(CHAT_USER_ID);
//        String password = EnvironmentVariable.getProperty(CHAT_PASSWORD);
//        EFHttpRequest httpRequest = new EFHttpRequest(this);
//        String url = GetHttpUtil.ROOTURL + "/IMServer/user/getOtherUserByUserId?otherUserId=" + uid;
//        httpRequest.httpGet(url);
//        httpRequest.setHttpRequestListener(new HttpRequestListener() {
//
//            @Override
//            public void onRequestSuccess(int requestCode, String response) {
//                try {
//                    JSONObject jsonObject = new JSONObject(response).getJSONObject("user");
//
//                    int id = jsonObject.getInt("userId");
//                    User user = new User();
//                    user.setId(jsonObject.getInt("userId"));
//                    user.setLoginUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
//                    user.setName(jsonObject.getString("userName"));
//                    if (jsonObject.has("nickName")) {
//                        user.setNickName(jsonObject.getString("nickName"));
//                        user.setReMark(jsonObject.getString("nickName"));
//                    } else {
//                        user.setNickName(jsonObject.getString("userName"));
//                        user.setReMark(jsonObject.getString("userName"));
//                    }
//                    if (jsonObject.has("sex")) {
//                        user.setSex(jsonObject.getString("sex"));
//                    } else {
//                        user.setSex("M");
//                    }
//                    if (jsonObject.has("phone")) {
//                        user.setPhone(jsonObject.getString("phone"));
//                    } else {
//                        user.setPhone("");
//                    }
//                    if (jsonObject.has("mobilePhone")) {
//                        user.setMobilePhone(jsonObject.getString("mobilePhone"));
//                    } else {
//                        user.setMobilePhone("");
//                    }
//                    if (jsonObject.has("email")) {
//                        user.setEmail(jsonObject.getString("email"));
//                    } else {
//                        user.setEmail("");
//                    }
//                    if (jsonObject.has("userType")) {
//                        user.setType(Integer.valueOf(jsonObject.getString("userType")));
//                    } else {
//                        user.setType(User.PERSONALFRIEND);//好友类型
//                    }
//                    if (jsonObject.has("avatar")) {
//                        if (!jsonObject.getString("avatar").equals("") && jsonObject.getString("avatar").contains("http")) {
//                            user.setAvatar(jsonObject.getString("avatar"));
//                        } else
//                            user.setAvatar("");
//                    } else {
//                        user.setAvatar("");
//                    }
//                    if (jsonObject.has("sign")) {//个性签名
//                        user.setSigNature(jsonObject.getString("sign"));
//                    } else {
//                        user.setSigNature("");
//                    }
//                    user.setDeptId(0);
//                    user.setIsImportantContacts(false);
//                    user.setIsBother(false);
//                    user.setIsTop(false);
//                    user.setSortLetters(null);
//
//
//                    if (isFriend) {
//                        user.setState(User.ACCEPTED);//0 未接受好友申请 1，已添加同意好友申请，2已发送好友申请
//                        user.setTime(new Date().getTime());
//                        user.setIsRead(false);
////                        New_FriendsActivity.UNREADNEWFRIEND += 1;
////                        receiveMessageEvent.receiveMessage("contacts", New_FriendsActivity.UNREADNEWFRIEND+GroupNotifacationActivity.GROUPNOTICOUNT);
////                        if (newFriendCallBack != null) {
////                            newFriendCallBack.setUnReadNum(New_FriendsActivity.UNREADNEWFRIEND);
////                        }
//                        weChatDBManager.agreeNewFriendApply(user);
////                        int newFriendCount = weChatDBManager.getNewFriendUnread();
////                        int groupNoticeCount = weChatDBManager.getGroupNoticveUnreadCount();
////                        EventBus.getDefault().post(new NoticeCountEvent(newFriendCount, groupNoticeCount));
//                        UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(-2 + "", (byte) 0);
//                        EventBus.getDefault().post(updateBadgeViewEvent);
//
//                        showAddFriendNotification(user, isFriend);
//
//                    } else {
//                        //将好友申请保存到数据库
//                        user.setState(User.UNACCEPT);
//                        user.setIsRead(false);
//                        user.setTime(new Date().getTime());
//                        weChatDBManager.insertSendNewFriendApply(user);
////                        New_FriendsActivity.UNREADNEWFRIEND += 1;
////                        if (newFriendCallBack != null) {
////                            newFriendCallBack.setUnReadNum(New_FriendsActivity.UNREADNEWFRIEND);
////                        }
////
////                        receiveMessageEvent.receiveMessage("contacts", New_FriendsActivity.UNREADNEWFRIEND+GroupNotifacationActivity.GROUPNOTICOUNT);
//                        int newFriendCount = weChatDBManager.getNewFriendUnread();
//                        int groupNoticeCount = weChatDBManager.getGroupNoticveUnreadCount();
//                        //EventBus.getDefault().post(new NoticeCountEvent(newFriendCount, groupNoticeCount));
//                        UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(-2 + "", (byte) 0);
//                        EventBus.getDefault().post(updateBadgeViewEvent);
//                        showAddFriendNotification(user, isFriend);
//                    }
//
//                    // }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//            @Override
//            public void onRequestFail(int requestCode, String message) {
//
//
//            }
//        });
//
//    }
//
//    // todo 2016/10/16 系统消息  处理消息，个人信息，群组信息更改后推送的消息
//    private void dealSystemMessage(IMStruct002 imstruct002) {
//        String json = "";
//        try {
//            json = new String(imstruct002.getBody(), "UTF-8");
//            System.out.println("----打印输出系统消息：" + json + "----");
//            Log.i(TAG, "---json--" + json);
//            // {"friendUserId":1,"CMD":"applyAddFriend"}
//            JSONObject jsonObject = new JSONObject(json);
//            int friendUserId;
//            String CMD = jsonObject.getString("CMD");
//            Log.i(TAG, CMD);
//            if (CMD.equals("applyAddFriend")) {// 申请好友
//                friendUserId = jsonObject.getInt("friendUserId");
//                getFriendInfo(friendUserId, false, TYPE_FRIENDAPPLY);
//                Log.i("addfriendService", String.valueOf(friendUserId));
//            } else if (CMD.equals("addFriend")) {// 对方同意你的好友申请
//                friendUserId = jsonObject.getInt("friendUserId");
//                getFriendInfo(friendUserId, true, TYPE_FRIENDAPPLY);
//
//
//            } else if (CMD.equals("userQuitGroup")) {//用户退群
//                int groupId = jsonObject.getInt("groupId");
//                int userId = jsonObject.getInt("groupUserId");
//                weChatDBManager.quitGroup(userId, groupId);
//                CHATMAP.remove(groupId);
//                //GroupAvatarUtil.createNewGroupAvatar(getApplicationContext(), groupId);
//                helper.createNewGroupAvatar(groupId);
//            } else if (CMD.equals("updateOwnerNoteInGroup")) {//群成员修改群昵称的消息
//                int groupId = jsonObject.getInt("groupId");
//                int userId = jsonObject.getInt("userId");
//                String note = jsonObject.getString("note");
//                User tempUser = weChatDBManager.getGroupUserInfo(groupId, userId);
//                tempUser.setOwnGroupRemark(note);
//                weChatDBManager.insertOrUpdateMyGroupUser(groupId, tempUser);
//            } else if (CMD.equals("deleteGroupUser")) {//群主移除群组人员
//                int groupId = jsonObject.getInt("groupId");
//                int userId = jsonObject.getInt("groupUserId");
//                weChatDBManager.quitGroup(userId, groupId);
//                CHATMAP.remove(groupId);
//                //GroupAvatarUtil.createNewGroupAvatar(getApplicationContext(), groupId);
//                helper.createNewGroupAvatar(groupId);
//                //TODO 如果userId和登录的用户id相同，删除列表数据
//                if (userId == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
//                    ChatListItem chatListItem = weChatDBManager.getChatListItem(groupId, StructFactory.TO_USER_TYPE_GROUP);
//                    if (chatListItem != null) {
//                        weChatDBManager.deleteChatListiItem(chatListItem);
//                        EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.DELETE));
//                        // 清除通知栏消息
//                        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//                        int requestCode = Integer.valueOf(chatListItem.getUserId() + "" + chatListItem.getChatType());
//                        notificationManager.cancel(requestCode);
//                    }
//                }
//            } else if (CMD.equals("addUserToGroup")) {//新建群聊系统推送的人员列表
//                final int groupId = jsonObject.getInt("groupId");
//                final int userId = jsonObject.getInt("groupUserId");
//                ApplyGroupNotice notice = new ApplyGroupNotice();
//                notice.setGroupId(groupId);
//                notice.setUserId(userId);
//                notice.setTime(System.currentTimeMillis());
//                notice.setRead(true);
//                notice.setState(ApplyGroupNotice.ACCEPTED);
//                weChatDBManager.updateGroupNotice(notice);//更新群通知消息
//
//                int newFriendCount = weChatDBManager.getNewFriendUnread();
//                int groupNoticeCount = weChatDBManager.getGroupNoticveUnreadCount();
//                //EventBus.getDefault().post(new NoticeCountEvent(newFriendCount, groupNoticeCount));
//                UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(-2 + "", (byte) 0);
//
////                GetHttpUtil.getUserInfo(userId, getApplicationContext(), new
////                        GetHttpUtil.GetUserListener() {
////                            @Override
////                            public void onGetUserSuccess(User user1) {
////                                //TODO yqs 插入新成员到数据库
////                                weChatDBManager.insertOrUpdateMyGroupUser(groupId, userId);
////
////                            }
////                        });
//                Group group1 = weChatDBManager.getGroupWithUsers(groupId);
//                if (!group1.isExist()) {
//                    GetHttpUtil.getGroupById(getApplicationContext(), groupId, new GetHttpUtil.getGroupInfoCallBack() {
//                        @Override
//                        public void onGetGroupInfoSuccess(Group group) {
//                            HttpRequestStatusUtils.remove(groupId + "");
//                        }
//                    }, true);
//                }
//                //如果群存在并且群成员数为0
//                else if (group1 != null && group1.getUsers().size() == 0) {
//                    GetHttpUtil.getGroupUsers(getApplicationContext(), groupId, new GetHttpUtil.ReqCallBack() {
//                        @Override
//                        public void onReqSuccess(Object result) {
//                            Log.i(TAG, "success---yqs");
//                            helper.createNewGroupAvatar(groupId);
//                        }
//
//                        @Override
//                        public void onReqFailed(String errorMsg) {
//
//                        }
//                    });
//                } else if (group1 != null) {
//                    User user = weChatDBManager.getOneUserById(userId);
//                    if (!user.isExist()) {
//                        GetHttpUtil.getUserInfo(userId, getApplicationContext(), new GetHttpUtil.GetUserListener() {
//                            @Override
//                            public void onGetUserSuccess(User user1) {
//                                //TODO yqs 插入新成员到数据库
//                                weChatDBManager.insertOrUpdateMyGroupUser(groupId, userId);
//                                helper.createNewGroupAvatar(groupId);
//
//                            }
//                        });
//                        return;
//                    }
//                    weChatDBManager.insertOrUpdateMyGroupUser(groupId, userId);
//                    helper.createNewGroupAvatar(groupId);
//                }
//
//
//            } else if (CMD.equals("updateGroup")) {//更新群组的消息
//                final int groupId = jsonObject.getInt("groupId");
//                final String groupName = jsonObject.getString("groupName");
//                String avatar = "";
//                if (jsonObject.has("avatar")) {
//                    avatar = jsonObject.getString("avatar");
//                }
//                Group group = weChatDBManager.getGroupWithUsers(groupId);
//                if (group != null) {
//                    group.setGroupName(groupName);
//                    if (!avatar.equals("")) {
//                        group.setAvatar(avatar);
//                    }
//                    weChatDBManager.insertOrUpdateGroup(group);
//                }
//                ChatListItem chatListItem = weChatDBManager.getChatListItem(groupId, StructFactory.TO_USER_TYPE_GROUP);
//                if (chatListItem != null) {
//                    chatListItem.setGroup(group);
//                    EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
//                }
//
//            } else if (CMD.equals("updateUser")) {//更新 好友信息
//                int userId = jsonObject.getInt("userId");
//                String json1 = jsonObject.getString("user");
//                User user = weChatDBManager.getOneUserById(userId);
//                if (user != null) {
//                    user.setLoginUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
//                    JSONObject jsonObject1 = new JSONObject(json1);
//                    user.setName(jsonObject1.getString("userName"));
//
//                    if (jsonObject1.has("nickName")) {
//                        user.setNickName(jsonObject1.getString("nickName"));
//
//                    } else {
//                        user.setNickName(jsonObject1.getString("userName"));
//                    }
//                    if (jsonObject1.has("sex")) {
//                        user.setSex(jsonObject1.getString("sex"));
//                    } else {
//                        user.setSex("M");
//                    }
//                    if (jsonObject1.has("phone")) {
//                        user.setPhone(jsonObject1.getString("phone"));
//                    } else {
//                        user.setPhone("");
//                    }
//                    if (jsonObject1.has("mobilePhone")) {
//                        user.setMobilePhone(jsonObject1.getString("mobilePhone"));
//                    } else {
//                        user.setMobilePhone("");
//                    }
//                    if (jsonObject1.has("email")) {
//                        user.setEmail(jsonObject1.getString("email"));
//                    } else {
//                        user.setEmail("");
//                    }
//                    if (jsonObject1.has("userType")) {
//                        user.setType(Integer.valueOf(jsonObject1.getString("userType")));
//                    } else {
//                        user.setType(User.PERSONALFRIEND);//好友类型
//                    }
//                    if (jsonObject1.has("avatar")) {
//                        if (!jsonObject1.getString("avatar").equals("") && jsonObject1.getString("avatar").contains("http")) {
//                            user.setAvatar(jsonObject1.getString("avatar"));
//                        } else
//                            user.setAvatar("");
//                    } else {
//                        user.setAvatar("");
//                    }
//                    if (jsonObject1.has("note")) {//备注名
//                        user.setReMark(jsonObject1.getString("note"));
//                    } else {
//                        user.setReMark(user.getNickName());
//                    }
//                    if (jsonObject1.has("sign")) {//个性签名
//                        user.setSigNature(jsonObject1.getString("sign"));
//                    } else {
//                        user.setSigNature("");
//                    }
//                    //weChatDBManager.insertOrUpdateUser(user);
//                    weChatDBManager.insertUserTable(user);
//                    ChatListItem chatListItem = weChatDBManager.getChatListItem(user.getId(), 0);
//                    if (chatListItem != null) {
//                        chatListItem.setUser(user);
//                        EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
//                    }
//
//                }
//
//
//            } else if (CMD.equals("updatePublic")) {//应用号信息更新
////                PansoftDeviceAdminManager.initDPM(this);
////                PansoftDeviceAdminManager.initComponent(this, PansoftDeviceAdminReceiver.class);
//
//                JSONObject publicUser = jsonObject.getJSONObject("public");
//                //// TODO: 17-8-7 MDM管理待修改
////                String command = publicUser.getString("userName");
////                if (publicUser.getInt("userId")==2307) {
////                    switch (command) {
////                        case "lock":
////                            PansoftDeviceAdminManager.lockScreen();
////                            break;
////                        case "updateInfo":
////                            DeviceInfoManager deviceInfoManager = new DeviceInfoManager(this);
////                            deviceInfoManager.getDeviceInfo();
////                            break;
////                        case "logOut":
////                            EventBus.getDefault().post(new LogoutEvent());
////                            break;
////                        case "0000":
////                            PansoftDeviceAdminManager.resetPassword("");
////                            break;
////                        default:
////                            PansoftDeviceAdminManager.resetPassword(command);
////                            break;
////                    }
////                }
//                User user = new User();
//                user.setId(publicUser.getInt("userId"));
//                user.setType(publicUser.getInt("userType"));
//                user.setName(publicUser.getString("userName"));
//                user.setNickName(publicUser.getString("nickName"));
//                user.setAvatar(publicUser.getString("avatar"));
//                user.setReMark(publicUser.getString("nickName"));
//                weChatDBManager.insertOrUpdateFriendUser(user);
//                ChatListItem chatListItem = weChatDBManager.getChatListItem(user.getId(), 0);
//                if (chatListItem != null) {
//                    chatListItem.setUser(user);
//                    chatListItem.setName(publicUser.getString("nickName"));
//                    EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
//                }
//
//            } else if (CMD.equals("deviceLogout")) {
//                //设备下线
//                EventBus.getDefault().post(new LogoutEvent());
//            } else if (CMD.equals("applyAddGroup")) {//申请加群的系统消息
//                int groupId = jsonObject.getInt("groupId");//申请要加入的群号
//                int userId = jsonObject.getInt("userId");//申请加群的人的信息
//                // GroupNotifacationActivity.GROUPNOTICOUNT += 1;
//                User tempUser = weChatDBManager.getOneUserById(userId);
//                Group tempGroup = weChatDBManager.getGroupWithUsers(groupId);
//                final ApplyGroupNotice applyGroupNotice = new ApplyGroupNotice();
//                applyGroupNotice.setUserId(userId);
//                applyGroupNotice.setGroupId(groupId);
//                applyGroupNotice.setRead(false);
//                applyGroupNotice.setState(ApplyGroupNotice.UNACCEPT);
//                applyGroupNotice.setTime(System.currentTimeMillis());
//                applyGroupNotice.setGroup(tempGroup);
//
//                if (tempUser.getNickName().equals(String.valueOf(tempUser.getId()))) {
//                    //该用户在本地不存在
//                    GetHttpUtil.getUserInfo(userId, getApplicationContext(), new GetHttpUtil.GetUserListener() {
//                        @Override
//                        public void onGetUserSuccess(User user) {
//                            applyGroupNotice.setUser(user);
//                            showApplyNotice(applyGroupNotice);
//                        }
//                    });
//                } else {
//                    applyGroupNotice.setUser(tempUser);
//                    showApplyNotice(applyGroupNotice);
//
//                }
//
//
//            } else if (CMD.equals("setGroupMana")) {//设置系统管理员的系统消息
//                int groupId = jsonObject.getInt("groupId");
//                int userId = jsonObject.getInt("userId");
//                User user = new User();
//                user.setId(userId);
//                user.setGroupUserType(User.GROUPMANAGER);//为用户设置管理员属性
//                weChatDBManager.insertorUpdateGroupManager(groupId, user);
//            } else if (CMD.equals("cancelGroupMana")) {//取消设置系统管理员的系统消息
//                int groupId = jsonObject.getInt("groupId");
//                int userId = jsonObject.getInt("userId");
//                User user = new User();
//                user.setId(userId);
//                user.setGroupUserType(User.GROUPMEMBER);//为用户设置普通成员属性
//                weChatDBManager.insertorUpdateGroupManager(groupId, user);
//            } else if (CMD.equals("addUserToPublic")) {//fixme 收到关注应用号成功的消息
//                int userId = jsonObject.getInt("userId");
//                int publicId = jsonObject.getInt("publicId");
//                User user = weChatDBManager.getOneUserById(publicId);
//                user.setType(User.PUBLICFRIEND);
//                user.setIsBother(false);
//                user.setLoginUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
//                weChatDBManager.insertOfficialNumber(user);
//                ImNotificationUtil.showApplyPublicNotification(user.getId(), getApplicationContext(), weChatDBManager);
//            } else if (CMD.equals("deleteFriend")) {//自己删除好友，其他设备收到推送系统消息
//                //{"friendUserId":54,"CMD":"deleteFriend"}
//                int userId = jsonObject.getInt("friendUserId");
//                ClearUserUtil.deleteUserFromDb(weChatDBManager, getApplicationContext(), userId, (byte) 0);
//            } else if (CMD.equals("dissolveGroup")) {//收到解散群组的消息
//                // {"CMD":"dissolveGroup","groupId":1770,"userId":192}
//                int groupId = jsonObject.getInt("groupId");
//                ClearUserUtil.dissolveGroup(weChatDBManager, getApplicationContext(), groupId);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    private void showApplyNotice(ApplyGroupNotice applyGroupNotice) {
//        weChatDBManager.insertOrUpdateGroupNotice(applyGroupNotice);
//        ImNotificationUtil.showApplyGroupNotice(getApplicationContext(),
//                applyGroupNotice, ImNotificationUtil.APPLYING);
//        /// EventBus.getDefault().post(new BadageNumEvent(GroupNotifacationActivity.GROUPNOTICOUNT, 0));
////        int newFriendCount = weChatDBManager.getNewFriendUnread();
////        int groupNoticeCount = weChatDBManager.getGroupNoticveUnreadCount();
////        EventBus.getDefault().post(new NoticeCountEvent(newFriendCount, groupNoticeCount));
//        EventBus.getDefault().post(new UpdateBadgeViewEvent("-2", (byte) 0));
//    }
//
//    /**
//     * 处理脚本类型消息
//     */
//    private void dealScriptMessage(IMStruct002 imstruct002) {
//        Node scripChildNode = findScriptNode(imstruct002);
//        if (scripChildNode == null) return;
//        //读取到脚本，并执行脚本
//        String script = getScript(imstruct002, scripChildNode);
//        //
//        FormAppUtil.executeScript(script);
//    }
//
//    /***
//     * 根据消息类型，找到对应得脚本节点
//     *
//     * @param imstruct002
//     * @return
//     */
//    private Node findScriptNode(IMStruct002 imstruct002) {
//        int fromUserId = imstruct002.getFromUserId();//应用号id
//        String path = EFAppAccountUtils.getAppAccountAppsPath() + "/" + fromUserId + "/app_frame.xml";
//        //读取 xml中配置的脚本
//        try {
//            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(path));
//            Element rootElement = document.getDocumentElement();
//            NodeList nodeList = rootElement.getElementsByTagName("scriptObject");
//            if (nodeList == null || nodeList.getLength() == 0) return null;
//            Node scriptNode = nodeList.item(0);
//            if (scriptNode.getNodeType() == Node.ELEMENT_NODE) {
//                Element scriptElement = (Element) scriptNode;
//                NodeList scriptChildNodes = scriptElement.getChildNodes();
//                for (int i = 0; i < scriptChildNodes.getLength(); i++) {
//                    Node scripChildNode = scriptChildNodes.item(i);
//                    if (scripChildNode.getNodeType() == Node.ELEMENT_NODE) {
//                        String id = scripChildNode.getAttributes().getNamedItem("id").getNodeValue();
//                        if (id.equals("message_type_" + imstruct002.getMessageChildType())) {
//                            return scripChildNode;
//                        }
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    private String getScript(IMStruct002 imstruct002, Node scripChildNode) {
//        String script = null;
//        try {
//            JSONObject jsonObject = new JSONObject(imstruct002.getMessage());
//            script = scripChildNode.getTextContent();
//            //解析参数
//            String arguments = scripChildNode.getAttributes().getNamedItem("arguments").getNodeValue();
//            if (arguments != null && arguments.length() > 0) {
//                String[] argumentArray = arguments.split(";");
//                for (String argument : argumentArray) {
//                    String argumentValue = jsonObject.getString(argument);
//                    script = script.replaceAll("@" + argument + "@", argumentValue);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return script;
//    }
//
//    //监听收到新消息的事件
//    public interface ReceiveMessageEvent {
//        public void receiveMessage(String type, int num);
//    }
//
//    public static void setReceiveMessageEvent(ReceiveMessageEvent _receiveMessageEvent) {
//        receiveMessageEvent = _receiveMessageEvent;
//    }
//
//    public interface NewFriendCallBack {
//        public void setUnReadNum(int count);
//    }
//
//    public static void setNewFriendCallBack(NewFriendCallBack newFriendCallBack1) {
//        newFriendCallBack = newFriendCallBack1;
//    }
//
//}
