private int flag_init = 0;//初始化,0未初始化,1已初始化

        public void InitUserControlUI()
        {
            if (flag_init == 1)
            {
                return;
            }
            flag_init = 1;

            System.Data.DataTable table = dbOperation.GetDepartment();
            if (table != null)
            {
                department = new Department();
                //DataRow[] rows = table.Select("FK_CODE_DEPT='0'");
                //if (rows.Length == 0)
                //{
                //    return;
                //}
                DataRow[] rows = table.Select();
                department.Name = rows[0]["INFO_NAME"].ToString();
                department.Row = rows[0];

                string deptId = "";
                deptId = rows[0]["INFO_CODE"].ToString();
                rows = table.Select("FK_CODE_DEPT='" + deptId + "'", " orderid asc");
                foreach (DataRow row1 in rows)
                {
                    Department department1 = new Department();
                    department1.Parent = department;
                    department1.Row = row1;
                    department1.Name = row1["INFO_NAME"].ToString();
                    rows = table.Select("FK_CODE_DEPT='" + row1["INFO_CODE"].ToString() + "'", " orderid asc");
                    foreach (DataRow row2 in rows)
                    {
                        Department department2 = new Department();
                        department2.Parent = department1;
                        department2.Row = row2;
                        department2.Name = row2["INFO_NAME"].ToString();
                        rows = table.Select("FK_CODE_DEPT='" + row2["INFO_CODE"].ToString() + "'", " orderid asc");
                        foreach (DataRow row3 in rows)
                        {
                            Department department3 = new Department();
                            department3.Parent = department2;
                            department3.Row = row3;
                            department3.Name = row3["INFO_NAME"].ToString();
                            rows = table.Select("FK_CODE_DEPT='" + row3["INFO_CODE"].ToString() + "'", " orderid asc");
                            foreach (DataRow row4 in rows)
                            {
                                Department department4 = new Department();
                                department4.Parent = department3;
                                department4.Row = row4;
                                department4.Name = row4["INFO_NAME"].ToString();
                                department3.Children.Add(department4);
                            }
                            department2.Children.Add(department3);
                        }
                        department1.Children.Add(department2);
                    }
                    department.Children.Add(department1);
                }

                departmentViewModel = new FamilyTreeViewModel(department);
                _treeView.DataContext = departmentViewModel;
            }
        }
        private void _import_Click(object sender, RoutedEventArgs e)
        {
           System.Data.DataTable importdt = new System.Data.DataTable();
           importdt = GetDataFromExcelByCom();
           if (importdt != null)
           {
               if (importdt.Rows.Count != 0)
               {
                   //获取当前部门的信息
                   Department department = _import.Tag as Department;
                   
                   for (int i = 0; i < importdt.Rows.Count; i++)
                   {
                       DataRow row = department.Row.Table.NewRow();
                       row.ItemArray = (object[])department.Row.ItemArray.Clone();
                       row["FK_CODE_DEPT"] = row["INFO_CODE"];

                       //上级部门级别
                       int fk_flag_tier = Convert.ToInt32(department.Row["FLAG_TIER"].ToString());
                       //导入的部门级别
                       string dept_flag = importdt.Rows[i][1].ToString();
                       DataRow[] rows = dt_level.Select("levelname = '" + dept_flag + "'");
                       int flag_tier = Convert.ToInt32(rows[0]["levelid"].ToString());
                       if (flag_tier <= fk_flag_tier)
                       {
                           Toolkit.MessageBox.Show("导入的部门级别不能高于上级部门,请确认后重新导入!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                           return;
                       }
                       row["FLAG_TIER"] = flag_tier;

                       //
                       int maxID = 0;

                       if (department.Children.Count == 0)
                       {
                           maxID = Convert.ToInt32(row["INFO_CODE"].ToString() + "01");
                           row["INFO_CODE"] = maxID;
                       }
                       else
                       {
                           for (int j = 0; j < department.Children.Count; j++)
                           {
                               int v = Convert.ToInt32(department.Children[j].Row["INFO_CODE"].ToString());
                               if (maxID < v)
                               {
                                   maxID = v;
                               }
                           }
                           row["INFO_CODE"] = maxID + 1;
                       }

                       row["INFO_NAME"] =importdt.Rows[i][0].ToString();
                       if (row["INFO_NAME"].ToString() == "")
                       {
                           load.Close();
                           Toolkit.MessageBox.Show("检测单位名称不能为空!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                           return;
                       }
                       row["address"] = importdt.Rows[i][9].ToString();
                       row["CONTACTER"] = importdt.Rows[i][6].ToString();
                       row["tel"] = importdt.Rows[i][8].ToString();
                       row["phone"] = importdt.Rows[i][7].ToString();

                       string type = importdt.Rows[i][5].ToString();
                       if (row["FLAG_TIER"].ToString() == "4")
                       {
                           if (type == "")
                           {
                               load.Close();
                               Toolkit.MessageBox.Show("检测站点性质不能为空!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                               return;
                           }
                           else
                           {
                               if (type == "屠宰场")
                               {
                                   row["type"] = "0";
                               }
                               else if (type == "养殖场")
                               {
                                   row["type"] = "1";
                               }
                               else if (type == "检疫站")
                               {
                                   row["type"] = "2";
                               }
                               else if (type == "加工企业")
                               {
                                   row["type"] = "3";
                               }
                           }
                       }
                      

                       //根据当前部门的级别来赋省,市,区的值
                       string provice = importdt.Rows[i][2].ToString();
                       string city = importdt.Rows[i][3].ToString();
                       string country = importdt.Rows[i][4].ToString();

                       if (provice != "")
                       {
                           bool provice_exit = dbOperation.GetDbHelper().Exists(string.Format("SELECT count(id) from sys_city where name ='{0}'", provice));
                           if (!provice_exit)
                           {
                               load.Close();
                               Toolkit.MessageBox.Show("省:" + provice + "不存在,请确认!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                               return;

                           }
                           else
                           {
                               row["Province"] = ProvinceCityTable.Select("name='" + provice + "'")[0]["id"].ToString();
                           }
                       }
                       else
                       {
                           row["Province"] = "";
                       }

                       if (city != "")
                       {
                           bool city_exit = dbOperation.GetDbHelper().Exists(string.Format("SELECT count(id) from sys_city where name ='{0}'", city));
                           if (!city_exit)
                           {
                               load.Close();
                               Toolkit.MessageBox.Show("市:" + city + "不存在,请确认!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                               return;
                           }
                           else
                           {
                               row["City"] = dbOperation.GetDbHelper().GetSingle(string.Format("SELECT id from sys_city where name ='{0}' and pid = '{1}'", city, row["Province"])).ToString();
                           }
                       }
                       else
                       {
                           row["City"] = "";
                       }

                       if (country != "")
                       {
                           bool country_exit = dbOperation.GetDbHelper().Exists(string.Format("SELECT count(id) from sys_city where name ='{0}'", country));
                           if (!country_exit)
                           {
                               load.Close();
                               Toolkit.MessageBox.Show("区:" + country + "不存在,请确认!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                               return;
                           }
                           else
                           {
                               row["Country"] = dbOperation.GetDbHelper().GetSingle(string.Format("SELECT id from sys_city where name ='{0}' and pid = '{1}'", country, row["City"])).ToString();
                           }
                       }
                       else
                       {
                           row["Country"] = "";
                       }

                       Department newDepartment = new Department();
                       newDepartment.Parent = department;
                       newDepartment.Name = row["INFO_NAME"].ToString();
                       newDepartment.Row = row;

                       string sql = String.Format("insert into sys_client_sysdept (INFO_CODE,INFO_NAME,FLAG_TIER,FK_CODE_DEPT,PROVINCE,CITY,COUNTRY,ADDRESS,CONTACTER,TEL,PHONE,TYPE,supplierId) values " +
                           "('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}');"
                     , row["INFO_CODE"], row["INFO_NAME"], row["FLAG_TIER"], row["FK_CODE_DEPT"]
                     , row["PROVINCE"], row["CITY"], row["COUNTRY"], row["ADDRESS"], row["CONTACTER"], row["TEL"], row["PHONE"], row["TYPE"], row["supplierId"]);

                       try
                       {
                           int count = dbOperation.GetDbHelper().ExecuteSql(sql);
                           if (count == 1)
                           {
                               //Toolkit.MessageBox.Show("保存成功!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                               Common.SysLogEntry.WriteLog("部门管理", (System.Windows.Application.Current.Resources["User"] as UserInfo).ShowName, Common.OperationType.Modify, "新增部门信息");
                           }
                           else
                           {
                               load.Close();
                               Toolkit.MessageBox.Show("保存失败!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                               return;
                           }
                       }
                       catch (Exception ee)
                       {
                           load.Close();
                           System.Diagnostics.Debug.WriteLine("SysDeptManager.btnSave_Click" + ee.Message);
                           Toolkit.MessageBox.Show("数据更新失败!稍后尝试!");
                           return;
                       }
                       state = "view";

                       department.Children.Add(newDepartment);

                       if (i == importdt.Rows.Count - 1)
                       {
                           load.Close();
                           Toolkit.MessageBox.Show("保存成功!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);

                           departmentViewModel = new FamilyTreeViewModel(this.department);
                           load_DeptDetails(row);
                           departmentViewModel.SearchText = row["INFO_NAME"].ToString();
                           departmentViewModel.SearchCommand.Execute(null);
                           _treeView.DataContext = null;
                           _treeView.DataContext = departmentViewModel;
                           _add.Tag = newDepartment;
                           _import.Tag = newDepartment;
                           _edit.Tag = newDepartment;
                       }
                   }
               }
               else
               {
                   load.Close();
                   Toolkit.MessageBox.Show("导入excel内容为空,请确认!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                   return;
               }
           }
        }
        private DepartmentViewModel(Department department, DepartmentViewModel parent)
        {
            _department = department;
            _parent = parent;

            _children = new ReadOnlyCollection<DepartmentViewModel>(
                    (from child in _department.Children
                     select new DepartmentViewModel(child, this))
                     .ToList<DepartmentViewModel>());
        }
        //保存按钮
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            Department department = _add.Tag as Department;

            //新增
            if (state == "add")
            {
                System.Data.DataTable dt = new System.Data.DataTable();
                DataRow row = department.Row.Table.NewRow();
                row.ItemArray = (object[])department.Row.ItemArray.Clone();
                row["FK_CODE_DEPT"] = row["INFO_CODE"];

                int maxID = 0;

                if (department.Children.Count == 0)
                {
                    maxID = Convert.ToInt32(row["INFO_CODE"].ToString() + "01");
                    row["INFO_CODE"] = maxID;
                }
                else
                {
                    for (int i = 0; i < department.Children.Count; i++)
                    {
                        int v = Convert.ToInt32(department.Children[i].Row["INFO_CODE"].ToString());
                        if (maxID < v)
                        {
                            maxID = v;
                        }
                    }
                    row["INFO_CODE"] = maxID + 1;
                }

                if (_level.SelectedIndex < 1)
                {
                    Toolkit.MessageBox.Show("请选择部门级别!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                if (_station.Text == "")
                {
                    if (row["FLAG_TIER"].ToString() == "4")
                    {
                        Toolkit.MessageBox.Show("请输入检测单位名称!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    else
                    {
                        Toolkit.MessageBox.Show("请输入部门名称!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }

                row["INFO_NAME"] = _station.Text;
                row["FLAG_TIER"] = (_level.SelectedItem as System.Windows.Controls.Label).Tag.ToString();

                if (user_flag_tier == "0")
                {
                    if (_Supplier.SelectedIndex < 1)
                    {
                        Toolkit.MessageBox.Show("请选择供应商!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }

                row["Province"] = _lower_provice.SelectedIndex < 1 ? "" : (_lower_provice.SelectedItem as System.Windows.Controls.Label).Tag.ToString();
                row["City"] = _lower_city.SelectedIndex < 1 ? "" : (_lower_city.SelectedItem as System.Windows.Controls.Label).Tag.ToString();
                if(_lower_country.Items.Count <= 0)
                {
                    row["Country"] = "";
                }
                else
                {
                    row["Country"] = _lower_country.SelectedIndex < 1 ? "" : (_lower_country.SelectedItem as System.Windows.Controls.Label).Tag.ToString();
                }

                if (row["Province"].ToString() == "" || row["City"].ToString() == "" || row["Country"].ToString() == "")
                {
                    Toolkit.MessageBox.Show("请选择所在地!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                
                row["INFO_NAME"] = _station.Text;
                row["address"] = _address.Text;
                row["CONTACTER"] = _principal_name.Text;
                row["tel"] = _phone.Text;
                row["phone"] = _contact_number.Text;
                row["supplierId"] = (_Supplier.SelectedItem as System.Windows.Controls.Label).Tag.ToString();
                //row["title"] = _title.Text;
                //row["INFO_NOTE"] = _note.Text;

                //获取画面上的检测点类型
                string type = "";
                if (_direct_station.IsChecked == true)
                {
                    row["type"] = "2";
                    type = "2";
                }
                else if (_cultivate_station.IsChecked == true)
                {
                    row["type"] = "1";
                    type = "1";
                }
                else if (_slaughter_station.IsChecked == true)
                {
                    row["type"] = "0";
                    type = "0";
                }
                else if (_direct_station_2.IsChecked == true)
                {
                    row["type"] = "3";
                    type = "3";
                }

                if (row["type"].ToString() == ""   && row["FLAG_TIER"].ToString() == "4")
                {
                    Toolkit.MessageBox.Show("请选择检测点性质!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                Department newDepartment = new Department();
                newDepartment.Parent = department;
                newDepartment.Name = _station.Text;
                newDepartment.Row = row;

                string sql = String.Format("insert into sys_client_sysdept (INFO_CODE,INFO_NAME,FLAG_TIER,FK_CODE_DEPT,PROVINCE,CITY,COUNTRY,ADDRESS,CONTACTER,TEL,PHONE,TYPE,supplierId) values " +
                    "('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}');"
              , row["INFO_CODE"], row["INFO_NAME"], row["FLAG_TIER"], row["FK_CODE_DEPT"]
              , row["PROVINCE"], row["CITY"], row["COUNTRY"], row["ADDRESS"], row["CONTACTER"], row["TEL"], row["PHONE"], row["TYPE"], row["supplierId"]);

                try
                {
                    int count = dbOperation.GetDbHelper().ExecuteSql(sql);
                    if (count == 1)
                    {
                        ////如果是养殖场类型的部门,把信息插入t_company表中
                        //if(row["TYPE"].ToString() == "1")
                        //{
                        //    int n = dbOperation.GetDbHelper().ExecuteSql(string.Format("INSERT INTO t_company (COMPANYNAME,AREAID,OPENFLAG,cuserid,cdate,sysdeptid) VALUES('{0}','{1}','{2}','{3}','{4}','{5}')",
                        //                                          row["INFO_NAME"],row["COUNTRY"],'1',(Application.Current.Resources["User"] as UserInfo).ID,
                        //                                          DateTime.Now, row["INFO_CODE"]));
                        //    if (n != 1)
                        //    {
                        //        Toolkit.MessageBox.Show("被检单位添加失败!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        //        return;
                        //    }
                        //}
                        Toolkit.MessageBox.Show("保存成功!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        Common.SysLogEntry.WriteLog("部门管理", (System.Windows.Application.Current.Resources["User"] as UserInfo).ShowName, Common.OperationType.Modify, "新增部门信息");
                    }
                    else
                    {
                        Toolkit.MessageBox.Show("保存失败!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }
                catch (Exception ee)
                {
                    System.Diagnostics.Debug.WriteLine("SysDeptManager.btnSave_Click" + ee.Message);
                    Toolkit.MessageBox.Show("数据更新失败!稍后尝试!");
                    return;
                }
                state = "view";

                department.Children.Add(newDepartment);
                departmentViewModel = new FamilyTreeViewModel(this.department);

                departmentViewModel.SearchText = _station.Text;
                departmentViewModel.SearchCommand.Execute(null);
                _add.Tag = newDepartment;
                _import.Tag = newDepartment;
                _edit.Tag = newDepartment;



            }//修改
            else if (state == "edit")
            {
                //获取画面上的检测点类型
                string type = "";
                if (_direct_station.IsChecked == true)
                {
                    type = "2";
                }
                else if (_cultivate_station.IsChecked == true)
                {
                    type = "1";
                }
                else if (_slaughter_station.IsChecked == true)
                {
                    type = "0";
                }
                else if (_direct_station_2.IsChecked == true)
                {
                    type = "3";
                }

                string Province = _lower_provice.SelectedIndex < 1 ? "" : (_lower_provice.SelectedItem as System.Windows.Controls.Label).Tag.ToString();
                string City = _lower_city.SelectedIndex < 1 ? "" : (_lower_city.SelectedItem as System.Windows.Controls.Label).Tag.ToString();
                string Country = "";
                if (_lower_country.Items.Count <= 0)
                {
                    Country = "";
                }
                else
                {
                    Country = _lower_country.SelectedIndex < 1 ? "" : (_lower_country.SelectedItem as System.Windows.Controls.Label).Tag.ToString();
                }

                if (Province == "" || City == "" || Country == "")
                {
                    Toolkit.MessageBox.Show("请选择所在地!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                string sql = String.Format("UPDATE sys_client_sysdept set INFO_NAME='{0}',ADDRESS='{1}',CONTACTER='{2}',TEL='{3}',PHONE='{4}',TYPE='{5}',supplierId = '{6}',"+
                    "PROVINCE = '{7}',CITY = '{8}',COUNTRY ='{9}'  where INFO_CODE='{10}';"
                , _station.Text, _address.Text, _principal_name.Text, _phone.Text, _contact_number.Text, type, 
                (_Supplier.SelectedItem as System.Windows.Controls.Label).Tag,
                Province, City, Country,department.Row["INFO_CODE"]);

                try
                {
                    int count = dbOperation.GetDbHelper().ExecuteSql(sql);
                    if (count == 1)
                    {
                        ////如果是养殖场类型的部门,把修改的部门名称保存进t_company表中
                        //if (type == "1")
                        //{
                        //    int n = dbOperation.GetDbHelper().ExecuteSql(string.Format("update t_company set COMPANYNAME = '{0}' where sysdeptid = '{1}'",
                        //                                                  _station.Text,department.Row["INFO_CODE"]));
                        //    if (n != 1)
                        //    {
                        //        Toolkit.MessageBox.Show("被检单位修改失败!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        //        return;
                        //    }
                        //}

                        Toolkit.MessageBox.Show("保存成功!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        Common.SysLogEntry.WriteLog("部门管理", (System.Windows.Application.Current.Resources["User"] as UserInfo).ShowName, Common.OperationType.Modify, "修改部门信息");
                    }
                    else
                    {
                        Toolkit.MessageBox.Show("保存失败!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }
                catch (Exception ee)
                {
                    System.Diagnostics.Debug.WriteLine("SysDeptManager.btnSave_Click" + ee.Message);
                      Toolkit.MessageBox.Show("数据更新失败!稍后尝试!");
                    return;
                }
                state = "view";

                //更新树形表
                department.Row["INFO_NAME"] = _station.Text;
                department.Name = _station.Text;
                department.Row["address"] = _address.Text;
                department.Row["contacter"] = _principal_name.Text;
                department.Row["tel"] = _phone.Text;
                department.Row["phone"] = _contact_number.Text;
                department.Row["supplierId"] = (_Supplier.SelectedItem as System.Windows.Controls.Label).Tag.ToString();
                department.Row["type"] = type;
                department.Row["Province"] = Province;
                department.Row["City"] = City;
                department.Row["Country"] = Country;
                _edit.IsEnabled = true;
            }
            else
            {
                return;
            }

            _treeView.DataContext = null;
            _treeView.DataContext = departmentViewModel;
            _detail_info.IsEnabled = false;
        }
 public DepartmentViewModel(Department department)
     : this(department, null)
 {
 }
        public FamilyTreeViewModel(Department rootPerson)
        {
            _rootPerson = new DepartmentViewModel(rootPerson);

            _firstGeneration = new ReadOnlyCollection<DepartmentViewModel>(
                new DepartmentViewModel[] 
                { 
                    _rootPerson 
                });

            _searchCommand = new SearchFamilyTreeCommand(this);
        }
        public void Load_DeptManager(object sender, RoutedEventArgs e)
        {
            //if (flag_init == 1)
            //{
            //    return;
            //}
            //flag_init = 1;

            DataTable table = dbOperation.GetDepartment();

            if (table != null)
            {
                department = new Department();
                //DataRow[] rows = table.Select("FK_CODE_DEPT='0'");
                //if (rows.Length == 0)
                //{
                //    return;
                //}
                DataRow[] rows = table.Select();
                department.Name = rows[0]["INFO_NAME"].ToString();
                department.Row  = rows[0];
                //对应湖北省级有3个部门(101 湖北畜安处,102 湖北动监处,103 湖北屠宰办),数据库中存在下级部门的是102
                string deptId = "";
                deptId = rows[0]["INFO_CODE"].ToString();
                rows   = table.Select("FK_CODE_DEPT='" + deptId + "'", " orderid asc");
                foreach (DataRow row1 in rows)
                {
                    Department department1 = new Department();
                    department1.Parent = department;
                    department1.Row    = row1;
                    department1.Name   = row1["INFO_NAME"].ToString();
                    //对应湖北省级有3个部门(101 湖北畜安处,102 湖北动监处,103 湖北屠宰办),数据库中存在下级部门的是102
                    string deptId2 = "";
                    deptId2 = row1["INFO_CODE"].ToString();
                    rows    = table.Select("FK_CODE_DEPT='" + deptId2 + "'", " orderid asc");
                    foreach (DataRow row2 in rows)
                    {
                        Department department2 = new Department();
                        department2.Parent = department1;
                        department2.Row    = row2;
                        department2.Name   = row2["INFO_NAME"].ToString();
                        rows = table.Select("FK_CODE_DEPT='" + row2["INFO_CODE"].ToString() + "'", " orderid asc");
                        foreach (DataRow row3 in rows)
                        {
                            Department department3 = new Department();
                            department3.Parent = department2;
                            department3.Row    = row3;
                            department3.Name   = row3["INFO_NAME"].ToString();
                            rows = table.Select("FK_CODE_DEPT='" + row3["INFO_CODE"].ToString() + "'", " orderid asc");
                            foreach (DataRow row4 in rows)
                            {
                                Department department4 = new Department();
                                department4.Parent = department3;
                                department4.Row    = row4;
                                department4.Name   = row4["INFO_NAME"].ToString();
                                department3.Children.Add(department4);
                            }
                            department2.Children.Add(department3);
                        }
                        department1.Children.Add(department2);
                    }
                    department.Children.Add(department1);
                }
                departmentViewModel   = new FamilyTreeViewModel(department);
                _treeView.DataContext = departmentViewModel;
            }
        }
        public void Load_DeptManager(object sender, RoutedEventArgs e)
        {
            //if (flag_init == 1)
            //{
            //    return;
            //}
            //flag_init = 1;

            DataTable table = dbOperation.GetDepartment();
            if (table != null)
            {
                department = new Department();
                //DataRow[] rows = table.Select("FK_CODE_DEPT='0'");
                //if (rows.Length == 0)
                //{
                //    return;
                //}
                DataRow[] rows = table.Select();
                department.Name = rows[0]["INFO_NAME"].ToString();
                department.Row = rows[0];
                //对应湖北省级有3个部门(101 湖北畜安处,102 湖北动监处,103 湖北屠宰办),数据库中存在下级部门的是102
                string deptId = "";
                if (rows[0]["INFO_CODE"].ToString() == "101" || rows[0]["INFO_CODE"].ToString() == "103")
                {
                    deptId = "102";
                }
                else
                {
                    deptId = rows[0]["INFO_CODE"].ToString();
                }
                rows = table.Select("FK_CODE_DEPT='" + deptId + "'", " orderid asc");
                foreach (DataRow row1 in rows)
                {
                    Department department1 = new Department();
                    department1.Parent = department;
                    department1.Row = row1;
                    department1.Name = row1["INFO_NAME"].ToString();
                    //对应湖北省级有3个部门(101 湖北畜安处,102 湖北动监处,103 湖北屠宰办),数据库中存在下级部门的是102
                    string deptId2 = "";
                    if (row1["INFO_CODE"].ToString() == "101" || row1["INFO_CODE"].ToString() == "103")
                    {
                        deptId2 = "102";
                    }
                    else
                    {
                        deptId2 = row1["INFO_CODE"].ToString();
                    }
                    rows = table.Select("FK_CODE_DEPT='" + deptId2 + "'", " orderid asc");
                    foreach (DataRow row2 in rows)
                    {
                        Department department2 = new Department();
                        department2.Parent = department1;
                        department2.Row = row2;
                        department2.Name = row2["INFO_NAME"].ToString();
                        rows = table.Select("FK_CODE_DEPT='" + row2["INFO_CODE"].ToString() + "'", " orderid asc");
                        foreach (DataRow row3 in rows)
                        {
                            Department department3 = new Department();
                            department3.Parent = department2;
                            department3.Row = row3;
                            department3.Name = row3["INFO_NAME"].ToString();
                            rows = table.Select("FK_CODE_DEPT='" + row3["INFO_CODE"].ToString() + "'", " orderid asc");
                            foreach (DataRow row4 in rows)
                            {
                                Department department4 = new Department();
                                department4.Parent = department3;
                                department4.Row = row4;
                                department4.Name = row4["INFO_NAME"].ToString();
                                department3.Children.Add(department4);
                            }
                            department2.Children.Add(department3);
                        }
                        department1.Children.Add(department2);
                    }
                    department.Children.Add(department1);
                }
                departmentViewModel = new FamilyTreeViewModel(department);
                _treeView.DataContext = departmentViewModel;
            }
        }
        //保存按钮
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            Department department = _add.Tag as Department;

            //新增
            if (state == "add")
            {
                DataTable dt = new DataTable();
                DataRow row = department.Row.Table.NewRow();
                row.ItemArray = (object[])department.Row.ItemArray.Clone();
                row["FK_CODE_DEPT"] = row["INFO_CODE"];

                int maxID = 0;

                if (department.Children.Count == 0)
                {
                    maxID = Convert.ToInt32(row["INFO_CODE"].ToString() + "01");
                    row["INFO_CODE"] = maxID;
                }
                else
                {
                    for (int i = 0; i < department.Children.Count; i++)
                    {
                        int v = Convert.ToInt32(department.Children[i].Row["INFO_CODE"].ToString());
                        if (maxID < v)
                        {
                            maxID = v;
                        }
                    }
                    row["INFO_CODE"] = maxID + 1;
                }

                row["INFO_NAME"] = _station.Text;
                row["FLAG_TIER"] = (Convert.ToInt32(department.Row["FLAG_TIER"].ToString()) + 1);
                if (_lower_area.SelectedIndex == -1 && row["FLAG_TIER"].ToString() != "4")
                {
                    Toolkit.MessageBox.Show("请选择所在地!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                if (_station.Text == "")
                {
                    if (row["FLAG_TIER"].ToString() == "4")
                    {
                        Toolkit.MessageBox.Show("请输入检测站点名称!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    else
                    {
                        Toolkit.MessageBox.Show("请输入部门名称!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }

                if (user_flag_tier == "0")
                {
                    if (_Supplier.SelectedIndex < 1)
                    {
                        Toolkit.MessageBox.Show("请选择供应商!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }

                string lower_area_id = "";

                if (_lower_area.Text != "")
                {
                    lower_area_id = ProvinceCityTable.Select("name='" + _lower_area.Text + "'")[0]["id"].ToString();
                }
                //根据当前部门的级别来赋省,市,区的值
                switch (row["FLAG_TIER"].ToString())
                {
                    case "0": row["Province"] = ""; 
                              row["City"] = ""; 
                              row["Country"] = ""; 
                              break;
                    case "1": row["Province"] = lower_area_id; 
                              row["City"] = ""; 
                              row["Country"] = ""; 
                              break;
                    case "2": row["Province"] = department.Row["Province"].ToString(); 
                              row["City"] = lower_area_id; 
                              row["Country"] = ""; 
                              break;
                    case "3": row["Province"] = department.Row["Province"].ToString(); 
                              row["City"] = department.Row["City"].ToString();
                              row["Country"] = lower_area_id;
                              break;
                    case "4": row["Province"] = department.Row["Province"].ToString(); 
                              row["City"] = department.Row["City"].ToString();
                              row["Country"] = department.Row["Country"].ToString();
                              break;
                    default: break;
                }
                row["INFO_NAME"] = _station.Text;
                row["address"] = _address.Text;
                row["CONTACTER"] = _principal_name.Text;
                row["tel"] = _phone.Text;
                row["phone"] = _contact_number.Text;
                row["supplierId"] = (_Supplier.SelectedItem as Label).Tag.ToString();
                //row["title"] = _title.Text;
                //row["INFO_NOTE"] = _note.Text;

                if (_direct_station.IsChecked == true)
                {
                    row["type"] = "2";
                }
                else if (_cultivate_station.IsChecked == true)
                {
                    row["type"] = "1";
                }
                else if (_slaughter_station.IsChecked == true)
                {
                    row["type"] = "0";
                }
                else if (_direct_station_2.IsChecked == true)
                {
                    row["type"] = "3";
                }

                if (row["type"].ToString() == ""   && row["FLAG_TIER"].ToString() == "4")
                {
                    Toolkit.MessageBox.Show("请选择检测点性质!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                Department newDepartment = new Department();
                newDepartment.Parent = department;
                newDepartment.Name = _station.Text;
                newDepartment.Row = row;

                string sql = String.Format("insert into sys_client_sysdept (INFO_CODE,INFO_NAME,FLAG_TIER,FK_CODE_DEPT,PROVINCE,CITY,COUNTRY,ADDRESS,CONTACTER,TEL,PHONE,TYPE,supplierId) values " +
                    "('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}');"
              , row["INFO_CODE"], row["INFO_NAME"], row["FLAG_TIER"], row["FK_CODE_DEPT"]
              , row["PROVINCE"], row["CITY"], row["COUNTRY"], row["ADDRESS"], row["CONTACTER"], row["TEL"], row["PHONE"], row["TYPE"], row["supplierId"]);

                try
                {
                    int count = dbOperation.GetDbHelper().ExecuteSql(sql);
                    if (count == 1)
                    {
                        Toolkit.MessageBox.Show("保存成功!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        Common.SysLogEntry.WriteLog("部门管理", (Application.Current.Resources["User"] as UserInfo).ShowName, Common.OperationType.Modify, "新增部门信息");
                    }
                    else
                    {
                        Toolkit.MessageBox.Show("保存失败!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }
                catch (Exception ee)
                {
                    System.Diagnostics.Debug.WriteLine("SysDeptManager.btnSave_Click" + ee.Message);
                    Toolkit.MessageBox.Show("数据更新失败!稍后尝试!");
                    return;
                }
                state = "view";

                department.Children.Add(newDepartment);
                departmentViewModel = new FamilyTreeViewModel(this.department);

                departmentViewModel.SearchText = _station.Text;
                departmentViewModel.SearchCommand.Execute(null);



            }//修改
            else if (state == "edit")
            {
                //获取画面上的检测点类型
                string type = "";
                if (_direct_station.IsChecked == true)
                {
                    type = "2";
                }
                else if (_cultivate_station.IsChecked == true)
                {
                    type = "1";
                }
                else if (_slaughter_station.IsChecked == true)
                {
                    type = "0";
                }

                string sql = String.Format("UPDATE sys_client_sysdept set INFO_NAME='{0}',ADDRESS='{1}',CONTACTER='{2}',TEL='{3}',PHONE='{4}',TYPE='{5}',supplierId = '{6}'  where INFO_CODE='{7}';"
                , _station.Text, _address.Text, _principal_name.Text, _phone.Text, _contact_number.Text,type ,(_Supplier.SelectedItem as Label).Tag, department.Row["INFO_CODE"]);

                try
                {
                    int count = dbOperation.GetDbHelper().ExecuteSql(sql);
                    if (count == 1)
                    {
                        Toolkit.MessageBox.Show("保存成功!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        Common.SysLogEntry.WriteLog("部门管理", (Application.Current.Resources["User"] as UserInfo).ShowName, Common.OperationType.Modify, "修改部门信息");
                    }
                    else
                    {
                        Toolkit.MessageBox.Show("保存失败!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }
                catch (Exception ee)
                {
                    System.Diagnostics.Debug.WriteLine("SysDeptManager.btnSave_Click" + ee.Message);
                      Toolkit.MessageBox.Show("数据更新失败!稍后尝试!");
                    return;
                }
                state = "view";

                //更新树形表
                department.Row["INFO_NAME"] = _station.Text;
                department.Name = _station.Text;
                department.Row["address"] = _address.Text;
                department.Row["contacter"] = _principal_name.Text;
                department.Row["tel"] = _phone.Text;
                department.Row["phone"] = _contact_number.Text;
                _edit.IsEnabled = true;


            }
            else
            {
                return;
            }

            _treeView.DataContext = null;
            _treeView.DataContext = departmentViewModel;
            _detail_info.IsEnabled = false;
        }