using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.ExtensionMethod;
using KGIS.Framework.Utils.Helper;
using KGIS.Framework.Utils.Interface;
using KGIS.Framework.Views;
using Kingo.Plugin.MapView.Enum;
using Kingo.Plugin.MapView.Model;
using Kingo.PluginServiceInterface;
using Kingo.PluginServiceInterface.Model;
using KUI.ComboBox;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace Kingo.Plugin.MapView.Views.FeatureAttribute
{
    /// 
    /// UCAttributeEdit.xaml 的交互逻辑
    /// 
    public partial class UCAttributeEdit : UserControl, IElementInfo
    {
        LayerFieldCfg Cfg = null;
        EngineEditor editor = null;
        List Dics = null;
        public Linkage[] LinkageCfg { get; set; }
        private object Data = null;
        private List Property = null;
        public UCAttributeEdit()
        {
            InitializeComponent();
            this.DockAreas = DockStyle.DockRight | DockStyle.Float;//Common.Interface.DockStyle.DockRight | Common.Interface.DockStyle.Float;
            this.FloatSize = new System.Drawing.Size(400, 500);
            this.DefaultArea = DockStyle.Float;// Common.Interface.DockStyle.DockRight;
            this.ShowCloseButton = false;
            this.ShowAutoHideButton = true;
            this.Title = "要素属性";
            editor = new EngineEditorClass();
            Property = new List();
            string cfgFilePath = System.IO.Path.Combine(SysAppPath.GetConfigPath(), "LayerFieldsCfg.xml");
            Cfg = SerializeAPI.DeserializeToObject2(cfgFilePath);
            this.Loaded += (s, e) =>
            {
                //关闭编辑禁用属性编辑
                bool IsOnlySave = false;
                editor = new EngineEditorClass();
                editor.OnStopEditing += (b) =>
                {
                    if (!IsOnlySave && Data != null)
                    {
                        if (Data is IFeature)
                            MapsManager.Instance.MapService.SelectFeature(((Data as IFeature).Class as FeatureClass).Name, (Data as IFeature).OID.ToString());
                        AllowEdit = false;
                        RefreshView();
                    }
                    IsOnlySave = false;
                    Dics = null;
                };
                editor.OnSaveEdits += () =>
                {
                    IsOnlySave = true;
                };
                editor.OnStartEditing += () =>
                {
                    if (Data != null)
                    {
                        AllowEdit = true;
                        RefreshView();
                        Dics = null;
                    }
                };
            };
        }
        #region 继承字段
        public bool IsShow { get; set; }
        public int ShowIndex { get; set; }
        public bool ResetSize { get; set; }
        public bool AllowEdit { get; set; }
        public Guid ID { get; set; }
        public DockStyle DockAreas { get; set; }
        public System.Drawing.Size FloatSize { get; set; }
        public int DockWidth { get; set; }
        public int DockHeight { get; set; }
        public DockStyle DefaultArea { get; set; }
        public bool ShowCloseButton { get; set; }
        public bool ShowAutoHideButton { get; set; }
        public string Title { get; set; }
        #endregion
        public void BindData(object obj)
        {
            try
            {
                if (obj is IFeature) Data = obj;
                Property.Clear();
                if (obj == null)
                {
                    grid.Children.Clear();
                    grid.RowDefinitions.Clear();
                    return;
                };
                //AllowEdit = !(editor.EditState == esriEngineEditState.esriEngineStateNotEditing || (editor.EditWorkspace != null && editor.EditWorkspace.PathName != ((obj as IFeature).Class as FeatureClass).Workspace.PathName));
                if (Dics == null && Platform.Instance.SystemType != SystemTypeEnum.DTBJK && Platform.Instance.SystemType != SystemTypeEnum.WYZS && Platform.Instance.SystemType != SystemTypeEnum.YCLJK)
                    Dics = Platform.Instance.DicHelper.GetAllDic();
                else if (Platform.Instance.SystemType == SystemTypeEnum.DTBJK || Platform.Instance.SystemType == SystemTypeEnum.WYZS || Platform.Instance.SystemType == SystemTypeEnum.YCLJK)
                    Dics = GetAllDic();
                if (obj is IFeature)
                {
                    AllowEdit = !(editor.EditState == esriEngineEditState.esriEngineStateNotEditing || (editor.EditWorkspace != null && editor.EditWorkspace.PathName != ((obj as IFeature).Class as FeatureClass).Workspace.PathName));
                    IFeature fe = obj as IFeature;
                    LayerInfo layer = Cfg.Layers[0];
                    for (int i = 0; i < fe.Fields.FieldCount; i++)
                    {
                        IField field = fe.Fields.get_Field(i);
                        if (field.Name.ToUpper() == "SHAPE" || field.Name.ToUpper().Contains("_EXTRA") || field.Name == "ErrorMessage" || field.Name == "ErrorShape")
                            continue;
                        List fields = layer.GetAllField();
                        FieldCfg fCfg = fields.FirstOrDefault(f => f.Name == field.Name);
                        IDomain domain = field.Domain;
                        PropertyGridDataStruct p = new PropertyGridDataStruct();
                        p.DisplayMemberPath = "DisplayName";
                        p.ValuePath = "CODE";
                        if (!field.Editable)
                        {
                            p.IsReadOnly = !field.Editable;
                        }
                        else
                        {
                            p.IsReadOnly = editor.EditState == esriEngineEditState.esriEngineStateNotEditing || (editor.EditWorkspace != null && editor.EditWorkspace.PathName != (fe.Class as FeatureClass).Workspace.PathName);
                        }
                        //是否可以为空
                        p.AllowNull = field.IsNullable;
                        if (string.IsNullOrWhiteSpace(field.AliasName))
                        {
                            p.Key = field.Name;
                        }
                        else
                        {
                            p.Key = field.AliasName;
                        }
                        p.FieldName = field.Name;
                        if (fCfg != null && !string.IsNullOrWhiteSpace(fCfg.DicName))
                        {
                            p.PropertyType = enumPropertyType.ComboBox;
                            if (LinkageCfg != null)
                            {
                                foreach (var item in LinkageCfg)
                                {
                                    if (field.Name == item.TargetPropertyName || field.Name == item.SourcePropertyName)
                                    {
                                        p.IsGroup = item.IsGroup;
                                        break;
                                    }
                                }
                                Linkage cfg = LinkageCfg.FirstOrDefault(w => w.SourcePropertyName == field.Name && w.LinkageType == EnumLinkageType.None && (!string.IsNullOrWhiteSpace(w.DisplayMemberPath) || !string.IsNullOrWhiteSpace(w.ValuePath)));
                                if (cfg != null)
                                {
                                    p.DisplayMemberPath = cfg.DisplayMemberPath;
                                    p.ValuePath = cfg.ValuePath;
                                }
                            }
                            p.DicData = new List();//单图斑建库系统不需要字典设置
                            DicTypeEnum dicType = (DicTypeEnum)System.Enum.Parse(typeof(DicTypeEnum), fCfg.DicName);
                            if (Platform.Instance.SystemType != SystemTypeEnum.DTBJK && Platform.Instance.SystemType != SystemTypeEnum.YCLJK)
                            {
                                if (p.Key == "权属单位代码" || p.Key == "坐落单位代码")
                                {
                                    p.DicData.Add(new DataDicTionary() { NAME = " ", CODE = " ", DisplayName = " - ", ID = 1 });
                                    p.DicData.AddRange(Platform.Instance.DicHelper.GetNoGroupDic(dicType, Dics).Where(x => (x.OWNERDIC == "1" || Convert.ToInt32(x.OWNERDIC) >= 50) && x.CODE.Length >= 19).ToLookup(x => x.CODE).ToDictionary(x => x.Key, x => x.First()).Values.ToList());
                                }
                                else
                                    p.DicData = Platform.Instance.DicHelper.GetNoGroupDic(dicType, Dics);
                            }
                            else
                            {
                                p.DicData = GetNoGroupDic(dicType, Dics);
                            }
                        }
                        else
                        {
                            p.PropertyType = enumPropertyType.TextBox;
                        }
                        //单图斑变更增加逻辑
                        if (p.Key == "DDTCMC" || p.Key == "单独图层名称")
                        {
                            p.DicData = new List();
                            //p.DicData.Add(new DataDicTionary() { NAME = " ", CODE = " ", DisplayName = " - ", ID = 1 }); 
                            p.DicData.Add(new DataDicTionary() { NAME = "一般地类", CODE = "一般地类", DisplayName = "一般地类-一般地类", ID = 2 });
                            p.DicData.Add(new DataDicTionary() { NAME = "已灭失", CODE = "已灭失", DisplayName = "已灭失-已灭失", ID = 3 });
                            p.DicData.Add(new DataDicTionary() { NAME = "光伏板区", CODE = "1302", DisplayName = "1302-光伏板区", ID = 4 });
                            p.DicData.Add(new DataDicTionary() { NAME = "推土区", CODE = "1303", DisplayName = "1303-推土区", ID = 5 });
                            p.DicData.Add(new DataDicTionary() { NAME = "拆除未尽区", CODE = "1304", DisplayName = "1304-拆除未尽区", ID = 6 });
                            p.DicData.Add(new DataDicTionary() { NAME = "路面范围", CODE = "1305", DisplayName = "1305-路面范围", ID = 7 });
                            p.DicData.Add(new DataDicTionary() { NAME = "工厂化种植更新", CODE = "1306", DisplayName = "1306-工厂化种植更新", ID = 8 });
                            p.PropertyType = enumPropertyType.ComboBox;
                        }
                        else if (p.Key == "SFXML" || p.Key == "变更类型")
                        {
                            p.DicData = new List();
                            p.DicData.Add(new DataDicTionary() { NAME = "否", CODE = "0", DisplayName = "0-否", ID = 2 });
                            p.DicData.Add(new DataDicTionary() { NAME = "是", CODE = "1", DisplayName = "1-是", ID = 3 });
                            p.PropertyType = enumPropertyType.ComboBox;
                        }
                        else if (p.Key == "XMLX" || p.Key == "项目类型")
                        {
                            p.DicData = new List();
                            p.DicData.Add(new DataDicTionary() { NAME = "土地开发项目", CODE = "1", DisplayName = "1-土地开发项目", ID = 2 });
                            p.DicData.Add(new DataDicTionary() { NAME = "增减挂钩项目", CODE = "2", DisplayName = "2-增减挂钩项目", ID = 3 });
                            p.DicData.Add(new DataDicTionary() { NAME = "生态修复项目", CODE = "3", DisplayName = "3-生态修复项目", ID = 4 });
                            p.DicData.Add(new DataDicTionary() { NAME = "高标准农田建设项目", CODE = "4", DisplayName = "4-高标准农田建设项目", ID = 5 });
                            p.DicData.Add(new DataDicTionary() { NAME = "恢复耕地项目", CODE = "5", DisplayName = "5-恢复耕地项目", ID = 6 });
                            p.DicData.Add(new DataDicTionary() { NAME = "其他项目", CODE = "6", DisplayName = "6-其他项目", ID = 7 });
                            p.PropertyType = enumPropertyType.ComboBox;
                        }
                        else if (p.Key == "TBMJ" || p.Key == "图斑面积")
                        {
                            p.IsReadOnly = true;
                        }
                        if (fe.get_Value(i) is DBNull || fe.get_Value(i) == null)
                        {
                            p.Value = null;
                        }
                        else
                        {
                            p.Value = fe.get_Value(i).ToString().Trim();
                        }
                        p.PropertyChanged += PropertyChangedEvent;
                        if ((fe.Class as FeatureClass).Name == "JCTB")
                            p.Visible = AllowEdit;//当前对监测图斑单独显示
                        Property.Add(p);
                    }
                    RefreshView();
                    this.DataContext = Property;
                    ExecuteDataCheck(fe);
                    //lbTBList.ItemsSource = null;
                    //lbTBList.ItemsSource = Property;
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("图斑变更属性编辑失败:" + ex.Message);
                throw ex;
            }
        }
        private void RefreshView()
        {
            SetVisible(Property);
            #region
            grid.Children.Clear();
            grid.RowDefinitions.Clear();
            Property = Property.OrderBy(o => o.Order).ToList();
            foreach (var item in Property)
            {
                if (item.Visible)
                {
                    grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(37, GridUnitType.Pixel) });
                    Label lab = new Label();
                    lab.Content = item.Key;
                    lab.SetValue(Grid.RowProperty, grid.RowDefinitions.Count - 1);
                    lab.HorizontalContentAlignment = HorizontalAlignment.Right;
                    lab.Margin = new Thickness(4);
                    lab.IsEnabled = !item.IsReadOnly;
                    grid.Children.Add(lab);
                    Control ctrl = new TextBox();
                    ctrl.Height = 27;
                    Binding bind = new Binding();
                    bind.Path = new PropertyPath("Value");
                    bind.Mode = BindingMode.TwoWay;
                    switch (item.PropertyType)
                    {
                        case enumPropertyType.Default:
                        case enumPropertyType.TextBox:
                            ctrl = new TextBox();
                            ctrl.Height = 27;
                            ctrl.DataContext = item;
                            bind.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
                            ctrl.SetBinding(TextBox.TextProperty, bind);
                            ctrl.IsEnabled = !item.IsReadOnly;
                            break;
                        case enumPropertyType.CheckBox:
                            ctrl = new CheckBox();
                            ctrl.DataContext = item;
                            ctrl.SetBinding(CheckBox.IsCheckedProperty, bind);
                            ctrl.IsEnabled = AllowEdit;
                            break;
                        case enumPropertyType.DatePicker:
                            ctrl = new DatePicker();
                            ctrl.DataContext = item;
                            ctrl.SetBinding(DatePicker.TextProperty, bind);
                            ctrl.IsEnabled = AllowEdit;
                            break;
                        case enumPropertyType.SpinEdit:
                            break;
                        case enumPropertyType.ButtonEdit:
                            break;
                        case enumPropertyType.ButtonEditFJ:
                            break;
                        case enumPropertyType.ComboBox:
                        case enumPropertyType.AutoCompleteBox:
                            ctrl = new AutoCompleteBox();
                            ctrl.Height = 27;
                            ctrl.DataContext = item;
                            ctrl.LostFocus += UCAttributeLostFocus;
                            bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                            ctrl.SetValue(AutoCompleteBox.ItemsSourceProperty, item.DicData);
                            ctrl.SetValue(AutoCompleteBox.ValueMemberPathProperty, item.ValuePath);
                            ctrl.SetValue(AutoCompleteBox.DisplayMemberPathProperty, item.DisplayMemberPath);
                            ctrl.SetBinding(AutoCompleteBox.SelectedValueProperty, bind);
                            ctrl.IsEnabled = AllowEdit;
                            (ctrl as AutoCompleteBox).IsEditable = AllowEdit;
                            break;
                        default:
                            break;
                    }
                    ctrl.SetValue(Grid.RowProperty, grid.RowDefinitions.Count - 1);
                    ctrl.SetValue(Grid.ColumnProperty, 1);
                    ctrl.HorizontalAlignment = HorizontalAlignment.Stretch;
                    ctrl.Margin = new Thickness(2);
                    grid.Children.Add(ctrl);
                }
            }
            grid.RowDefinitions.Add(new RowDefinition());
            #endregion
        }
        /// 
        /// AttributeEdit_LostFous
        /// 
        /// 
        /// 
        private void UCAttributeLostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                string senderText = (sender as AutoCompleteBox).Text.Trim();
                if (!(sender as AutoCompleteBox).SelectedValue.ToString().Trim().Equals(senderText) && string.IsNullOrWhiteSpace(senderText))
                {
                    (sender as AutoCompleteBox).SelectedValue = ((e.Source as AutoCompleteBox).ItemsSource as List)[0];
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex.Message);
            }
        }
        private void SetVisible(List pList)
        {
            string cfgFilePath = System.IO.Path.Combine(SysAppPath.GetConfigPath(), "LayerFieldsCfg.xml");
            if (Cfg == null)
                Cfg = SerializeAPI.DeserializeToObject2(cfgFilePath);
            if (Cfg == null || Cfg.Layers.Count == 0) return;
            LayerInfo layer = Cfg.Layers[0];
            if ((Data is IFeature) && ((Data as IFeature).Class as FeatureClass).Name == "DLTBGX")
                layer.Fields.ForEach(x => x.DisplayWhere = "");//增量更新变更展示全部可修改数据
            string dlbm = string.Empty;
            string ddtbbz = string.Empty;
            string sfxml = string.Empty;
            string zzsx = string.Empty;
            string czcsxm = string.Empty;
            PropertyGridDataStruct propertySet = pList.FirstOrDefault(x => x.FieldName.ToUpper().Equals("DDTCBZ"));
            if (propertySet != null)
            {
                ddtbbz = propertySet.Value;
            }
            propertySet = pList.FirstOrDefault(x => x.FieldName.ToUpper().Equals("DLBM"));
            if (propertySet != null)
            {
                dlbm = propertySet.Value == null ? "" : propertySet.Value;
            }
            //propertySet = pList.FirstOrDefault(x => x.FieldName.Equals("SFXML"));
            propertySet = pList.FirstOrDefault(x => x.Key.Equals("变更类型"));
            if (propertySet != null)
            {
                sfxml = propertySet.Value == null ? "" : propertySet.Value;
            }
            foreach (var item in layer.Fields)
            {
                string val = string.Empty;
                int idx = -1;
                //List TempDic = null;
                var GroupField = pList.FirstOrDefault(f => f.Key == item.Name || f.Key == item.AliasName);
                if (GroupField == null)
                {
                    GroupField = new PropertyGridDataStruct();
                    GroupField.PropertyType = enumPropertyType.ComboBox;
                    GroupField.PropertyChanged += PropertyChangedEvent;
                }
                GroupField.Order = layer.Fields.IndexOf(item);
                GroupField.Key = item.AliasName;
                foreach (var subItem in item.Fields)
                {
                    var field = pList.FirstOrDefault(f => f.Key == subItem.Name || f.Key == subItem.AliasName);
                    if (field == null) return;
                    if (!string.IsNullOrWhiteSpace(field.Value))
                    {
                        if (!string.IsNullOrWhiteSpace(val.ToTrim()))
                            val += "-";
                        val += field.Value;
                    }
                    if (GroupField.PropertyType == field.PropertyType)
                    {
                        if (GroupField.Value.ToTrim() != field.Value.ToTrim() && !GroupField.Value.ToTrim().Contains(field.Value.ToTrim()))
                            GroupField.Value = field.Value;
                        GroupField.DicData = field.DicData;
                        GroupField.ValuePath = field.DisplayMemberPath;
                        GroupField.DisplayMemberPath = field.DisplayMemberPath;
                    }
                    if (!string.IsNullOrWhiteSpace(subItem.DisplayWhere.ToTrim()))
                    {
                        //字段显示条件
                        string[] wheres = subItem.DisplayWhere.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < wheres.Length; i++)
                        {
                            string[] kv = wheres[i].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            if (kv.Length != 2)
                            {
                                LogAPI.Debug(string.Format("图层字段配置错误,FieldCfg中Name={0}", subItem.Name));
                                continue;
                            }
                            var tempField = pList.FirstOrDefault(f => f.Key == kv[0] || f.FieldName == kv[0]);
                            if (tempField != null)
                            {
                                if (kv[1].ToTrim().Contains("%"))
                                    subItem.Display = tempField.Value.ToTrim().StartsWith(kv[1].ToTrim().Replace("%", ""));
                                else
                                    subItem.Display = tempField.Value.ToTrim() == kv[1].ToTrim();
                            }
                        }
                    }
                    field.Visible = subItem.Display;
                    if (field.Visible)
                    {
                        item.Display = false;
                    }
                    if (idx == -1)
                    {
                        idx = pList.IndexOf(field);
                    }
                }
                if (!string.IsNullOrWhiteSpace(item.DisplayWhere.ToTrim()))
                {
                    //字段显示条件
                    string[] wheres = item.DisplayWhere.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < wheres.Length; i++)
                    {
                        string[] kv = wheres[i].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        if (kv.Length != 2)
                        {
                            LogAPI.Debug(string.Format("图层字段配置错误,FieldCfg中Name={0}", item.Name));
                            continue;
                        }
                        if (kv[1].Contains("|"))//当前为测试项逻辑
                        {
                            string[] kv2 = kv[1].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                            var tempField = pList.FirstOrDefault(f => f.Key == kv[0] || f.FieldName == kv[0]);
                            if (tempField != null)
                            {
                                if (kv2[0].ToTrim().Contains("%") && kv2[1].ToTrim().Contains("%"))
                                    item.Display = tempField.Value.ToTrim().StartsWith(kv2[0].ToTrim().Replace("%", "")) || tempField.Value.ToTrim().StartsWith(kv2[1].ToTrim().Replace("%", ""));
                                else if (kv2[0].ToTrim().Contains("%"))
                                    item.Display = tempField.Value.ToTrim().StartsWith(kv2[0].ToTrim().Replace("%", "")) || tempField.Value.ToTrim().Equals(kv2[1]);
                                else
                                    item.Display = tempField.Value.ToTrim() == kv2[1].ToTrim() || tempField.Value.ToTrim() == kv2[0].ToTrim();
                                GroupField.Visible = item.Display;
                            }
                        }
                        else
                        {
                            var tempField = pList.FirstOrDefault(f => f.Key == kv[0] || f.FieldName == kv[0]);
                            if (tempField != null)
                            {
                                if (kv[1].ToTrim().Contains("%"))
                                    item.Display = tempField.Value.ToTrim().StartsWith(kv[1].ToTrim().Replace("%", ""));
                                else
                                    item.Display = tempField.Value.ToTrim() == kv[1].ToTrim();
                                GroupField.Visible = item.Display;
                            }
                        }
                    }
                }
                if (item.Display)
                {
                    if (idx == -1) idx = 0;
                    var field = pList.FirstOrDefault(f => f.Key == item.Name || f.Key == item.AliasName);
                    if (field == null)
                    {
                        GroupField.Value = val;
                        GroupField.Visible = item.Display;
                        pList.Insert(idx, GroupField);
                    }
                    GroupField.Visible = item.Display;
                }
                //单图斑展示字段间逻辑
                if (item.AliasName.Trim() == "地类信息" && !string.IsNullOrWhiteSpace(ddtbbz))
                {
                    DataDicTionary dataDicTionary = GroupField.DicData.FirstOrDefault(x => string.IsNullOrWhiteSpace(x.CODE));
                    if (dataDicTionary != null)
                    {
                        GroupField.DicData.Remove(dataDicTionary);
                    }
                    GroupField.Visible = true;
                    List dataDicTionaries = new List();
                    switch (ddtbbz)
                    {
                        case "1301"://临时用地
                            string values = "05H1,0508,0601,0602,0603,0701,0702,08H1,08H2,08H2A,0809,0810,0810A,09,1001A,1002A,1003A,1004,1005,1007,1008,1009,1109,8801";
                            foreach (string code in values.Split(','))
                            {
                                dataDicTionary = GroupField.DicData.FirstOrDefault(x => x.CODE.Equals(code));
                                if (dataDicTionary != null)
                                {
                                    dataDicTionaries.Add(dataDicTionary);
                                }
                            }
                            break;
                        case "1302"://光伏板区
                            values = "0101,0102,0103,0204,0307,0401,0403,0404,0404A,0601,1101,1102,1103,1104,1104A,1105,1106,1107,1204,1205,1206,1207,8801,9901";
                            foreach (string code in values.Split(','))
                            {
                                dataDicTionary = GroupField.DicData.FirstOrDefault(x => x.CODE.Equals(code));
                                if (dataDicTionary != null)
                                {
                                    dataDicTionaries.Add(dataDicTionary);
                                }
                            }
                            break;
                        case "1303"://推土区
                            values = "8801,05H1,0508,0601,0602,0603,0701,0702,08H1,08H2,08H2A,0809,0810,0810A,09,1001";
                            foreach (string code in values.Split(','))
                            {
                                dataDicTionary = GroupField.DicData.FirstOrDefault(x => x.CODE.Equals(code));
                                if (dataDicTionary != null)
                                {
                                    dataDicTionaries.Add(dataDicTionary);
                                }
                            }
                            break;
                        case "1304"://拆除未尽区
                            values = "05H1,0508,0601,0602,0603,0701,0702,08H1,08H2,08H2A,0809,0810,0810A,09,1001,1001A,1002,1002A,1003,1003A,1004,1005,1007,1008,1009,1109,1202,8801";
                            foreach (string code in values.Split(','))
                            {
                                dataDicTionary = GroupField.DicData.FirstOrDefault(x => x.CODE.Equals(code));
                                if (dataDicTionary != null)
                                {
                                    dataDicTionaries.Add(dataDicTionary);
                                }
                            }
                            break;
                        case "1305"://路面范围
                            values = "1001,1003,8801";
                            if (SysConfigsOprator.GetAppsetingValueByKey("ArearName").Equals("43"))
                            {
                                values = "1003,8801";
                            }
                            foreach (string code in values.Split(','))
                            {
                                dataDicTionary = GroupField.DicData.FirstOrDefault(x => x.CODE.Equals(code));
                                if (dataDicTionary != null)
                                {
                                    dataDicTionaries.Add(dataDicTionary);
                                }
                            }
                            break;
                        case "1306"://工厂化种植更新(待更新相关地类)
                            break;
                        case "1307"://荒草地特征图斑(基础库地类建设用地或设施农用地)
                            dataDicTionary = GroupField.DicData.FirstOrDefault(x => x.CODE.Equals("8801"));
                            if (dataDicTionary != null)
                            {
                                dataDicTionaries.Add(dataDicTionary);
                            }
                            break;
                        default://一般地类不展示1001和1003地类
                            DataDicTionary[] dataDics = new DataDicTionary[GroupField.DicData.Count];
                            GroupField.DicData.CopyTo(dataDics);
                            dataDicTionaries = dataDics.ToList();
                            values = "1001,1003,8801";
                            if (SysConfigsOprator.GetAppsetingValueByKey("ArearName").Equals("43"))
                            {
                                values = "1003,8801";
                            }
                            foreach (string code in values.Split(','))
                            {
                                dataDicTionary = dataDicTionaries.FirstOrDefault(x => x.CODE.Equals(code));
                                if (dataDicTionary != null)
                                {
                                    dataDicTionaries.Remove(dataDicTionary);
                                }
                            }
                            break;
                    }
                    GroupField.DicData = dataDicTionaries;
                }
                else if (item.AliasName.Equals("城镇村属性码") && !string.IsNullOrWhiteSpace(dlbm))
                {
                    if (dlbm.Equals("9904") || dlbm.Equals("9905"))
                    {
                        GroupField.Value = string.Empty;
                        GroupField.Visible = false;
                        continue;
                    }
                    List dataDicTionaries = new List();
                    List listValue = new List();
                    //添加该字典的空选项
                    dataDicTionaries.Add(GroupField.DicData[0]);
                    if ("05H1/0508/0701/0702/08H1/08H2/08H2A/0809/0810/0810A/1005/1201/1004".Split('/').Contains(dlbm))
                    {
                        listValue = "201,202,203".Split(',').ToList();
                    }
                    else if (dlbm.Equals("0601"))
                    {
                        listValue = "201,202,203,201A,202A,203A".Split(',').ToList();
                    }
                    else if (dlbm.Equals("0602") || dlbm.Equals("0603"))
                    {
                        listValue = "201,202,203,204".Split(',').ToList();
                    }
                    else if (dlbm.Equals("09"))
                    {
                        listValue = "201,202,203,205".Split(',').ToList();
                    }
                    else
                    {
                        dataDicTionaries = GroupField.DicData;
                    }
                    foreach (string code in listValue)
                    {
                        DataDicTionary dataDicTionary = GroupField.DicData.FirstOrDefault(x => x.CODE.Equals(code));
                        if (dataDicTionary != null)
                        {
                            dataDicTionaries.Add(dataDicTionary);
                        }
                    }
                    GroupField.DicData = dataDicTionaries;
                    if (dataDicTionaries.FirstOrDefault(x => x.CODE.Equals(GroupField.Value)) == null)
                    {
                        GroupField.Value = string.Empty;
                    }
                }
                else if (item.AliasName.Equals("种植属性") && !string.IsNullOrWhiteSpace(dlbm))
                {
                    List listValue = new List();
                    string lstDLBM = "0101/0102/0103/0201/0202/0203/0204/0201K/0202K/0203K/0204K/0301/0302/0305/0307/0301K/0302K/0307K/0403K/1104K/0404A/1104/1104A/0404";
                    if (!lstDLBM.Split('/').Contains(dlbm))
                    {
                        GroupField.Value = string.Empty;
                        GroupField.Visible = false;
                    }
                    else
                    {
                        List dataDicTionaries = new List();
                        //添加该字典的空选项
                        dataDicTionaries.Add(GroupField.DicData[0]);
                        if (dlbm.StartsWith("01"))
                        {
                            listValue = "WG,LS,FLS,LYFL,LLJZ".Split(',').ToList();
                        }
                        else if ("0201/0202/0203/0204/0301/0302/0305/0307/1104/1104A/0404".Split('/').Contains(dlbm))
                        {
                            listValue = "JKHF,GCHF".Split(',').ToList();
                        }
                        else if ("0201K/0202K/0203K/0204K/0301K/0302K/0307K/0403K/1104K".Split('/').Contains(dlbm))
                        {
                            dataDicTionaries.Clear();
                            listValue = "JKHF,GCHF".Split(',').ToList();
                        }
                        else if (dlbm.Equals("0404A"))
                        {
                            listValue = "GCHF".Split(',').ToList();
                        }
                        else
                        {
                            dataDicTionaries = GroupField.DicData;
                        }
                        foreach (string code in listValue)
                        {
                            DataDicTionary dataDicTionary = GroupField.DicData.FirstOrDefault(x => x.CODE.Equals(code));
                            if (dataDicTionary != null)
                            {
                                dataDicTionaries.Add(dataDicTionary);
                            }
                        }
                        GroupField.DicData = dataDicTionaries;
                        if (dataDicTionaries.FirstOrDefault(x => x.CODE.Equals(GroupField.Value)) == null)
                        {
                            GroupField.Value = string.Empty;
                        }
                    }
                }
                else if (item.AliasName.Equals("图斑细化") && !string.IsNullOrWhiteSpace(dlbm))
                {
                    List listValue = new List();
                    string lstDLBM = "0101/0102/0103/0201/0202/0203/0204/0201K/0202K/0203K/0204K/0301/0302/0305/0307/0404/0404A/0601/0602/1001/1003";
                    if (!lstDLBM.Split('/').Contains(dlbm))
                    {
                        GroupField.Value = string.Empty;
                        GroupField.Visible = false;
                    }
                    else
                    {
                        List dataDicTionaries = new List();
                        //添加该字典的空选项
                        dataDicTionaries.Add(GroupField.DicData[0]);
                        if (dlbm.StartsWith("01"))
                        {
                            listValue = "HDGD,HQGD,LQGD,MQGD,SHGD,SMGD,YJGD".Split(',').ToList();
                        }
                        else if (dlbm.StartsWith("02"))
                        {
                            listValue = new List() { "LQYD" };
                        }
                        else if (dlbm.StartsWith("03") || dlbm.Equals("0404A"))
                        {
                            listValue = new List() { "LJTM" };
                        }
                        else if (dlbm.Equals("0404"))
                        {
                            listValue = new List() { "LJTM", "GCCD" };
                        }
                        else if (dlbm.Equals("0601"))
                        {
                            listValue = "HDGY,GTGY,MTGY,SNGY,BLGY,DLGY".Split(',').ToList();
                        }
                        else if (dlbm.Equals("0602") || dlbm.Equals("1001") || dlbm.Equals("1003"))
                        {
                            listValue = new List() { "FQ" };
                        }
                        else
                        {
                            dataDicTionaries = GroupField.DicData;
                        }
                        foreach (string code in listValue)
                        {
                            DataDicTionary dataDicTionary = GroupField.DicData.FirstOrDefault(x => x.CODE.Equals(code));
                            if (dataDicTionary != null)
                            {
                                dataDicTionaries.Add(dataDicTionary);
                            }
                        }
                        GroupField.DicData = dataDicTionaries;
                        if (dataDicTionaries.FirstOrDefault(x => x.CODE.Equals(GroupField.Value)) == null)
                        {
                            //GroupField.Value = string.Empty;
                        }
                    }
                }
                else if (item.AliasName.Equals("项目类型") || item.AliasName.Equals("项目名称") || item.AliasName.Equals("项目编号") || item.AliasName.Equals("地块名称"))
                {
                    if (sfxml.Equals("1"))
                    {
                        GroupField.Visible = true;
                    }
                    else
                    {
                        GroupField.Visible = false;
                        GroupField.Value = string.Empty;
                    }
                }
            }
        }
        void PropertyChangedEvent(object sender, PropertyChangedEventArgs e)
        {
            try
            {
                //if (MyPropertyGrid.ItemsSource == null)
                //    return;
                PropertyGridDataStruct property = (PropertyGridDataStruct)sender;
                if (property != null)
                {
                    if (!property.Visible) return;
                    if (Data is IFeature)
                    {
                        int index = (Data as IFeature).Fields.FindField(property.Key);
                        if (index == -1)
                            index = (Data as IFeature).Fields.FindFieldByAliasName(property.Key);
                        if (index != -1)
                        {
                            SetFeatureValue(property);
                        }
                        else
                        {
                            //Property.FirstOrDefault(f=>f.Key== property.Key)
                            if (Cfg == null) return;
                            if (Cfg.Layers.Count == 0) return;
                            LayerInfo layer = Cfg.Layers[0];
                            var fieldItem = layer.Fields.FirstOrDefault(f => f.Name == property.Key || f.AliasName == property.Key);
                            if (property.Value == "-") { property.Value = " - "; }//地类信息处理
                            string[] values = property.Value.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                            if (values.Length != fieldItem.Fields.Count) return;
                            for (int i = 0; i < fieldItem.Fields.Count; i++)
                            {
                                var hidItem = Property.FirstOrDefault(f => f.Key == fieldItem.Fields[i].Name || f.Key == fieldItem.Fields[i].AliasName);
                                if (hidItem != null)
                                {
                                    hidItem.Value = values[i].ToTrim();
                                    SetFeatureValue(hidItem);
                                }
                            }
                            RefreshView();
                        }
                    }
                    //MyPropertyGrid.ItemsSource = MyPropertyGrid.ItemsSource;
                }
                IFeature feature = Data as IFeature;
                Platform.Instance.SendMsg(new NotifyMsgPackage() { Content = feature, MsgType = "RefreshViewAttrTable" });
                Platform.Instance.SendMsg(new NotifyMsgPackage() { Content = feature, MsgType = "StartCheckD_BGTBMethod" });
            }
            catch (Exception ex)
            {
                //LogAPI.Debug("属性联动异常:" + ex);
                LogAPI.Debug("属性改变事件期间 属性联动异常,异常信息如下:");
                LogAPI.Debug(ex);
                LogAPI.Debug("属性改变事件期间 属性联动异常信息结束");
            }
        }
        private void SetFeatureValue(PropertyGridDataStruct proData)
        {
            if (Data is IFeature)
            {
                int index = (Data as IFeature).Fields.FindField(proData.Key);
                if (index == -1)
                    index = (Data as IFeature).Fields.FindFieldByAliasName(proData.Key);
                if (index != -1)
                {
                    var val = (Data as IFeature).get_Value(index);
                    if (!val.Equals(proData.Value))
                    {
                        if (val is DBNull && string.IsNullOrWhiteSpace(proData.Value))
                        {
                        }
                        else
                        {
                            if (editor.EditState == esriEngineEditState.esriEngineStateEditing)
                            {
                                editor.StartOperation();
                                try
                                {
                                    if (proData.Key == "耕地等别" && string.IsNullOrEmpty(proData.Value))
                                    {
                                        (Data as IFeature).set_Value(index, DBNull.Value);
                                    }
                                    else if (proData.Key == "线状地物宽度" && string.IsNullOrEmpty(proData.Value))
                                    {
                                        (Data as IFeature).set_Value(index, DBNull.Value);
                                    }
                                    else
                                    {
                                        if ((Data as IFeature).Fields.get_Field(index).Length < proData.Value.Length)
                                        {
                                            MessageHelper.ShowError(proData.Key + ":填写值长度过长!");
                                            editor.AbortOperation();
                                            return;
                                        }
                                        (Data as IFeature).set_Value(index, proData.Value);
                                    }
                                    (Data as IFeature).Store();
                                    if (proData.Visible)
                                        RefreshView();
                                    if (editor.EditState == esriEngineEditState.esriEngineStateEditing)
                                    {
                                        editor.StopOperation("Attribute update");
                                        ExecuteDataCheck(Data as IFeature);
                                    }
                                }
                                catch (Exception ex2)
                                {
                                    LogAPI.Debug("属性改变事件中 结束编辑操作期间 时异常,异常信息如下:");
                                    LogAPI.Debug(ex2);
                                    LogAPI.Debug("属性改变事件中 结束编辑操作期间 时异常信息结束");
                                    editor.AbortOperation();
                                }
                            }
                        }
                    }
                }
            }
        }
        ControlsEditingSaveCommandClass saveCmd = null;
        public void SaveEdit()
        {
            //if (saveCmd == null)
            //{
            //    saveCmd = new ControlsEditingSaveCommandClass();
            //    saveCmd.OnCreate(MapsManager.Instance.MapService.Hook);
            //}
            //if (saveCmd.Enabled)
            //{
            //    saveCmd.OnClick();
            //}
            SetVisible(Property);
        }
        public void ExecuteDataCheck(IFeature feature)
        {
            if (editor.EditState != esriEngineEditState.esriEngineStateEditing)
                return;
            IDataCheckHelper dataCheckHelper = UIShell.OSGi.BundleRuntime.Instance.GetFirstOrDefaultService();
            if (dataCheckHelper == null) return;
            dataCheckHelper.DataCheckByThread(new CheckParametr()
            {
                CheckType = enumCheckType.Attribute | enumCheckType.Graphic,
                DataSource = feature,
                IDataCheckName = "BGQDataCheck"
            });
        }
        private List GetNoGroupDic(DicTypeEnum pDicType, List dicList = null)
        {
            List result = null;
            try
            {
                string s = GetDicTypeID(pDicType);
                if (string.IsNullOrWhiteSpace(s))
                    return result;
                List tempDic = dicList;
                if (dicList == null || dicList.Count == 0)
                    tempDic = GetAllDic();
                if (tempDic == null)
                    return result;
                foreach (DataDicTionary item in tempDic)
                {
                    if (item.OWNERDIC == s)
                    {
                        if (result == null)
                        {
                            result = new List();
                            result.Add(new DataDicTionary() { CODE = "", NAME = "", DisplayName = "" });
                        }
                        result.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }
        private List GetAllDic()
        {
            DataTable dt = null;
            List result = new List();
            IRDBHelper rdbHelper = null;
            try
            {
                if ((MapsManager.Instance.CurrProjectInfo as ProjectInfo) != null)
                {
                    string dbPath = ((MapsManager.Instance.CurrProjectInfo as ProjectInfo) as ProjectInfo).GetDicDataPath();
                    if (!string.IsNullOrWhiteSpace(dbPath))
                    {
                        rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
                        string strSQL = "select * from Sys_DicDetail";
                        dt = rdbHelper.ExecuteDatatable("Dic", strSQL, true);
                        if (dt != null)
                        {
                            result = KGIS.Framework.Utils.Utility.TBToList.ToList(dt).OrderBy(x => x.CODE).ToList();
                            result.ForEach(x => x.DisplayName = x.CODE + "-" + x.NAME);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
            }
            finally
            {
                if (rdbHelper != null)
                {
                    rdbHelper.DisConnect();
                }
                if (dt != null)
                {
                    dt.Clear();
                    dt.Dispose();
                }
            }
            return result;
        }
        private Dictionary DicTypes = new Dictionary();
        public string GetDicTypeID(DicTypeEnum pDicType, bool GetNewDic = false)
        {
            string result = string.Empty;
            DataTable dtDicTypeID = null;
            try
            {
                if (dtDicTypeID == null || GetNewDic)
                {
                    IRDBHelper rdbHelper = null;
                    try
                    {
                        string dbPath = ((MapsManager.Instance.CurrProjectInfo as ProjectInfo) as ProjectInfo).GetDicDataPath();
                        if (string.IsNullOrWhiteSpace(dbPath))
                        {
                            LogAPI.Debug("GetDicDataPath 获取失败");
                        }
                        rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
                        string strSQL = "select ID,ALIASNAME from Sys_DicManage ";//WHERE ALIASNAME = '" + pDicType + "'";
                        dtDicTypeID = rdbHelper.ExecuteDatatable("DicType", strSQL, true);
                    }
                    catch (Exception ex)
                    {
                        LogAPI.Debug(ex);
                    }
                    finally
                    {
                        if (rdbHelper != null)
                        {
                            rdbHelper.DisConnect();
                        }
                    }
                }
                if (dtDicTypeID != null && dtDicTypeID.Rows.Count > 0)
                {
                    foreach (DataRow item in dtDicTypeID.Rows)
                    {
                        if (item[0] != null && !(item[0] is DBNull))
                        {
                            if (item[1].ToString() == pDicType.ToString())
                                result = item[0].ToString();
                            if (DicTypes.ContainsKey(item[0].ToString()))
                                continue;
                            DicTypes.Add(item[0].ToString(), item[1].ToString());
                        }
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (dtDicTypeID != null)
                {
                    dtDicTypeID.Clear();
                    dtDicTypeID.Dispose();
                }
            }
            return string.Empty;
        }
    }
}