private RegionManage()
        {
            List<DB_Talk.Model.m_Member> disPatchNumberList = new DB_Talk.BLL.m_Member().GetModelList(string.Format("boxID={0} and i_isdispatch=1 and i_Flag=0", Pub.manageModel.BoxID));
            if (disPatchNumberList.Count >= 2)
            {
                m_LeftDispatchNumber = new RegionCallInfo();
                m_LeftDispatchNumber.ID = disPatchNumberList[0].ID;
                m_LeftDispatchNumber.MemberType = (CommControl.PublicEnums.EnumRegionMemberType)disPatchNumberList[0].i_TellType;
                m_LeftDispatchNumber.IsCalling = false;
                m_LeftDispatchNumber.Name = disPatchNumberList[0].vc_Name;
                m_LeftDispatchNumber.PrimaryKey = disPatchNumberList[0].i_Number.ToString();
                m_LeftDispatchNumber.Number = disPatchNumberList[0].i_Number.ToString();
                this.RegeditMemberData(m_LeftDispatchNumber);
                //从原始结构中查找状态
                SingleUserControl baseControl = Pub._memberManage.GetSingleControl(Convert.ToInt64(Pub.manageModel.LeftDispatchNumber));
                m_LeftDispatchNumber.Name = baseControl.MemberName;
                m_LeftDispatchNumber.DestNumber = baseControl.PeerNumber;
                m_LeftDispatchNumber.UserLineStatus = baseControl.UserLineStatus;

                m_RightDispathchNumber = new RegionCallInfo();
                m_RightDispathchNumber.ID = disPatchNumberList[1].ID;
                m_RightDispathchNumber.MemberType = (CommControl.PublicEnums.EnumRegionMemberType)disPatchNumberList[1].i_TellType;
                m_RightDispathchNumber.IsCalling = false;
                m_RightDispathchNumber.Name = disPatchNumberList[1].vc_Name;
                m_RightDispathchNumber.PrimaryKey = disPatchNumberList[1].i_Number.ToString();
                m_RightDispathchNumber.Number = disPatchNumberList[1].i_Number.ToString();
                this.RegeditMemberData(m_RightDispathchNumber);
                //从原始结构中查找状态
                SingleUserControl rightControl = Pub._memberManage.GetSingleControl(Convert.ToInt64(Pub.manageModel.RightDispatchNumber));
                m_RightDispathchNumber.Name = baseControl.MemberName;
                m_RightDispathchNumber.DestNumber = baseControl.PeerNumber;
                m_RightDispathchNumber.UserLineStatus = baseControl.UserLineStatus;
            }
        }
 void frmFapMemberList_Load(object sender, EventArgs e)
 {
     List<DB_Talk.Model.m_Member> lstMemeber = new DB_Talk.BLL.m_Member().GetModelList(string.Format("i_Flag=0 and FapID={0} and BoxID={1}", _fapID, Global.Params.BoxID));
     
     foreach (DB_Talk.Model.m_Member item in lstMemeber)
     {
         dgvList.Rows.Add(item.i_Number, item.vc_Name);
     }
     tsbState.Text =string.Format("共{0}个手机",
         dgvList.Rows.Count.ToString());
 }
 private void btnDel_Click(object sender, EventArgs e)
 {
     if (dgvList.SelectedRows.Count > 0)
     {
         DB_Talk.Model.m_Box typeModel = (DB_Talk.Model.m_Box)dgvList.CurrentRow.Tag;
         if (typeModel != null)
         {
             if (CommControl.MessageBoxEx.MessageBoxEx.Show("确认要删除 【" + typeModel.vc_Name + "】 吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
             {
                 bool isExit_manager = new DB_Talk.BLL.m_Manager().Exists("BoxId='" + typeModel.ID + "'");
                 bool isExit_member = new DB_Talk.BLL.m_Member().Exists("BoxId='" + typeModel.ID + "'");
                 List<DB_Talk.Model.m_Group> lst = new DB_Talk.BLL.m_Group().GetModelList("i_Flag=0 and BoxId='" + typeModel.ID + "'");
                 bool isExit_group = false;
               
                 foreach (DB_Talk.Model.m_Group m in lst)
                 {
                     if (m.vc_Name != Global.Params.gruopNormalName)
                     {
                         isExit_group = true;
                         break;
                     }
                 }
                 bool isExit_CalledRule = new DB_Talk.BLL.m_CalledRule().Exists("BoxId='" + typeModel.ID + "' and i_Flag=0 and vc_CalledNumber!='*000'");
                 //bool isExit_group = new DB_Talk.BLL.m_Group().Exists("BoxId='" + typeModel.ID + "'");
                 if (isExit_manager || isExit_member || isExit_group || isExit_CalledRule)
                 //if (isExit_member)
                 {
                     CommControl.MessageBoxEx.MessageBoxEx.Show(Global.Params.BOXNAME + "已经被引用,不可以删除!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                     return;
                 }
                 if (new DB_Talk.BLL.m_Box().DeleteEx(typeModel.ID))
                 {
                     new DB_Talk.BLL.m_Group().Delete("i_Flag=0 and BoxId='" + typeModel.ID + "'");
                     CommControl.MessageBoxEx.MessageBoxEx.Show("删除成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                     CommControl.SystemLogBLL.WriteLog(Global.Params.UserID, typeModel.ID, CommControl.SystemLogBLL.EnumLogAction.Delete, "删除", "删除了站点:" + typeModel.vc_Name, "");
                     //.BLL.m_SystemLog.WriteLog(Global.Params.UserID, DB_FileManage.Model.m_SystemLog.EnumLogAction.Delete, "删除文件等级", "删除文件等级:" + typeModel.vc_Name);
                     LoadData();
                     Global.Params.LstBox.Remove(typeModel);
                     dr = DialogResult.OK;
                 }
                 else
                 {
                     CommControl.MessageBoxEx.MessageBoxEx.Show("删除失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 }
             }
         }
     }
     else
     {
         CommControl.MessageBoxEx.MessageBoxEx.Show("请选择要删除的" +Global.Params.BOXNAME, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
     }
 }
 //恢复出厂设置时清空数据库
 private bool ClearDispatchTell()
 {
     List<DB_Talk.Model.m_Member> lst = new DB_Talk.BLL.m_Member().GetModelList(" i_Flag=0 and BoxID='" + Global.Params.BoxID + "' and i_IsDispatch=1");
     foreach (DB_Talk.Model.m_Member m in lst)
     {
         //2013-6-13 修改,在删除前判断,存在的号码才删除(因为有时候数据库里面有的号码,box里面没有,直接删除会返回false)
         bool IsExist = MBoxSDK.ConfigSDK.MBOX_IsSubscriberExist(Global.Params.BoxHandle, m.i_Number.Value);
         if (IsExist)
         {
             if (MBoxSDK.ConfigSDK.MBOX_DeleteSubscriber(Global.Params.BoxHandle, (m.i_Number.Value)))
             {
                 new DB_Talk.BLL.m_Member().Delete(m.ID);
             }
             else
             {
                 return false;
             }
         }
     }
     return true;
 }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

           // Application.Run(new Form1());

           // Application.Run(new TalkLog());
            try
            {
               
                //new FormCallKeyborad(null).ShowDialog();
               // new Form1().ShowDialog();
                //单例模式
                bool bCreatedNew;
                System.Threading.Mutex mutex = new System.Threading.Mutex(false, Application.ProductName, out bCreatedNew);
                if (!bCreatedNew)
                {
                    CommControl.MessageBoxEx.MessageBoxEx.Show("程序已打开!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }


                //捕获程序级错误
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);

                Bestway.Windows.Forms.ProgressBarDialog procDlg = new Bestway.Windows.Forms.ProgressBarDialog(new FormWelcome());
                Form tempForm = new Form();
                tempForm.FormBorderStyle = FormBorderStyle.None;
                tempForm.Size = new System.Drawing.Size(1, 1);
                tempForm.Show();
                tempForm.Hide();
                //bool b = DB_Talk.DB.OpenDataBase("172.21.2.78\\hc", "MBoxOss", "Tester1", "User@1234", new ExecuteErrorEventHandler(OleDbHelper_ExecuteError));
                Pub._configModel = Config.GetModel();

                if (Pub._configModel.LocalIP == "127.0.0.1")
                {
                    IPHostEntry hostName = Dns.GetHostByName(Dns.GetHostName());
                    if (hostName.AddressList.Length > 0)
                    {
                        Pub._configModel.LocalIP = hostName.AddressList[0].ToString();
                        Config.WriteModel(Pub._configModel);
                    }
                }

                // bool b = DB_Talk.DB.OpenDataBase(Pub._configModel.DBServer, Pub._configModel.DBName, Pub._configModel.DBUserName, Pub._configModel.DBPassword, new ExecuteErrorEventHandler(OleDbHelper_ExecuteError));
                procDlg.Show(Bestway.Windows.Forms.EnumDisplayType.LoadData, "  正在连接数据库,请稍等...");
                if (OpenDataBase() == false)
                {
                    procDlg.Hide();
                    DialogResult dr = new DialogResult();
                    dr = (new frmDatabaseConfig()).ShowDialog();
                    if (dr == DialogResult.Cancel)
                    {
                        procDlg.Dispose();
                        return;
                    }
                }
                procDlg.Hide();

                if (Pub._configModel.IsAutoLogin)
                {
                    List<DB_Talk.Model.m_Manager> lst = new List<DB_Talk.Model.m_Manager>();
                    lst = new DB_Talk.BLL.m_Manager().GetModelList(string.Format("vc_UserName='******' and  i_Flag=0  ", "admin"));
                    Pub._configModel.LastUser = "******";
                    if (lst != null && lst.Count > 0)
                    {
                        Pub.manageModel = lst[0];

                        if (Pub.manageModel.i_Dispatch.Value != 1)
                        {
                            MessageBoxEx.Show("当前用户没有调度权限,请联系管理员!", "提示");
                            return;
                        }

                        Config.WriteModel(Pub._configModel);
                        //选择Box;
                        FormSelectBox fs = new FormSelectBox();
                        if (fs.LoadBoxList() == true)
                        {
                            fs.ShowDialog();
                        }
                        
                        if (Pub.manageModel.BoxID == null)
                        {
                            MessageBoxEx.Show("请先到网管程序配置语音调度交换机", "提示");
                            return;
                        }

                        DB_Talk.Model.m_Box boxModel = new DB_Talk.BLL.m_Box().GetModel(Pub.manageModel.BoxID.Value);
                        if (boxModel == null)
                        {
                            MessageBoxEx.Show("请到网管程序增加MBox设备!", "提示");
                            return;
                        }

                        ///添加调度号码,取调度的前两个

                        List<DB_Talk.Model.m_Member> lstM = new List<DB_Talk.Model.m_Member>();

                        lstM = new DB_Talk.BLL.m_Member().GetModelList(string.Format("boxID={0} and i_isdispatch=1 and i_Flag=0", Pub.manageModel.BoxID));
                        if (lstM.Count >= 2)
                        {
                            Pub.manageModel.LeftDispatchNumber = lstM[0].i_Number;
                            Pub.manageModel.LeftDispatchName = lstM[0].vc_Name;

                            Pub.manageModel.RightDispatchNumber = lstM[1].i_Number;
                            Pub.manageModel.RightDispatchName = lstM[1].vc_Name;
                        }
                        else
                        {
                            MessageBoxEx.Show("请到网管程序添加调度号码!", "提示");
                            return;
                        }

                        lstM = new DB_Talk.BLL.m_Member().GetModelList(string.Format("boxID={0} and i_isdispatch=2 and i_Flag=0", Pub.manageModel.BoxID));
                        if (lstM != null && lstM.Count > 0)
                        {
                            Pub.VideoNumber = lstM[0].i_Number.Value.ToString();
                            Pub.VideoPassword = lstM[0].i_NuPassword.ToString();
                        }
                        else
                        {
                            if (Pub._configModel.IsVideoCall)
                            {
                                MessageBoxEx.Show("请到网管程序添加视频调度号码!", "提示");
                                return;
                            }
                        }

                        if (Pub._configModel.IsVideoCall)
                        {
                            if (Pub._configModel.VideoSize<=0 || Pub._configModel.VideoSize>=10)
                            {
                                 MessageBoxEx.Show("请设置合适的视频大小!", "提示");
                                return;
                            }
                        }
                        if (boxModel.i_MaxMeetingMember != null)
                        {
                            Pub._maxMeetingMemberCount = boxModel.i_MaxMeetingMember.Value;
                        }
                        CommControl.SystemLogBLL.WriteLog(
                            Pub.manageModel.ID, Pub.manageModel.BoxID.Value, SystemLogBLL.EnumLogAction.SystemOperate, "登录", "登录成功", "");
                    }
                    else
                    {
                        MessageBoxEx.Show("请先到网管程序进行配置!", "提示");
                        return;
                    }
                }
                else
                {
                    FormLogin frmLogin = new FormLogin(FormLogin.EnumLoginType.Login);
                    if (frmLogin.ShowDialog() == DialogResult.Cancel)
                    {
                        procDlg.Dispose();
                        return;
                    }
                }
                Pub.CanDestroyControl = false;
                //frmLogin.Dispose();
                List<DB_Talk.Model.m_Member> lstMember = new DB_Talk.BLL.m_Member().GetModelList(string.Format("i_Flag=0 and BoxID={0} order by id", Pub.manageModel.BoxID.Value));

                if (lstMember.Count == 0)
                {
                    CommControl.MessageBoxEx.MessageBoxEx.Show("请先到网管软件增加用户", "提示");
                    return;
                }
                
                FormMain frmMain = new FormMain();
                //Form1 frmMain = new Form1();
                //frmMain.Width = 1;
                //frmMain.Height = 1;
                procDlg.Show(Bestway.Windows.Forms.EnumDisplayType.LoadData, "  正在初始化程序,请稍等...");

                frmMain.WindowState = FormWindowState.Normal;
                frmMain.Show();//为了让加载主窗体滚动条显示出来
                frmMain.Visible = false;
                Pub._pageControl = Pub._meetingManage.GetToSelectPageControl();
                if (Pub._pageControl == null)
                {
                    procDlg.Hide();
                    MessageBoxEx.Show("请先到网管程序增加电话号码!", "提示");
                    return;
                }
                

                frmMain.ShowLoadOk();
                frmMain.Visible = true;
                int tt = 10000;//当所有用户的信息都上报之后LstMember.cout会等于0,如果意外情况下Box内部没有上报数据库中的号码的话,这里执行10000次自动跳过
                while (FormMain._lstMember.Count>0 && tt>=0)
                {
                    tt--;
                    System.Threading.Thread.Sleep(1);
                    Application.DoEvents();
                }
                
                frmMain.SetDispatchAndLoadState();
                frmMain.WindowState = System.Windows.Forms.FormWindowState.Maximized;

                procDlg.Hide();
                procDlg.Dispose();
                Pub._memberManage.ClickTab();
                frmMain.imgBtnMeeting_Click(null, null);
                Pub._meetingManage.ClickTab();
               
                
                frmMain.imgBtnDispatch_Click(null, null);
                frmMain.SetSortButton();
                Pub.CanDestroyControl = true;
                frmMain.SetDefaultMemberGroupIndex();
                frmMain.SetMenuSelect();
                //new Form1().ShowDialog();
                Application.Run(frmMain);

            }
            catch (Exception ex)
            {
                CommControl.Tools.WriteLog.AppendLog("Main:" + ex.Message + ex.StackTrace);
                //MessageBoxEx.Show(ex.Message, "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Environment.Exit(0);
            }
        }
        /// <summary>
        ///  取IP广播板的IP地址
        /// </summary>
        /// <returns></returns>
        public List<string> GetBroadcastIP()
        {
            List<DB_Talk.Model.m_Member> lstMember = new DB_Talk.BLL.m_Member().GetModelList(
                string.Format("i_Flag=0 and i_IsDispatch=0 and BoxID={0} and i_TellType={1} order by id", Pub.manageModel.BoxID.Value,CommControl.PublicEnums.EnumTelType.广播.GetHashCode()));

            List<string> lst=lstMember.Select(p => p.vc_IP).ToList();
           //var   lstMember.Select(p => p.vc_IP);
           // foreach (var item in lstMember)
           // {
                
           // }
            return lst;
        }
        /// <summary>加载用户</summary>
        /// <param name="frm"></param>
        private void LoadMember()
        {
            //2014-11-11修改i_Dispatch=0,只显示正常号码,调度号和视频调度号不显示
            List<DB_Talk.Model.m_Member> lstMember = new DB_Talk.BLL.m_Member().GetModelList(string.Format("i_Flag=0 and i_IsDispatch=0 and BoxID={0} order by id",Pub.manageModel.BoxID.Value));

            //if (lstMember.Count == 0)
            //{
            //    CommControl.MessageBoxEx.MessageBoxEx.Show("请先到网管软件增加用户","提示");
            //    Application.Exit();
            //}

            PageControl pControl = new PageControl();
            _mainForm.superTabControlPanel5.Controls.Add(pControl);
            
            NormalGroupModel gModel = new NormalGroupModel();
            _lstGroup.Add(gModel);
            foreach (DB_Talk.Model.m_Member item in lstMember)
            {
                SingleUserControl s = new SingleUserControl();
                if (item.vc_Name!=null)
                {
                    s.MemberName = item.vc_Name.ToString();    
                }
                
                s.Number = item.i_Number.Value;
                s.ID = item.ID;
                if (item.LevelID!=null)
                {
                    s.MemberLevel = item.LevelID.Value;    
                }
                if (item.DepartmentID!=null)
                {
                    s.DepartmentID = item.DepartmentID.Value;
                }

                if (item.i_TellType != null )
                {
                    s.TellType = (CommControl.PublicEnums.EnumTelType)item.i_TellType.Value;
                }

                s.BackColor = Color.BlueViolet;
                if (s.Number != Pub.manageModel.LeftDispatchNumber.Value && s.Number != Pub.manageModel.RightDispatchNumber.Value)
                {
                    gModel.lstControl.Add(s);
                    s.Click += new EventHandler(_mainForm.single_Click);
                }
                else
                {

                }
            }

            gModel.PageControl = pControl;
            pControl.Init(gModel.lstControl);
            pControl.Dock = DockStyle.Fill;

            NormalGroupModel dispatchsModel = new NormalGroupModel();
            _lstGroup.Add(dispatchsModel);
            if (Pub.manageModel.LeftDispatchNumber!=null)
            {
                _mainForm.cLeft.Number = Pub.manageModel.LeftDispatchNumber.Value;
                _mainForm.cLeft.UserLineStatus = TalkControl.EnumUserLineStatus.Offline;
            }
            
            //_mainForm.cLeft.Name = "左席";
            _mainForm.cLeft.MemberName = Pub.manageModel.LeftDispatchName;
            _mainForm.cLeft.IsDispatch = true;

            dispatchsModel.lstControl.Add(_mainForm.cLeft);

            if (Pub.manageModel.RightDispatchNumber!=null)
            {
                _mainForm.cRight.Number = Pub.manageModel.RightDispatchNumber.Value;
                _mainForm.cRight.UserLineStatus = TalkControl.EnumUserLineStatus.Offline;
            }
            
            //_mainForm.cRight.Name = "右席";
            _mainForm.cRight.MemberName = Pub.manageModel.RightDispatchName;
            _mainForm.cRight.IsDispatch = true;
            dispatchsModel.lstControl.Add(_mainForm.cRight);
            Pub.SetSupperTabColor(_mainForm.stiAllMember);
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (_erroLoingCount <= 0)
            {
                this.Close();
                return;
            }

            List<DB_Talk.Model.m_Manager> lst=new List<DB_Talk.Model.m_Manager>();
            try
            {
                lst = new DB_Talk.BLL.m_Manager().GetModelList(string.Format("vc_UserName='******' and  i_Flag=0 and vc_Password='******'", txtUser.Text, txtPass.Text));
            }
            catch (Exception)
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
                return;
            }
            

            if (lst.Count > 0)
            {
                Pub.manageModel = lst[0];
                if (_type== EnumLoginType.Out && Pub.manageModel.BoxID==null)
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                    return;
                }
                
                if (Pub.manageModel.i_Dispatch.Value!=1)
                {
                     MessageBoxEx.Show("当前用户没有调度权限,请联系管理员!", "提示");
                    return;
                }
                //选择Box;
                FormSelectBox fs = new FormSelectBox();
                if (fs.LoadBoxList() == true)
                {
                    fs.ShowDialog();
                }
                        

                if (Pub.manageModel.BoxID == null )
                {
                    MessageBoxEx.Show("请到网管程序修改相应权限!", "提示");
                    return;
                }

                DB_Talk.Model.m_Box boxModel = new DB_Talk.BLL.m_Box().GetModel(Pub.manageModel.BoxID.Value);
                if (boxModel == null)
                {
                    MessageBoxEx.Show("请到网管程序增加MBox设备!", "提示");
                    return;
                }
                #region 添加调度号码,取调度的前两个

               
                ///

                List<DB_Talk.Model.m_Member> lstMember = new List<DB_Talk.Model.m_Member>();

                lstMember = new DB_Talk.BLL.m_Member().GetModelList(string.Format("boxID={0} and i_isdispatch=1 and i_Flag=0", Pub.manageModel.BoxID));
                if (lstMember.Count >= 2)
                {
                    Pub.manageModel.LeftDispatchNumber = lstMember[0].i_Number;
                    Pub.manageModel.LeftDispatchName = lstMember[0].vc_Name;

                    Pub.manageModel.RightDispatchNumber = lstMember[1].i_Number;
                    Pub.manageModel.RightDispatchName= lstMember[1].vc_Name;
                }
                else
                {
                    MessageBoxEx.Show("请到网管程序添加调度号码!", "提示");
                    return;
                }
                #endregion

                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                Pub._configModel.LastUser = txtUser.Text;
                Config.WriteModel(Pub._configModel);
                
                switch (_type)
                {
                    case EnumLoginType.Login:
                        CommControl.SystemLogBLL.WriteLog(
                            Pub.manageModel.ID, Pub.manageModel.BoxID.Value, SystemLogBLL.EnumLogAction.SystemOperate, "登录", "登录成功", "");
                        break;
                    case EnumLoginType.Out:
                        CommControl.SystemLogBLL.WriteLog(
                            Pub.manageModel.ID, Pub.manageModel.BoxID.Value, SystemLogBLL.EnumLogAction.SystemOperate, "退出", "退出成功", "");
                        break;
                    case EnumLoginType.Lock:
                        break;
                    default:
                        break;
                }
            }
            else
            {
                switch (_type)
                {
                    case EnumLoginType.Login:
                        MessageBoxEx.Show("登录失败", "登录");
                        break;
                    case EnumLoginType.Out:
                        MessageBoxEx.Show("退出失败", "退出");
                        break;
                    case EnumLoginType.Lock:
                        MessageBoxEx.Show("解锁失败", "解锁");
                        break;
                    default:
                        break;
                }
                _erroLoingCount--;
            }
        }
 //判断关联号码
 private void CheckAssociateNum(string AssociateNum)
 {
     List<DB_Talk.Model.m_Member> lst = new List<DB_Talk.Model.m_Member>();
     //box要存在
     lst = new DB_Talk.BLL.m_Member().GetModelList(string.Format(" i_flag=0 and i_IsDispatch=0 and BoxID='{0}' " +
                    " and i_Number='{1}'", Global.Params.BoxID, AssociateNum));
     if (lst.Count > 0)
     {
     }
     else
         throw new Exception("关联号码【" + AssociateNum + "】不存在");
     //只能用一次
     lst = new DB_Talk.BLL.m_Member().GetModelList(string.Format(" i_flag=0 and i_IsDispatch=0 and BoxID='{0}' "+
                     " and i_AssociateNum1='{1}' or i_AssociateNum2='{1}'", Global.Params.BoxID, AssociateNum));
     if (lst.Count > 0)
         throw new Exception("号码【" + AssociateNum + "】已经和号码【"+lst[0].i_Number+"】互为关联号码");
    
 }
        private void RemoveAssociateNum(DB_Talk.Model.v_Member vmodel)
        {
            List<DB_Talk.Model.m_Member> lst = new List<DB_Talk.Model.m_Member>();
            string strW = string.Format(" i_flag=0 and i_IsDispatch=0 and BoxID='{0}' ", Global.Params.BoxID);
            if (vmodel.i_AssociateNum1 > 0)
                strW = strW + string.Format(" and i_Number='{0}'", vmodel.i_AssociateNum1);
            if (vmodel.i_AssociateNum2 > 0)
                strW = strW + string.Format(" or i_Number='{0}'", vmodel.i_AssociateNum2);
            if (vmodel.i_AssociateNum1 > 0 || vmodel.i_AssociateNum2 > 0)
               lst = new DB_Talk.BLL.m_Member().GetModelList(strW);
            foreach(DB_Talk.Model.m_Member item in lst)
            {
                item.i_AssociateNum1 = 0;
                item.i_AssociateNum2 = 0;
                item.i_IsAssociateActive = 0;  //取消被动关联
                item.i_supplementSerive &= (uint)(~MBoxSDK.ConfigSDK.SPM_ASSO_NUM);  //去关联
                new DB_Talk.BLL.m_Member().Update(item);
            }

        }
 private void btnAdd_Click(object sender, EventArgs e)
 {
     if (!IsSetBoxNumLenAndHead())
     {
         CommControl.MessageBoxEx.MessageBoxEx.Show("还未进行基本设置,不能执行添加操作!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
         return;
     }
     
     DB_Talk.BLL.m_Member _BLL = new DB_Talk.BLL.m_Member();
     List<DB_Talk.Model.m_Member> list = new List<DB_Talk.Model.m_Member>();
     list = _BLL.GetModelList(string.Format(" i_flag=0 and BoxID='{0}'", Global.Params.BoxID));
     if (list.Count >= Global.Params.MaxBoxMemberCount)
     {
         CommControl.MessageBoxEx.MessageBoxEx.Show(string.Format("不能添加,号码已经达到最大限制,【{0}】个!", Global.Params.MaxBoxMemberCount), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
         return;
     }
     UI.frmMember frm = new UI.frmMember(null, 0);
     frm.ShowDialog();
     if(frm.DialogResult==DialogResult.OK)
        LoadData("");
 
 }
        //CommControl.MessageBoxEx.MessageBoxEx messagebox;
        private void btnOK_Click(object sender, EventArgs e)
        {
            DB_Talk.BLL.m_Member _BLL = new DB_Talk.BLL.m_Member();
            List<DB_Talk.Model.m_Member> listCount = new List<DB_Talk.Model.m_Member>();
            listCount = _BLL.GetModelList(string.Format(" i_flag=0 and BoxID='{0}'", Global.Params.BoxID));
            if (listCount.Count >= Global.Params.MaxBoxMemberCount)
            {
                CommControl.MessageBoxEx.MessageBoxEx.Show(string.Format("不能导入,号码已经达到最大限制,【{0}】个!", Global.Params.MaxBoxMemberCount), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Bestway.Windows.Forms.ProgressBarDialog procDlg = null;
            procDlg = new Bestway.Windows.Forms.ProgressBarDialog();
            try
            {
                procDlg.Show(Bestway.Windows.Forms.EnumDisplayType.LoadData, "      正在导入用户,请稍等...");
                DataTable dt = new DataTable();
                dt = (DataTable)dgvList.DataSource;
                if (dt == null)
                {
                    throw new Exception("没有数据!");
                    
                }
                DB_Talk.BLL.m_Member bll = new DB_Talk.BLL.m_Member();
                StringBuilder sbAdd = new StringBuilder();
                List<DB_Talk.Model.m_Member> listAdd = new List<DB_Talk.Model.m_Member>();

                StringBuilder sbNotAdd = new StringBuilder();
                StringBuilder sbAdded = new StringBuilder();     //box中已经存在的
                StringBuilder sbBoxMaxNotAdded = new StringBuilder();  //box到达最大值未添加的
                //List<DB_Talk.Model.m_Member> list = (List < DB_Talk.Model.m_Member >)dgvListOk.DataSource;
                List<DB_Talk.Model.m_Member> list = DataTableToModelList(dt);

                int iAdd=0,iAdded = 0;  //添加成功数,已经存在的数
                int iRepeatIP=0;  //IP已经存在的
                int iNotAdd = 0;     //添加失败数
                int iBoxMaxNotAdded = 0;    //到达最大后的用户
                if (dt.Rows.Count == 0)
                {
                    throw new Exception("没有数据可以导入!");
                }
                if (list.Count == 0)
                {
                    throw new Exception("没有合法的数据可以导入!");
                }

                foreach (DB_Talk.Model.m_Member item in list)
                {
                    if (listCount.Count + iAdded >= Global.Params.MaxBoxMemberCount)  //到达最大值
                    {
                        iBoxMaxNotAdded++;
                        sbBoxMaxNotAdded.Append("," + item.i_Number);

                    }
                    else
                    {
                        string strW = " i_Flag=0 and BoxID='" + Global.Params.BoxID + "'";
                        //strW += " and vc_Name='" + item.vc_Name + "'";
                        strW += " and i_Number='" + item.i_Number + "'";

                       

                        bool IsExist = MBoxSDK.ConfigSDK.MBOX_IsSubscriberExist(Global.Params.BoxHandle,(item.i_Number.Value));
                        CommControl.Tools.WriteLog.AppendLog("box添加号码", "boxHandle:" + Global.Params.BoxHandle + ", 号码:" + Convert.ToInt32(item.i_Number.ToString()) + ", 是否存在:" + IsExist);
          
                        if (bll.Exists(strW) || IsExist)
                            //MBoxSDK.ConfigSDK.MBOX_IsSubscriberExist(Global.Params.BoxHandle, Convert.ToInt32(item.i_Number.ToString())))
                        {
                            iAdded++;
                            sbAdded.Append("," + item.i_Number);//.vc_Name);
                        }
                        else if (item.i_TellType.Value == PublicEnums.EnumTelType.广播.GetHashCode() &&
                          _BLL.GetModelList(string.Format(" i_flag=0 and  vc_IP='{0}' and BoxID='{1}'", item.vc_IP, item.BoxID)).Count > 0)
                        {
                           //(string.Format("数据库中IP【{0}】已存在!", item.i_Number)
                            iRepeatIP++;
                        }
                        else
                        {
                            item.i_supplementSerive = (int)(MBoxSDK.ConfigSDK.SPM_MISS_CALL |
                                                            MBoxSDK.ConfigSDK.SPM_MISS_CALL_ON_BUSY |
                                                            MBoxSDK.ConfigSDK.SPM_SMS |
                                                            MBoxSDK.ConfigSDK.SPM_THREE_PARTY |
                                                            MBoxSDK.ConfigSDK.SPM_CALL_WAITING |
                                                            MBoxSDK.ConfigSDK.SPM_CALL_TRANSFER); // |
                                                           // MBoxSDK.ConfigSDK.SPM_CALL_PICKUP);
                            bool create= new frmMember(null, 0).AddBase(item);
                            //bool create =  MBoxSDK.ConfigSDK.MBOX_CreateSubscriber(Global.Params.BoxHandle,ref subscriberBase);
                            if (create)
                            //MBoxSDK.ConfigSDK.MBOX_CreateSubscriber(Global.Params.BoxHandle, Convert.ToInt32(item.i_Number.ToString())))
                            {
                                listAdd.Add(item);
                                //bll.Add(item);
                                //CommControl.SystemLogBLL.WriteLog(Global.Params.UserID, Global.Params.BoxID, CommControl.SystemLogBLL.EnumLogAction.Add, "导入", "导入了人员:" + item.vc_Name, "");
                                sbAdd.Append("," + item.i_Number);

                                iAdd++;
                                procDlg.Show(Bestway.Windows.Forms.EnumDisplayType.LoadData, "      用户【" + item.vc_Name + "】正在写入硬件,请稍等...");
                            }
                            else
                            {
                                sbNotAdd.Append("," + item.i_Number); //.vc_Name);
                                iNotAdd++;

                            }
                        }
                    }
                }
                string mes = "";
                bool bSave = false;
                if (iAdd > 0)
                {
                    TimeSpan sp = new TimeSpan(0);
                    DateTime dtstart = System.DateTime.Now;
                    bSave = MBoxSDK.ConfigSDK.MBOX_SaveHaveDoneCfg(Global.Params.BoxHandle); //保存更改
                    DateTime dtEnd = System.DateTime.Now;
                    if (bSave)
                    {
                        sp = dtEnd - dtstart;
                        //CommControl.MessageBoxEx.MessageBoxEx.Show(sp.TotalMilliseconds.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    //sbAdd.Remove(0, 1);
                }
                if (bSave)
                {
                    foreach (DB_Talk.Model.m_Member item in listAdd)
                    {
                        procDlg.Show(Bestway.Windows.Forms.EnumDisplayType.LoadData, "      用户【" + item.vc_Name + "】加入数据库,请稍等...");
                     
                        bll.Add(item);
                        CommControl.SystemLogBLL.WriteLog(Global.Params.UserID, Global.Params.BoxID, CommControl.SystemLogBLL.EnumLogAction.Add, "导入", "导入了人员:" + item.vc_Name, "");
                    }
                           
                    if (iAdd > 10)
                    {
                        mes = "共导入【" + iAdd + "】个用户!\r\n";
                    }
                    else if (iAdd > 0 && iAdd <= 10)
                    {
                        sbAdd.Remove(0, 1);
                        mes = "号码【" + sbAdd.ToString() + "】导入成功!\r\n";
                    }

                }
                else if (iAdd!=0)
                {
                    mes = "保存硬件配置失败!\r\n";
                }

                if (iNotAdd > 10)
                {
                    mes += "【" + iNotAdd + "】个号码写入硬件失败!\r\n";
                }
                else if (iNotAdd > 0 && iNotAdd <= 10)
                {
                    sbNotAdd.Remove(0, 1);
                    mes += "号码【" + sbNotAdd.ToString() + "】写入硬件失败!\r\n";
                }

                if (iAdded > 10)
                {
                    mes += "【" + iAdded + "】个号码已经存在,不再导入!\r\n";
                }
                else if (iAdded > 0 && iAdded <= 10)
                {
                    sbAdded.Remove(0, 1);
                    mes += "号码【" + sbAdded.ToString() + "】已经存在,不再导入!\r\n";
                }
                if(iBoxMaxNotAdded>5)
                {
                    mes += "设备中号码已经达到最大值,【" + iBoxMaxNotAdded + "】个号码,不再导入!";
                }
                else if (iBoxMaxNotAdded > 0 && iBoxMaxNotAdded <= 5)
                {
                    sbBoxMaxNotAdded.Remove(0, 1);
                    mes += "设备中号码已经达到最大值,号码【" + sbBoxMaxNotAdded + "】,不再导入!";
                }
                if (iRepeatIP>0)
                {
                    mes += "【" + iRepeatIP + "】个重复IP,不再导入!";
                }

                procDlg.Dispose();
                if (mes.Length > 0)
                {
                    CommControl.MessageBoxEx.MessageBoxEx.Show(mes, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                procDlg.Dispose();
                CommControl.MessageBoxEx.MessageBoxEx.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
           
            
           
         }
        private void GetModel()
        {
            _mModel.BoxID = Global.Params.BoxID;
            
            _mModel.vc_Name = txtName.Text.Trim();
            if (txtName.Enabled==true && _mModel.vc_Name == "")
            {
                txtName.Focus();
                throw new Exception("用户名称不可以为空");
            }
            if (_mModel.vc_Name.IndexOf("'") >= 0)
            {
                txtName.Focus();
                throw new Exception("名称中不可以有特殊字符");
            }
            /*
            if (_mModel.DepartmentID == null)
            {
                throw new Exception("请选择部门");
            }
            */
            if (txtTel.Text.Trim() == "" || int.Parse(txtTel.Text.Trim()) == 0 )
            {
                txtTel.Focus();
                throw new Exception("电话号码不可以为空或零");
            }

            string str = txtTel.Text.Trim().Substring(0,1);
            if (txtTel.Text.Trim().Length != Global.Params.NumberLen || CheckNumberRule(txtTel.Text.Trim(), Global.Params.strNumHead)==false)   
            {
                txtTel.Focus();
                string mes = Global.Params.strNumHead.Replace(",", "或");
                throw new Exception("用户号码长度必须是【" + Global.Params.NumberLen + "】位,且以数字【" + mes + "】开头");
                
            }

            DB_Talk.Model.m_Box modelBox = new DB_Talk.BLL.m_Box().GetModel(Global.Params.BoxID);
            if (modelBox != null)
            {
                if (modelBox.i_DispatchNumber == int.Parse(txtTel.Text.Trim()))
                {
                    throw new Exception("用户号码不能和调度号码(" + modelBox.i_DispatchNumber + ")相同!");
                }
                if (modelBox.i_EmergencyNumber == int.Parse(txtTel.Text.Trim()))
                {
                    throw new Exception("用户号码不能和紧急号码(" + modelBox.i_EmergencyNumber+ ")相同!");
                }
            }
            //if (txtTel.Text.Replace(" ", "").Length != Global.Params.NumberLen)
            //{
            //    txtTel.Focus();
            //    throw new Exception("电话号码必须是: "+Global.Params.NumberLen+" 位");
            //}

            _mModel.i_Number = int.Parse(txtTel.Text.Replace(" ", "").Trim());


            if (cmbNoType.SelectedValue.ToString() != CommControl.PublicEnums.EnumTelType.G3G手机.GetHashCode().ToString())
            {
                if (_mModel.i_NuPasswordType == null)
                    throw new Exception("请选择密码模式");
                if (_mModel.i_NuPasswordType == PublicEnums.EnumTelPasswordType.增加.GetHashCode())
                {
                    _mModel.i_NuPassword = (UInt64)_mModel.i_Number;
                }
                else
                {
                    if (txtPassword.Text.Trim() == "")
                    {
                        txtPassword.Focus();
                        throw new Exception("当密码模式为固定时,用户密码不能为空");
                    }
                    _mModel.i_NuPassword = UInt64.Parse(txtPassword.Text.Trim());
                    //UInt64 pasw = 0;
                    //if (UInt64.TryParse(txtPassword.Text.Trim(), out pasw) && pasw > 100 && pasw<=999999999999)
                    //    //pasw.ToString().Length >= 3 && pasw.ToString().Length <= 12)
                    //    _mModel.i_NuPassword = pasw;
                    //else
                    //    throw new Exception("用户密码必须是100~999999999999位之间的数字");
                    //    //throw new Exception("用户密码长度必须在3~12位之间,且大于零");
                }
            }
            else
            {
                _mModel.i_NuPasswordType=0;
                _mModel.i_NuPassword = 0;
            }

            if (_mModel.NumberTypeID == null)
            {
                throw new Exception("请选择号码类别");
            }
          
            _mModel.vc_MAC = txtMAC.Text.Trim();
            //if (_mModel.vc_MAC == "")
            //{
            //    txtMAC.Focus();
            //    throw new Exception("MAC不可以为空");
            //}
            if (_mModel.vc_MAC.IndexOf("'") >= 0)
            {
                txtName.Focus();
                throw new Exception("MAC中不可以有特殊字符");
            }

            if (txtTelEnd.Text.Trim() != "")
            {
                string strEnd = txtTelEnd.Text.Trim().Substring(0, 1);
                if (txtTelEnd.Text.Trim().Length != Global.Params.NumberLen || Global.Params.strNumHead.IndexOf(str) < 0)
                {
                    txtTelEnd.Focus();
                    string mes = Global.Params.strNumHead.Replace(",", "或");
                    throw new Exception("用户号码长度必须是【" + Global.Params.NumberLen + "】位,且以数字【" + mes + "】开头");

                }

                addCount =Int64.Parse(txtTelEnd.Text.Trim()) -_mModel.i_Number.Value;
                if (addCount < 0)
                {
                    txtTelEnd.Focus();
                    throw new Exception("终止号码不可以小于起始号码");
                }
                else 
                {
                    DB_Talk.BLL.m_Member _BLL = new DB_Talk.BLL.m_Member();
                    List<DB_Talk.Model.m_Member> listCount = new List<DB_Talk.Model.m_Member>();
                    listCount = _BLL.GetModelList(string.Format(" i_flag=0 and BoxID='{0}'", Global.Params.BoxID));
                    if (listCount != null && (addCount > Global.Params.MaxBoxMemberCount - listCount.Count))
                    {
                        throw new Exception(string.Format("终止号码过大,最多还能添加【{0}】个号码!", Global.Params.MaxBoxMemberCount-listCount.Count));
                    }
                }

              
               
            }


            if (txtIP1.Enabled)
            {
                if (txtIP1.Text=="" || txtIP2.Text=="")
                {
                    throw new Exception("起始或者终止IP地址不能为空!");
                }

                bool b = IsSameLanNet(IPAddress.Parse(txtIP1.Text.Trim()), IPAddress.Parse(txtIP2.Text.Trim()));
                if (!b)
                {
                     throw new Exception("起始IP与终止IP不在一个网段");
                }

                string[] IP1 = txtIP1.Text.Trim().Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                string[] IP2 = txtIP2.Text.Trim().Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                int addCountIP = int.Parse(IP2[3]) - int.Parse(IP1[3]);
                if (addCountIP < 0)
                {
                    txtIP2.Focus();
                    throw new Exception("终止IP不可以小于起始IP");
                }
                if (addCount==0 && addCountIP>0)
                {
                    throw new Exception("起始IP与终止IP不同时,终止号码不能为空!\n\n且增加号码个数与IP个数必须相同");                    
                }
                else if (addCount!=addCountIP)
                {
                    throw new Exception("增加的号码个数与IP个数不一致");                    
                }
                _mModel.vc_IP = txtIP1.Text.Trim();

            }

            if (_mModel.i_TellType == CommControl.PublicEnums.EnumTelType.G3G手机.GetHashCode()
                && txtUmtsImsi.Text.Trim()=="")
            {
                throw new Exception("3G号码标示码不能为空");
            }
            _mModel.vc_UmtsImsi = txtUmtsImsi.Text.Trim();

            _mModel.vc_Memo = txtMemo.Text.Trim();
            if (_mModel.vc_Memo.IndexOf("'") >= 0)
            {
                txtMemo.Focus();
                throw new Exception("备注中不可以有特殊字符");
            }

            if (groupBoxG.Visible == true)
            {
                if (chkUnCForward.Checked && txtUnCForward.Text == "")
                {
                    txtUnCForward.Focus();
                    throw new Exception("请设置无条件呼叫前转号码");
                }
                else if (txtUnCForward.Text != "")
                {
                    if (txtUnCForward.Text.Trim() == txtTel.Text.Trim())
                    {
                        txtUnCForward.Focus();
                        throw new Exception("无条件呼叫前转号码不能与自身号码相同");
                    }
                    _mModel.i_UnCForwardNu = int.Parse(txtUnCForward.Text);
                }
                else
                {
                    _mModel.i_UnCForwardNu = 0;
                }


                if (chkNoAnswerForward.Checked && txtNoAnswerForward.Text == "")
                {
                    txtNoAnswerForward.Focus();
                    throw new Exception("请设置无应答呼叫前转号码");
                }
                else if (txtNoAnswerForward.Text != "")
                {
                    if (txtNoAnswerForward.Text.Trim() == txtTel.Text.Trim())
                    {
                        txtNoAnswerForward.Focus();
                        throw new Exception("无应答呼叫前转号码不能与自身号码相同");
                    }
                    _mModel.i_NoAnswerForward = int.Parse(txtNoAnswerForward.Text);
                }
                else
                {
                    _mModel.i_NoAnswerForward = 0;
                }


                if (chkBusyForward.Checked && txtBusyForward.Text == "")
                {
                    txtBusyForward.Focus();
                    throw new Exception("请设置遇忙前转号码");
                }
                else if (txtBusyForward.Text != "")
                {
                    if (txtBusyForward.Text.Trim() == txtTel.Text.Trim())
                    {
                        txtBusyForward.Focus();
                        throw new Exception("遇忙转接号码不能与自身号码相同");
                    }
                    _mModel.i_BusyForward = int.Parse(txtBusyForward.Text);
                }
                else
                {
                    _mModel.i_BusyForward = 0;
                }

                if (chkPowerOffForward.Checked && txtPowerOffForward.Text == "")
                {
                    txtPowerOffForward.Focus();
                    throw new Exception("请设置关机前转号码");
                }
                else if (txtPowerOffForward.Text != "")
                {
                    if (txtPowerOffForward.Text.Trim() == txtTel.Text.Trim())
                    {
                        txtPowerOffForward.Focus();
                        throw new Exception("关机前转号码不能与自身号码相同");
                    }
                    _mModel.i_PowerOffForward = int.Parse(txtPowerOffForward.Text);
                }
                else
                {
                    _mModel.i_PowerOffForward = 0;
                }


                if (chkDirectNum.Checked && txtDirectNum.Text == "")
                {
                    txtDirectNum.Focus();
                    throw new Exception("请设置直通号码");
                }
                else if (txtDirectNum.Text != "")
                {
                    if (txtDirectNum.Text.Trim() == txtTel.Text.Trim())
                    {
                        txtDirectNum.Focus();
                        throw new Exception("直播号码不能与自身号码相同");
                    }
                    _mModel.i_DirectNum = int.Parse(txtDirectNum.Text);

                }
                else
                {
                    _mModel.i_DirectNum = 0;
                }


                if (chkAssociateNum1.Checked && txtAssociateNum1.Text == "")
                {
                    txtAssociateNum1.Focus();
                    throw new Exception("请设置关联号码1");
                }
                else if (txtAssociateNum1.Text != "")
                {
                    if (  _mModel.i_AssociateNum1 != int.Parse(txtAssociateNum1.Text))
                    {
                        _mModel.i_AssociateNum1 = int.Parse(txtAssociateNum1.Text);
                        CheckAssociateNum(_mModel.i_AssociateNum1.ToString());
                    }
                }
                else
                {
                    _mModel.i_AssociateNum1 = 0;
                }


                if (chkAssociateNum2.Checked && txtAssociateNum2.Text == "")
                {
                    txtAssociateNum2.Focus();
                    throw new Exception("请设置关联号码2");
                }
                else if (txtAssociateNum2.Text != "")
                {
                    _mModel.i_AssociateNum2 = int.Parse(txtAssociateNum2.Text);
                    CheckAssociateNum(_mModel.i_AssociateNum2.ToString());
                }
                else
                {
                    _mModel.i_AssociateNum2 = 0;
                }

                if (txtAssociateNum1.Text.Trim() != "" && txtAssociateNum2.Text.Trim() != "" && txtAssociateNum1.Text.Trim() == txtAssociateNum2.Text.Trim())
                {
                    txtAssociateNum2.Focus();
                    throw new Exception("两个关联号码不能相同");
                }

            }
        }
        private void RemoveAssociateNum(DB_Talk.Model.m_Member m) //string UnactiveAssociateNum)  //被动关联的号码
        {
            List<DB_Talk.Model.m_Member> lst = new List<DB_Talk.Model.m_Member>();
            string strW = string.Format(" i_flag=0 and i_IsDispatch=0 and BoxID='{0}' and i_IsAssociateActive=1", Global.Params.BoxID);
            if(m.i_AssociateNum1>0)
                strW = strW + string.Format(" and i_Number='{0}'", m.i_AssociateNum1);
            if (m.i_AssociateNum2 > 0)
                strW = strW + string.Format(" or i_Number='{0}'", m.i_AssociateNum2);

            lst = new DB_Talk.BLL.m_Member().GetModelList(strW);
            if (lst.Count > 0)
            {
                if (ModifyDetailAssociateNum(lst[0].i_Number.Value))
                {
                }
                   // UpdateAssociateNum(lst[0]);
                //lst[0].i_AssociateNum1 = model.i_Number;
                //lst[0].i_AssociateNum2 = model.i_AssociateNum2;
                //lst[0].i_IsAssociateActive = 2;  //被动关联
                //new DB_Talk.BLL.m_Member().Update(lst[0]);
            }
        }
        //更新被关联的号码
        private void UpdateAssociateNum(DB_Talk.Model.m_Member model)
        {
                DB_Talk.Model.m_Member m = new DB_Talk.BLL.m_Member().GetModel(string.Format(" i_flag=0 and i_IsDispatch=0 and BoxID='{0}' " +
                               " and i_Number='{1}'", Global.Params.BoxID, model.i_Number));
                if (m != null)
                {
                    if (model.i_AssociateNum1 > 0 || model.i_AssociateNum2 > 0)
                    {
                        m.i_IsAssociateActive = 1;   //主动关联
                    }
                    else
                    {
                        m.i_IsAssociateActive = 0;   //取消关联
                    }
                    new DB_Talk.BLL.m_Member().Update(m);
                }



                if (model.i_AssociateNum1 > 0)
                {
                    List<DB_Talk.Model.m_Member> lst = new List<DB_Talk.Model.m_Member>();
                    lst = new DB_Talk.BLL.m_Member().GetModelList(string.Format(" i_flag=0 and i_IsDispatch=0 and BoxID='{0}' " +
                                   " and i_Number='{1}'", Global.Params.BoxID, model.i_AssociateNum1));
                    if (lst.Count > 0)
                    {
                        lst[0].i_AssociateNum1 = model.i_Number;
                        lst[0].i_AssociateNum2 = model.i_AssociateNum2;
                        lst[0].i_IsAssociateActive = 2;  //被动关联
                        lst[0].i_supplementSerive |= (int)(MBoxSDK.ConfigSDK.SPM_ASSO_NUM);  //关联
                        new DB_Talk.BLL.m_Member().Update(lst[0]);
                    }

                }
                else
                {
                    if (_mPreModel.i_AssociateNum1 > 0)
                    {
                        List<DB_Talk.Model.m_Member> lst = new List<DB_Talk.Model.m_Member>();
                        lst = new DB_Talk.BLL.m_Member().GetModelList(string.Format(" i_flag=0 and i_IsDispatch=0 and BoxID='{0}' " +
                                       " and i_Number='{1}'", Global.Params.BoxID, _mPreModel.i_AssociateNum1));
                        if (lst.Count > 0)
                        {
                            lst[0].i_AssociateNum1 = 0;
                            lst[0].i_AssociateNum2 = 0;
                            lst[0].i_IsAssociateActive = 0;  //取消被动关联
                            lst[0].i_supplementSerive &= (uint)(~MBoxSDK.ConfigSDK.SPM_ASSO_NUM);  //去关联
                            new DB_Talk.BLL.m_Member().Update(lst[0]);
                        }
                    }
                }
                if (model.i_AssociateNum2 > 0)
                {
                    List<DB_Talk.Model.m_Member> lst = new List<DB_Talk.Model.m_Member>();
                    lst = new DB_Talk.BLL.m_Member().GetModelList(string.Format(" i_flag=0 and i_IsDispatch=0 and BoxID='{0}' " +
                                   " and i_Number='{1}'", Global.Params.BoxID, model.i_AssociateNum2));
                    if (lst.Count > 0)
                    {
                        lst[0].i_AssociateNum1 = model.i_Number;
                        lst[0].i_AssociateNum2 = model.i_AssociateNum1;
                        lst[0].i_IsAssociateActive = 2;  //被动关联
                        lst[0].i_supplementSerive |= (int)(MBoxSDK.ConfigSDK.SPM_ASSO_NUM);  //关联
                        new DB_Talk.BLL.m_Member().Update(lst[0]);
                    }
                }
                else
                {
                    if (_mPreModel.i_AssociateNum2 > 0)
                    {
                        List<DB_Talk.Model.m_Member> lst = new List<DB_Talk.Model.m_Member>();
                        lst = new DB_Talk.BLL.m_Member().GetModelList(string.Format(" i_flag=0 and i_IsDispatch=0 and BoxID='{0}' " +
                                       " and i_Number='{1}'", Global.Params.BoxID, _mPreModel.i_AssociateNum2));
                        if (lst.Count > 0)
                        {
                            lst[0].i_AssociateNum1 = 0;
                            lst[0].i_AssociateNum2 = 0;
                            lst[0].i_IsAssociateActive = 0;  //取消被动关联
                            lst[0].i_supplementSerive &= (uint)(~MBoxSDK.ConfigSDK.SPM_ASSO_NUM);  //去关联
                            new DB_Talk.BLL.m_Member().Update(lst[0]);
                        }
                    }
                }
        }
        public void LoadData()
        {
            dgvList.Rows.Clear();
            List<DB_Talk.Model.m_FAP> lst = new List<DB_Talk.Model.m_FAP>();
            lst = new DB_Talk.BLL.m_FAP().GetModelList(string.Format("i_Flag=0 and BoxID='{0}' ", Global.Params.BoxID));
            int i = 0;


            //从BOX中取
            List<DB_Talk.Model.m_FAP> lstBoxFap = new List<DB_Talk.Model.m_FAP>();
            Tools.MBoxOperate.GetFAP(out lstBoxFap);

            foreach (DB_Talk.Model.m_FAP item in lst)
            {
                i++;
                List<DB_Talk.Model.m_Member> lstMember = new DB_Talk.BLL.m_Member().GetModelList(string.Format("i_Flag=0 and FapID={0} and BoxID={1}", item.ID,Global.Params.BoxID));
                int phoneCount = 0;
                if (lstMember!=null && lstMember.Count>0)
                {
                    phoneCount = lstMember.Count;
                }
                string fapState=GetFapState(lstBoxFap,item.FapID);
                if (fapState!="注册成功")
                {
                    phoneCount = 0;
                }
                dgvList.Rows[dgvList.Rows.Add(item.ID,
                        item.FapID,
                        item.vc_TempAddress,
                        fapState,
                        item.vc_Name,
                        item.vc_Identify,
                        phoneCount
                        )].Tag = item;
            }

           
           
            kryptonHeaderGroup1.ValuesSecondary.Heading = "  共" + dgvList.Rows.Count.ToString() + "条记录";
            
        }
        private void btnDel_Click(object sender, EventArgs e)
        {
            if (dgvList.CurrentRow != null)
            {
                bool delete = false;
                Bestway.Windows.Forms.ProgressBarDialog procDlg = new Bestway.Windows.Forms.ProgressBarDialog();
                try
                {
                    DB_Talk.Model.m_CalledRule model = dgvList.CurrentRow.Tag as DB_Talk.Model.m_CalledRule;
                    if (model != null)
                    {
                        CheckDeleteCondition(model);
                        List<DB_Talk.Model.m_Member> lstMember=new DB_Talk.BLL.m_Member().GetModelList(
                           string.Format(" i_Flag=0 and i_Number like '{0}%' and BoxID='{1}' ", model.vc_CalledNumber, Global.Params.BoxID));
                          // string.Format(" i_Flag=0 and i_Number like '{0}%' and BoxID='{1}' and i_IsDispatch!=1", model.vc_CalledNumber, Global.Params.BoxID));

                        if (lstMember.Count > 0)
                        {
                            CommControl.MessageBoxEx.MessageBoxEx.Show("用户号码中引用了此呼叫规则,不允许删除,要想删除,请先删除用户号码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        procDlg.Show(Bestway.Windows.Forms.EnumDisplayType.LoadData, "      正在删除被叫规则【" + model.vc_CalledNumber + "】,请稍等...");
                        List<DB_Talk.Model.m_CalledRule> lstAdd = new List<DB_Talk.Model.m_CalledRule>();
                        List<DB_Talk.Model.m_CalledRule> lstDelete = new List<DB_Talk.Model.m_CalledRule>();
                        lstDelete.Add(model);
                        DB_Talk.Model.m_SIPInterface modelSip = null;
                        DB_Talk.Model.m_PRIInterface modelPri = null;

                        if (model.i_SIPID > 0)
                            modelSip = new DB_Talk.BLL.m_SIPInterface().GetModel(
                                 string.Format(" i_Flag=0 and SIPID='{0}' and BoxID='{1}'", model.i_SIPID, Global.Params.BoxID));
                        if (modelSip != null)
                        {
                            List<DB_Talk.Model.m_CalledRule> lstm = new DB_Talk.BLL.m_CalledRule().GetModelList(
                               string.Format(" i_Flag=0 and i_SIPID='{0}' and BoxID='{1}' and ID!='{2}'",
                               model.i_SIPID, Global.Params.BoxID, model.ID));
                            if (lstm.Count > 0)  //只删除呼叫规则(还存在引用此中继的呼叫规则)
                            {
                                if (Tools.MBoxOperate.Delete_Rule(lstAdd, lstDelete))
                                {
                                    delete = true;
                                    if (model.i_CalledSubType == MBoxSDK.ConfigSDK.CALLED_SUB_RULE_TYPE.市话.GetHashCode())
                                    {
                                        modelSip.vc_OutNumberLocal = modelSip.vc_OutNumberLocal.Replace(model.vc_CalledNumber, "").Replace(",,",",").Trim(','); ;
                                    }
                                    else if (model.i_CalledSubType == MBoxSDK.ConfigSDK.CALLED_SUB_RULE_TYPE.长途.GetHashCode())
                                    {
                                        modelSip.vc_OutNumber = modelSip.vc_OutNumber.Replace(model.vc_CalledNumber, "").Replace(",,", ",").Trim(','); ;
                                    }
                                     new DB_Talk.BLL.m_SIPInterface().Update(modelSip);
                                }
                            }
                            else  //连中继一起删除
                            {
                                if (Tools.MBoxOperate.DeleteSIP(modelSip, lstAdd, lstDelete) && new DB_Talk.BLL.m_SIPInterface().Delete(modelSip.ID))
                                {
                                    delete = true;
                                }
                            }
                        }

                        if (model.i_PRIID > 0)
                            modelPri = new DB_Talk.BLL.m_PRIInterface().GetModel(
                                 string.Format(" i_Flag=0 and PRIID='{0}' and BoxID='{1}'", model.i_PRIID, Global.Params.BoxID));

                        if (modelPri != null)
                        {
                            List<DB_Talk.Model.m_CalledRule> lstm = new DB_Talk.BLL.m_CalledRule().GetModelList(
                                string.Format(" i_Flag=0 and i_PRIID='{0}' and BoxID='{1}' and ID!='{2}'",
                                model.i_PRIID, Global.Params.BoxID, model.ID));
                            if (lstm.Count > 0 && Tools.MBoxOperate.Delete_Rule(lstAdd, lstDelete))  //只删除呼叫规则
                            {
                                if (model.i_CalledSubType == MBoxSDK.ConfigSDK.CALLED_SUB_RULE_TYPE.市话.GetHashCode())
                                {
                                    //modelPri.vc_OutNumberLocal = modelPri.vc_OutNumberLocal.Replace(model.vc_CalledNumber, "").Replace(",,", ",").Trim(',');
                                    modelPri.vc_OutNumberLocal = ReplaceString(modelPri.vc_OutNumberLocal, model.vc_CalledNumber);
                                }
                                else if (model.i_CalledSubType == MBoxSDK.ConfigSDK.CALLED_SUB_RULE_TYPE.长途.GetHashCode())
                                {
                                   // modelPri.vc_OutNumber = modelPri.vc_OutNumber.Replace(model.vc_CalledNumber, "").Replace(",,", ",").Trim(',');
                                    modelPri.vc_OutNumber = ReplaceString(modelPri.vc_OutNumber, model.vc_CalledNumber);
                                }
                                 new DB_Talk.BLL.m_PRIInterface().Update(modelPri);
                                delete = true;
                            }
                            else  //连中继一起删除
                            {
                                if (Tools.MBoxOperate.DeletePRI(modelPri, lstAdd, lstDelete) && new DB_Talk.BLL.m_PRIInterface().Delete(modelPri.ID))
                                {
                                    delete = true;
                                }
                            }
                        }

                        if (modelSip == null && modelPri == null)  //删除的入局规则
                        {

                            if (Tools.MBoxOperate.Delete_Rule(lstAdd, lstDelete))
                            {
                                DB_Talk.Model.m_Box BoxModel = new DB_Talk.BLL.m_Box().GetModel(Global.Params.BoxID);
                                if (BoxModel != null && BoxModel.vc_NumberHead!=null)  
                                {

                                    BoxModel.vc_NumberHead = BoxModel.vc_NumberHead.Replace(lstDelete[0].vc_CalledNumber, "").Replace(",,", ",").Trim(',');
                                    
                                    new DB_Talk.BLL.m_Box().Update(BoxModel);
                                }
                                delete = true;
                            }
                        }
                    }
                    else  //还未添加 直接删除
                        delete = true;


                    if (delete)
                    {
                        MBoxSDK.ConfigSDK.MBOX_SaveHaveDoneCfg(Global.Params.BoxHandle);
                        procDlg.Hide();
                        Loaddata();
                        //dgvList.Rows.Remove(dgvList.CurrentRow);
                        CommControl.MessageBoxEx.MessageBoxEx.Show("删除成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    }
                    else
                    {
                        procDlg.Hide();
                        CommControl.MessageBoxEx.MessageBoxEx.Show("删除失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    }
                }
                catch (Exception ex)
                {
                    procDlg.Hide();
                    CommControl.MessageBoxEx.MessageBoxEx.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    //CommControl.Tools.WriteLog.AppendErrorLog(ex);
                }
                finally
                {
                    procDlg.Dispose();
                }
            }
            else
            {
                CommControl.MessageBoxEx.MessageBoxEx.Show("请选择要删除的呼叫规则!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
        }
        void _talkControl_OnMemberStateChanged(object obj, TalkControl.UserStateArgs e)
        {
            System.Console.WriteLine("开始:_talkControl_OnMemberStateChanaged");
            //IntPtr i = this.Handle;

            if (IsDisposed || !this.IsHandleCreated) return;

            this.Invoke(new EventHandler(delegate(object o, EventArgs ee)
            {
                Pub._memberManage.UpdateState(obj, e);
                Pub._meetingManage.UpdateMeeting(obj, e);
                //  Console.Write(e.ToString());
                if (waitControl1.NumberIsExits(e.UserNumber) == true
                    && e.UserLineStatus != TalkControl.EnumUserLineStatus.Idle
                    && e.UserLineStatus != TalkControl.EnumUserLineStatus.Offline
                    )
                {
                    Pub._memberManage.SetMemberState(e.UserNumber, "等待中");
                    Pub._meetingManage.SetMemberState(e.UserNumber, "等待中");
                }

                if (waitControl1.NumberIsExits(e.UserNumber) == true
                   && (e.UserLineStatus == TalkControl.EnumUserLineStatus.Idle
                   || e.UserLineStatus == TalkControl.EnumUserLineStatus.Offline)
                   )
                {
                    waitControl1.DeleteWait(e.UserNumber);
                    Pub._lemcWaitForm.DeleteWait(e.UserNumber);
                }

                if (Pub._lemcWaitForm != null)
                {
                    if ((e.UserNumber == cLeft.Number || e.UserNumber == cRight.Number) && e.UserLineStatus == TalkControl.EnumUserLineStatus.Idle)
                    {
                        if (Pub._lemcWaitForm.WaitUserCount > 0)
                        {
                            Pub._lemcWaitForm.ResetCallState();
                        }
                        else
                        {
                            if (waitControl1.WaitUserCount > 0)
                            {
                                waitControl1.ResetCallState();
                            }
                        }
                    }
                    Pub._lemcWaitForm.UpdateMemberState(obj, e);
                }

                if (e.UserHookStatus == TalkControl.EnumUserHookStatus.ON && e.UserLineStatus == TalkControl.EnumUserLineStatus.Idle)//手柄 摘机状态
                {
                    SetDispatchButtonState(e.UserNumber);
                }
                Pub.waitMsg = string.Format("正在获取号码【{0}】的状态信息", e.UserNumber);
                //   System.Console.WriteLine("Ab");

                DB_Talk.Model.m_Member model = _lstMember.Find(p => p.i_Number == e.UserNumber);
                if (model != null)
                {
                    _lstMember.Remove(model);
                }

                //为了解决Box在接队列时返回不正使用的补救方法
                if ((e.UserNumber == cLeft.Number || e.UserNumber == cRight.Number) && e.UserLineStatus == TalkControl.EnumUserLineStatus.Busy)
                {
                    DispatchLogBLL.UpdateLog(CommControl.PublicEnums.EnumNormalCmd.SelectAnser, e.UserNumber, e.PeerPartNumber.ToString(), true);
                }

                if (e.UserLineStatus == TalkControl.EnumUserLineStatus.Idle)
                {
                    Pub.DeleteMemberState(e.UserNumber);
                }

                //将当前号码属于那个基站记录在号码表中
                //System.Console.WriteLine("sdf" + e.FapIP);
                // DispatchPlatform.TalkControl.EnumEquipmentType type=    Pub._talkControl.GetEquipmentType();
                SingleUserControl sc = Pub._memberManage.GetSingleControl(e.UserNumber);
                if (sc != null && e.FapIP != "0.0.0.0")
                {
                    //if (sc.FapIP != e.FapIP || e.UserLineStatus == TalkControl.EnumUserLineStatus.Offline)
                    //{
                    sc.FapIP = e.FapIP;

                    if (Pub.DicFap.ContainsKey(e.FapIP))
                    {
                        int fapID = Pub.DicFap[e.FapIP];
                        DB_Talk.Model.m_Member mem = new DB_Talk.BLL.m_Member().GetModel(sc.ID);
                        if (mem != null)
                        {

                            if (e.UserLineStatus == TalkControl.EnumUserLineStatus.Offline)
                            {
                                mem.FapID = 0;
                            }
                            else
                            {
                                mem.FapID = fapID;
                            }

                            new DB_Talk.BLL.m_Member().Update(mem);
                        }
                    }
                    //  }
                }
                //
                ////if (Pub.CanSort)//定时刷新在线的
                ////{
                ////    Pub._meetingManage.Sort();
                ////    Pub._memberManage.Sort();
                ////}


                SetCommandState();
            }));
            // System.Console.WriteLine("结束:_talkControl_OnMemberStateChanaged");

        }