/**
   * 响应:员工的在线状态
   *
   * <p>一次请求最大值为100
   *
   * @param command
   */
  private void responseState(short command) {

    LogFactory.d("EmployeeState", "----------responseEmployeeState ---------");
    GetEmployeesStatusInPacket inPacket =
        (GetEmployeesStatusInPacket) IMOApp.getDataEngine().getInPacketByCommand(command);
    if (inPacket == null) {
      return;
    }

    inPacket.getCid();
    int[] uid = inPacket.getUid();
    int[] status = inPacket.getStatus();

    for (int i = 0; i < uid.length; i++) {
      mGlobal.userStateMap.put(uid[i], status[i]);
    }

    // 当前部门的请求是否都已经完成了
    if (parent_hasRequestCount < parent_StateRequestCount) {

      Object[] idArrays = getRequestUserIdArray();
      if (idArrays != null) {
        doEmployeeState(((int[]) idArrays[0]).length, ((int[]) idArrays[0]), ((int[]) idArrays[1]));
      }
    } else {
      LogFactory.d("EmployeeState", "状态请求完成。。。。。");
      // /更新
      StateHandle.getInstance().updateAllState();
    }
  }
 private void get_special_hide_dept_ids(int uid) {
   Integer did = findDidByUid(uid);
   DeptMaskItem deptMaskItem = null;
   while (did != null && did != 0) {
     special_hide_dept_ids.add(did);
     deptMaskItem = IMOApp.getApp().deptInfoMap.get(did);
     if (deptMaskItem == null) return;
     did = deptMaskItem.getParent_dept_id();
   }
 }
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (isFinishing()) {
      return true;
    }

    if (keyCode == KeyEvent.KEYCODE_MENU) {}

    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
      LogFactory.d(TAG, "KEYCODE_BACK has clicked .");

      if (mStructNavView.getViewGroupChildCount() == 2) {
        mStructNavView.removeAllItemView();
        adapter.showChildNodes(rootNodeDept);
      } else {
        Node node = mStructNavView.getLastChildNode();
        if (node != null) {
          adapter.showChildNodes(node);
        } else {
          boolean keepOnline =
              (Boolean)
                  PreferenceManager.get(
                      Globe.SP_FILE, new Object[] {LoginActivity.LOGIN_KEEPONLINE, false});
          if (!keepOnline) {
            DialogFactory.promptExit(mContext).show();
          } else {
            IMOApp.getApp().hasRunInBackground = true;
            NoticeManager.updateRecoverAppNotice(notificationManager);
            Functions.backToDesk(this);
          }
        }
      }
      return true;
    }

    if (keyCode == KeyEvent.KEYCODE_SEARCH) {}

    return super.onKeyDown(keyCode, event);
  }
  /** 构建组织架构部门树 */
  private void buildOrganizeTree() {
    // 1-构建DeptNode
    if (mGlobal.deptid == null) {
      return;
    }

    for (int i = 0; i < mGlobal.deptid.length; i++) {
      int id = mGlobal.deptid[i];

      DeptMaskItem deptInfo = mGlobal.deptInfoMap.get(id);
      if (deptInfo == null) {
        IMOApp.getApp().turn2LoginForLogout();
        return;
      }
      Node deptNode = null;
      if (deptInfo.getDept_id() == 0) {
        deptNode = new Node(new NodeData("组织结构"));
      } else {
        deptNode = new Node(new NodeData(deptInfo.getName()));
      }
      deptNode.setId(deptInfo.getDept_id());
      deptNode.setDept(true);
      // if (currentDeptNeedHide(id))
      // deptNode.setNeedShow(false);
      nodeMap.put(deptInfo.getDept_id(), deptNode);
      deptNodeNextSiblingMap.put(deptInfo.getDept_id(), deptInfo.getNext_sibling());
      deptIdList.add(deptInfo.getDept_id());
    }

    for (int i = 0; i < mGlobal.deptid.length; i++) {
      int id = mGlobal.deptid[i];
      Node curDeptNode = nodeMap.get(id);
      if (id != 0) {
        DeptMaskItem deptInfo = mGlobal.deptInfoMap.get(id);

        int parentId = deptInfo.getParent_dept_id();
        Node parentNode = nodeMap.get(parentId);

        if (parentNode != null) {
          NodeManager.addChildNode(parentNode, curDeptNode);
        }

        int firstChildId = deptInfo.getFirst_child();
        if (firstChildId != -1) {
          // 添加child
          Node firstChildNode = nodeMap.get(firstChildId);
          NodeManager.addChildNode(curDeptNode, firstChildNode);
        }
      }
    }
    // 隐藏部门
    for (Integer did : IMOApp.getApp().hide_dept_ids) {
      if (nodeMap == null) break;
      Node node = nodeMap.get(did);
      if (node == null) continue;
      node.setNeedShow(false);
      ArrayList<Node> nodes = node.getChildNodes();
      for (Node node1 : nodes) {
        node1.setNeedShow(false);
      }
    }
    // 显示自己
    System.out.println("显示部门列表:" + Arrays.toString(special_hide_dept_ids.toArray()));
    for (Integer did : special_hide_dept_ids) {
      if (nodeMap == null) break;
      Node node = nodeMap.get(did);
      if (node == null) continue;
      node.setNeedShow(true);
    }

    Node rootNode = nodeMap.get(0);
    sortDeptNode(rootNode);
  }
  @Override
  protected void registerEvents() {
    String isFirstLoading =
        (String) PreferenceManager.get("IMOLoading", new String[] {"isFirstLoading", "no"});
    MainActivityGroup.getActivityGroup().updateTipShow(!isFirstLoading.equals("yes"));

    if (getTcpConnection() == null) {
      resetConnection();
      if (getTcpConnection() != null) {
        IMOApp.getDataEngine().addToObserverList(this);
      }
    } else {
      IMOApp.getDataEngine().addToObserverList(this);
    }

    // //1- 更新自己的状态 login over
    doRequestOwnState();
    // / 2- 发送CrashReport
    sendCrashMSG();

    getOrganizeTree();

    getContactTree();

    mTitleBar.setSystemSetListener(
        new OnTouchListener() {

          @Override
          public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              return true;
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
              SystemSetActivity.launch(OrganizeActivity.this);
              return true;
            }

            return true;
          }
        });

    mTitleBar.setFaceOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            UserConfigActivity.launch(mContext);
          }
        });

    // ///状态弹窗显示
    mTitleBar.setStateOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            mChangeStatePop.popUp(getWindow().getDecorView());
          }
        });

    mChangeStatePop.setListener(
        new OnStateClickListener() {

          @Override
          public void onClickAction() {
            Globe.canConnect = false;
            requestLogOut(false);
          }
        });

    mChangeStatePop.setReLoginListener(
        new OnStateClickListener() {

          @Override
          public void onClickAction() {
            if (EngineConst.isNetworkValid && EngineConst.isReloginSuccess) {
              return;
            } else if (ConnectionChangeReceiver.pingAddress()) {
              System.out.println("shoudong old connection id = " + EngineConst.IMO_CONNECTION_ID);
              EngineConst.isReloginSuccess = false;
              String oldConnectionID = EngineConst.IMO_CONNECTION_ID;

              EngineConst.IMO_CONNECTION_ID = EngineConst.GenerateRandomString();

              System.out.println(
                  "shoudong new connection id :"
                      + EngineConst.IMO_CONNECTION_ID
                      + ",old connectionID :"
                      + oldConnectionID);

              AppService.getService()
                  .setTcpConnection(
                      (TCPConnection)
                          AppService.getService()
                              .getNIOThreadInstance()
                              .newTCPConnection(
                                  EngineConst.IMO_CONNECTION_ID,
                                  EngineConst.IMO_SERVER_ADDRESS,
                                  true));

              AppService.getService().getNIOThreadInstance().release(oldConnectionID, false);

              ReloginOutPacket out =
                  new ReloginOutPacket(
                      ByteBuffer.wrap(EngineConst.sessionKey),
                      IMOCommand.IMO_GET_RELOGIN,
                      EngineConst.cId,
                      EngineConst.uId);
              AppService.getService()
                  .getNIOThreadInstance()
                  .send(EngineConst.IMO_CONNECTION_ID, out, false);
            }
          }
        });

    mSearchBar.setOnClickEvent();

    mSearchBar.setOnSearchListener(
        new OnSearchListener() {

          @Override
          public void onSearch(View v) {
            LogFactory.d(TAG, "Dynamic key = " + ((EditText) v).getText());

            doSearch(((EditText) v).getText().toString().trim());
          }

          private void doSearch(String key) {
            // 查询的结果UIDList
            update2State(true);
            // 数据库中查询结果
            ArrayList<Integer> deptUserId = IMOApp.imoStorage.search(key);

            if (deptUserId != null) {
              mSearchResultAdapter.setShowData(getSearchResult(deptUserId));
              mSearchRestltListView.setAdapter(mSearchResultAdapter);
            } else {
              mSearchResultAdapter.setEmpty();
            }
          }

          @Override
          public void initState() {
            update2State(false);
          }
        });

    mSearchRestltListView.setOnItemClickListener(
        new OnItemClickListener() {

          @Override
          public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
            if (mSearchResultAdapter.getItem(position).getId() == EngineConst.uId) {
              EmployeeDetailActivity.launch(mContext);

            } else {
              Intent intent = new Intent(mContext, DialogueActivity.class);
              Bundle data = new Bundle();
              Node curNode = mSearchResultAdapter.getItem(position);
              data.putInt("cid", curNode.getCid());
              data.putInt("uid", curNode.getId());
              data.putString("name", curNode.getNodeData().nodeName);
              data.putBoolean("sex", curNode.getNodeData().isBoy);
              startActivity(intent.putExtras(data));
            }
          }
        });
  }