using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.Geoprocessor;
using KGIS.Framework.AE;
using KGIS.Framework.AE.GPHelper;
using KGIS.Framework.Core.Services;
using KGIS.Framework.Maps;
using KGIS.Framework.OpenData.Control;
using KGIS.Framework.OpenData.Filter;
using KGIS.Framework.OpenData.InterFace;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.ExtensionMethod;
using KGIS.Framework.Utils.Helper;
using Kingo.PluginServiceInterface;
using KUI.Windows;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Xml;
using UIShell.OSGi;
namespace Kingo.Plugin.DataLoad.Views
{
    /// 
    /// FrmDataImport.xaml 的交互逻辑
    /// 
    public partial class FrmDataImport : BaseWindow
    {
        public Action ImpComplate;
        private bool _AllowEdit = true;
        public bool AllowEdit
        {
            get { return _AllowEdit; }
            set
            {
                _AllowEdit = value;
                //validationContainer.IsEnabled = value;
            }
        }
        private bool IsJCTB;
        private bool IsBGTB;
        private string _DataSourcePath;
        /// 
        /// 数据源路径
        /// 
        public string DataSourcePath
        {
            get { return _DataSourcePath; }
            set
            {
                _DataSourcePath = value;
            }
        }
        private IFeatureLayer _TargetLayer;
        /// 
        /// 目标图层
        /// 
        public IFeatureLayer TargetLayer
        {
            get
            {
                return _TargetLayer;
            }
            set
            {
                _TargetLayer = value;
                if (_TargetLayer != null)
                    txtTargetLayer.EditValue = _TargetLayer.Name;
            }
        }
        private IFeatureClass _SourceFeatureClass;
        /// 
        /// 数据源
        /// 
        public IFeatureClass SourceFeatureClass
        {
            get { return _SourceFeatureClass; }
            set { _SourceFeatureClass = value; }
        }
        private List listRuleTableEntity
        {
            get;
            set;
        }
        string strWhere = string.Empty;
        public FrmDataImport()
        {
            InitializeComponent();
            this.CustomToolTip = "导入的源数据需保证与目标图层类型一致且字段长度不大于目标字段长度";
            listRuleTableEntity = GetListRuleTableEntity();
            if (Platform.Instance.SystemType == SystemTypeEnum.BGFWCG)
            {
                cbTBLoadBGData.Visibility = Visibility.Collapsed;
                cbHitchBGData.Visibility = Visibility.Collapsed;
            }
        }
        public void InitData()
        {
            if (TargetLayer.FeatureClass.AliasName != "监测图斑" && TargetLayer.FeatureClass.AliasName != "自主变更图斑" && this.Title != "监测数据加载")
            {
                cbTBLoadBGData.IsChecked = false;
                cbTBLoadBGData.Visibility = Visibility.Collapsed;
                cbHitchBGData.Visibility = Visibility.Collapsed;
                FunctionalAnnotation.Visibility = Visibility.Collapsed;
                ImprotFeatureData.RowDefinitions.RemoveAt(2);
                if (TargetLayer.FeatureClass.AliasName == "地类图斑变更层")
                {
                    cbTBLoadJCData.Visibility = Visibility.Visible;
                    IsBGTB = true;
                }
            }
            else
            {
                IsJCTB = true;
                panelSJLY.Visibility = Visibility.Visible;
                cbHitchBGData.IsChecked = false;
                if (TargetLayer.Name == "国家监测图斑")
                {
                    rdGJJC.IsChecked = true;
                    rdZZBG.IsChecked = false;
                }
                else
                {
                    rdGJJC.IsChecked = false;
                    rdZZBG.IsChecked = true;
                }
            }
            if (this.Title == "监测数据加载")
            {
                rdGJJC.IsEnabled = true;
                rdZZBG.IsEnabled = true;
            }
            txtTargetSP.EditValue = (TargetLayer.FeatureClass as IGeoDataset).SpatialReference.Name;
        }
        /// 
        /// 根据表名获取检查表映射,lstTableName若参数为空则查询出所有的表映射
        /// 
        /// 
        /// 
        public static List GetListRuleTableEntity(List lstTableName = null)
        {
            List lstRuleTableEntity = new List();
            try
            {
                XmlDocument doc = new XmlDocument();
                string strPath = SysAppPath.GetDataCheckTableMappingConfigPath();
                if (System.IO.File.Exists(strPath))
                {
                    doc.Load(strPath);
                    if (doc != null)
                    {
                        #region 获取规则检查TableMapping
                        XmlNodeList nodeTableMappingList = doc.SelectNodes("CheckTableMapping");
                        if (nodeTableMappingList != null && nodeTableMappingList.Count > 0)
                        {
                            foreach (XmlNode checkTableNode in nodeTableMappingList)
                            {
                                foreach (XmlNode tableNode in checkTableNode.ChildNodes)
                                {
                                    if (tableNode.Attributes["TableName"] == null || string.IsNullOrWhiteSpace(tableNode.Attributes["TableName"].Value))
                                    {
                                        continue;
                                    }
                                    //如果参数不为空,则只返回参数里的表结构
                                    if (lstTableName != null && lstTableName.Count > 0 && !lstTableName.Contains(tableNode.Attributes["TableName"].Value))
                                    {
                                        continue;
                                    }
                                    RuleTableEntity pRuleTableEntity = new RuleTableEntity();
                                    pRuleTableEntity.Columns = new List();
                                    pRuleTableEntity.TableName = tableNode.Attributes["TableName"].Value;
                                    if (tableNode.Attributes["Name"] != null)
                                    {
                                        pRuleTableEntity.TableAliasName = tableNode.Attributes["Name"].Value;
                                    }
                                    if (tableNode.Attributes["Type"] != null)
                                    {
                                        pRuleTableEntity.Type = tableNode.Attributes["Type"].Value;
                                    }
                                    if (tableNode.Attributes["YSDM"] != null)
                                    {
                                        pRuleTableEntity.YSDM = tableNode.Attributes["YSDM"].Value;
                                    }
                                    if (tableNode.Attributes["CDM"] != null)
                                    {
                                        pRuleTableEntity.CDM = tableNode.Attributes["CDM"].Value;
                                    }
                                    if (tableNode.Attributes["IsNecessary"] != null)
                                    {
                                        bool b = false;
                                        if (bool.TryParse(tableNode.Attributes["IsNecessary"].Value, out b))
                                        {
                                        }
                                        pRuleTableEntity.IsNecessary = b;
                                    }
                                    #region 表结构的列
                                    foreach (XmlNode columnNode in tableNode.ChildNodes)
                                    {
                                        RuleColumnEntity pRuleColumnEntity = new RuleColumnEntity();
                                        if (columnNode.Attributes["Name"] != null)
                                        {
                                            pRuleColumnEntity.ColumnName = columnNode.Attributes["Name"].Value.Trim();
                                        }
                                        if (columnNode.Attributes["AliasName"] != null)
                                        {
                                            pRuleColumnEntity.AliasName = columnNode.Attributes["AliasName"].Value.Trim();
                                        }
                                        if (columnNode.Attributes["Range"] != null)
                                        {
                                            pRuleColumnEntity.Range = columnNode.Attributes["Range"].Value;
                                        }
                                        if (columnNode.Attributes["ToolTip"] != null)
                                        {
                                            pRuleColumnEntity.ToolTip = columnNode.Attributes["ToolTip"].Value;
                                        }
                                        if (columnNode.Attributes["Pic"] != null)
                                        {
                                            pRuleColumnEntity.Pic = columnNode.Attributes["Pic"].Value;
                                        }
                                        pRuleColumnEntity.AllowDBNull = false;
                                        //字段是否可为空:如果未配置则默认为false:标识当前字段为必填项,不可为空
                                        if (columnNode.Attributes["AllowDBNull"] != null)
                                        {
                                            bool b = false;
                                            if (bool.TryParse(columnNode.Attributes["AllowDBNull"].Value.Trim(), out b))
                                            {
                                            }
                                            pRuleColumnEntity.AllowDBNull = b;
                                        }
                                        pRuleColumnEntity.IsUnique = false;
                                        //字段值是否必须唯一:如果未配置则默认为false:表示当前字段不是必须唯一,可重复
                                        if (columnNode.Attributes["IsUnique"] != null)
                                        {
                                            bool b = false;
                                            if (bool.TryParse(columnNode.Attributes["IsUnique"].Value.Trim(), out b))
                                            {
                                            }
                                            pRuleColumnEntity.IsUnique = b;
                                        }
                                        pRuleColumnEntity.DataType = "string";
                                        if (columnNode.Attributes["DataType"] != null)
                                        {
                                            pRuleColumnEntity.DataType = columnNode.Attributes["DataType"].Value.Trim();
                                        }
                                        pRuleColumnEntity.IllegalityCheck = true;
                                        //如果不是字符串类型的字段则不检查
                                        //字段值非法字符检查:如果未配置则默认为false:表示需要检查非法字符
                                        if (pRuleColumnEntity.DataType != "string")
                                        {
                                            pRuleColumnEntity.IllegalityCheck = false;
                                        }
                                        else
                                        {
                                            pRuleColumnEntity.IllegalityCheck = true;
                                        }
                                        if (columnNode.Attributes["IllegalityNotCheck"] != null)
                                        {
                                            bool b = false;
                                            if (bool.TryParse(columnNode.Attributes["IllegalityNotCheck"].Value.Trim(), out b))
                                            {
                                            }
                                            pRuleColumnEntity.IllegalityCheck = b;
                                        }
                                        if (columnNode.Attributes["MaxLength"] != null)
                                        {
                                            int max = 0;
                                            if (int.TryParse(columnNode.Attributes["MaxLength"].Value.Trim(), out max))
                                            {
                                            }
                                            pRuleColumnEntity.MaxLength = max;
                                        }
                                        if (columnNode.Attributes["Precision"] != null)
                                        {
                                            int precision = 0;
                                            if (int.TryParse(columnNode.Attributes["Precision"].Value.Trim(), out precision))
                                            {
                                            }
                                            pRuleColumnEntity.Precision = precision;
                                        }
                                        if (columnNode.Attributes["Dic"] != null)
                                        {
                                            pRuleColumnEntity.DIC = columnNode.Attributes["Dic"].Value.Trim();
                                        }
                                        pRuleColumnEntity.IsEllipsoidArea = false;
                                        if (columnNode.Attributes["IsEllipsoidArea"] != null)
                                        {
                                            bool b = false;
                                            if (bool.TryParse(columnNode.Attributes["IsEllipsoidArea"].Value.Trim(), out b))
                                            {
                                            }
                                            pRuleColumnEntity.IsEllipsoidArea = b;
                                        }
                                        pRuleColumnEntity.ExtendField = false;
                                        if (columnNode.Attributes["ExtendField"] != null)
                                        {
                                            bool b = false;
                                            if (bool.TryParse(columnNode.Attributes["ExtendField"].Value.Trim(), out b))
                                            {
                                            }
                                            pRuleColumnEntity.ExtendField = b;
                                        }
                                        pRuleTableEntity.Columns.Add(pRuleColumnEntity);
                                    }
                                    #endregion
                                    lstRuleTableEntity.Add(pRuleTableEntity);
                                }
                            }
                        }
                        #endregion
                    }
                }
                return lstRuleTableEntity;
            }
            catch (Exception ex)
            {
                LogAPI.Debug("根据表名获取检查表映射,lstTableName若参数为空则查询出所有的表映射 时异常,异常信息如下:");
                LogAPI.Debug(ex);
                LogAPI.Debug("根据表名获取检查表映射,lstTableName若参数为空则查询出所有的表映射 时异常信息结束");
                throw new ArgumentNullException("加载CheckConfig的CheckTableMapping配置文件失败");
            }
        }
        private void BtnSelectedImportDataPath_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (TargetLayer == null)
                {
                    MessageHelper.ShowTips("目标图层不能为空!");
                    return;
                }
                OpenDataDialog pDialog = new OpenDataDialog();
                ISpatialDataObjectFilter pOFilter;
                pOFilter = new FilterDatasetsAndLayers();
                pDialog.AddFilter(pOFilter, true);
                pDialog.Title = "选择导入的数据";
                pDialog.AllowMultiSelect = false;
                pDialog.RestoreLocation = true;
                pDialog.StartLocation = pDialog.FinalLocation;
                System.Windows.Forms.DialogResult dialogResult = pDialog.ShowDialog();
                if (dialogResult == System.Windows.Forms.DialogResult.OK && pDialog.Selection.Count != 0)
                {
                    this.ShowLoading("正在进行数据校验中......", 0, 0);
                    foreach (ISpatialDataObject distObj in pDialog.Selection)
                    {
                        if (distObj.DatasetType == esriDatasetType.esriDTFeatureClass)
                        {
                            btnImportDataPath.EditValue = pDialog.FinalLocation;
                            SourceFeatureClass = (distObj.DatasetName as IName).Open() as IFeatureClass;
                            if (SourceFeatureClass == null)
                            {
                                MessageHelper.Show("源数据打开失败,请检查是否选择正确数据!");
                                this.Close();
                            }
                            if ((SourceFeatureClass as FeatureClass).Workspace.Type != esriWorkspaceType.esriRemoteDatabaseWorkspace)
                            {
                                IFeatureClassManage fcManage = SourceFeatureClass as IFeatureClassManage;
                                fcManage.UpdateExtent();
                            }
                            txtSourceSP.EditValue = (SourceFeatureClass as IGeoDataset).SpatialReference.Name;
                            IEnvelope envelope = (SourceFeatureClass as IGeoDataset).Extent;
                            if (string.IsNullOrWhiteSpace(RunIDService2.Instance.Area))
                            {
#if DEBUG
#else
                            MessageHelper.Show("未能获取有效的授权信息。");
                            return;
#endif
                            }
                            else if (envelope.IsEmpty)
                            {
                                MessageHelper.Show("选择的图层数据为空!");
                                return;
                            }
                            if (!string.IsNullOrWhiteSpace(RunIDService2.Instance.Area))
                            {
#if DEBUG
#else
                                if (!Kingo.PluginServiceInterface.Helper.AuthorizationVerification.VerifyRange(SourceFeatureClass))
                                {
                                    btnImportDataPath.EditValue = "";
                                    SourceFeatureClass = null;
                                    MessageHelper.Show("当前选择数据不在授权范围内");
                                    return;
                                }
#endif
                            }
                            System.Threading.Thread.Sleep(1000);
                            this.CloseLoading();
                            SetFieldMapping();
                        }
                    }
                    this.CloseLoading();
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Cannot acquire a lock"))
                {
                    MessageHelper.ShowError("选择导入数据发生异常:" + "文件已被其他软件占用!");
                    btnImportDataPath.EditValue = "";
                }
                else
                    MessageHelper.ShowError("选择导入数据发生异常:" + ex.Message);
                LogAPI.Debug("选择导入数据发生异常:" + ex);
            }
            finally
            {
                this.CloseLoading();
            }
        }
        /// 
        /// 设置字段映射
        /// 
        public void SetFieldMapping()
        {
            try
            {
                //选择的不为空且数据类型一致
                if (SourceFeatureClass != null && SourceFeatureClass.ShapeType == TargetLayer.FeatureClass.ShapeType)
                {
                    List dicData = new List
                    {
                        new DataDicTionary() { DisplayName = "Null", NAME = "Null", CODE = "-1", REMARK = "" },
                        new DataDicTionary() { DisplayName = "追加字段", NAME = "Add", CODE = "-2", REMARK = "" }
                    };
                    for (int i = 0; i < TargetLayer.FeatureClass.Fields.FieldCount; i++)
                    {
                        IField field = TargetLayer.FeatureClass.Fields.get_Field(i);
                        if (!field.Editable || field.Name.ToUpper() == "SHAPE") continue;
                        dicData.Add(new DataDicTionary() { DisplayName = string.IsNullOrWhiteSpace(field.AliasName) ? field.Name : field.AliasName, NAME = field.Name.ToUpper(), CODE = i.ToString(), REMARK = field.Type.ToString() });
                    }
                    List data = new List();
                    for (int i = 0; i < SourceFeatureClass.Fields.FieldCount; i++)
                    {
                        IField field = SourceFeatureClass.Fields.get_Field(i);
                        if (!field.Editable || field.Name.ToUpper() == "SHAPE") continue;
                        FieldMapping item = new FieldMapping();
                        item.S_FieldName = string.IsNullOrWhiteSpace(field.AliasName) ? field.Name : field.AliasName;
                        item.S_FieldIndex = i;
                        DataDicTionary dic = dicData.FirstOrDefault(f => (f.NAME.ToUpper() == field.Name.ToUpper() || f.DisplayName == field.Name || f.NAME == field.AliasName || f.DisplayName == field.AliasName));//&& f.REMARK == field.Type.ToString()
                        if (dic != null)
                        {
                            item.T_FieldName = dic.DisplayName;
                            item.T_FieldIndex = Convert.ToInt16(dic.CODE);
                        }
                        else
                        {
                            item.T_FieldIndex = -1;
                        }
                        //item.PropertyType = enumPropertyType.ComboBox;
                        item.FieldList = dicData.FindAll(f => f.REMARK == field.Type.ToString() || f.REMARK.Contains("Double") || f.REMARK.Contains("Integer") || f.CODE == "-1" || f.CODE == "-2");
                        data.Add(item);
                    }
                    dgFieldMapping.ItemsSource = data;
                }
                //提示不明确或缺少提示    王欢  2018-09-19 
                else
                {
                    MessageHelper.ShowTips("选择数据不正确,请确认数据是否为空或格式是否正确!");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageHelper.ShowError("数据导入SetFieldMapping异常:" + ex.Message);
                PluginServiceInterface.CommonHelper.RecordsErrLog("数据导入SetFieldMapping异常:", ex);
            }
        }
        private bool AllowProject;
        private void BtnOK_Click(object sender, RoutedEventArgs e)
        {
            int RowCount = 0;
            int ImportRowCount = 0;
            IWorkspaceEdit pWsEdit = null;
            try
            {
                if (string.IsNullOrEmpty(btnImportDataPath.Text))
                {
                    MessageHelper.ShowTips("请先选择导入数据文件的路径!");
                    return;
                }
                //SourceFeatureClass.CheckArea();
                #region 判断数据源,坐标系一致性
                IFeatureClass t_FC = TargetLayer.FeatureClass;
                if ((SourceFeatureClass as FeatureClass).Workspace.PathName.Equals((t_FC as FeatureClass).Workspace.PathName))
                {
                    if (SourceFeatureClass.Equals(t_FC))
                    {
                        MessageHelper.Show("选择导入的文件与工程加载的文件是同一个文件,数据不允许导入!");
                        return;
                    }
                }
                //外部图层FeatureDataset为空,bug11428
                if ((t_FC as FeatureClass).Workspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
                {
                    IEngineEditor edit = new EngineEditorClass();
                    if (edit.EditState == esriEngineEditState.esriEngineStateNotEditing)
                    {
                        MessageHelper.ShowTips("网络版数据库需要开启编辑后,再进行导入!");
                        return;
                    }
                }
                if (t_FC is IGeoDataset && SourceFeatureClass is IGeoDataset)
                {
                    IGeoDataset t_Ds = t_FC as IGeoDataset;
                    IGeoDataset s_Ds = SourceFeatureClass as IGeoDataset;
                    if (t_Ds.SpatialReference != null && s_Ds.SpatialReference != null)
                    {
                        if (string.IsNullOrEmpty(t_Ds.SpatialReference.Name) || t_Ds.SpatialReference.Name.ToUpper().Equals("UNKNOWN"))
                        {
                            GeoDBAPI.SetGeoDatasetSpatialReference((t_FC as FeatureClass).Workspace, s_Ds.SpatialReference, 0.0001);
                        }
                        else if (!GeoDBAPI.SpatialReferenceCompare(t_Ds.SpatialReference, s_Ds.SpatialReference))
                        {
                            if (s_Ds.SpatialReference is IGeographicCoordinateSystem && t_Ds.SpatialReference is IProjectedCoordinateSystem)
                            {
                                if (MessageHelper.ShowYesNoAndTips("源图层为非投影坐标系,是否转换为投影坐标系后继续导入?") != System.Windows.Forms.DialogResult.Yes)
                                {
                                    AllowProject = false;
                                    return;
                                }
                                else
                                {
                                    AllowProject = true;
                                }
                            }
                            else
                            {
                                MessageHelper.ShowTips("源要素坐标系与目标要素类坐标系不一致,无法进行数据导入!");
                                return;
                            }
                        }
                    }
                }
                #endregion
                RuleTableEntity ruleTableEntity = null;
                if (listRuleTableEntity != null && listRuleTableEntity.Count > 0)
                {
                    ruleTableEntity = listRuleTableEntity.FirstOrDefault(x => x.TableName == (t_FC as FeatureClass).BrowseName);
                }
                IDataset pDataset = t_FC as IDataset;
                IWorkspace pWs = pDataset.Workspace;
                pWsEdit = pWs as IWorkspaceEdit;
                //pWsEdit.StartEditing(true);
                pWsEdit.StartEditOperation();
                if (cbReplace.IsChecked == true)
                {
                    IQueryFilter queryfilter = new QueryFilterClass();
                    string checkedType = "";
                    if (rdZZBG.IsVisible && rdZZBG.IsChecked == true)
                        checkedType = rdZZBG.Content.ToString();
                    else if (rdGJJC.IsVisible && rdGJJC.IsChecked == true)
                        checkedType = rdGJJC.Content.ToString();
                    int sjlyIndex = TargetLayer.FeatureClass.FindField("SJLY");
                    if (checkedType == "国家监测图斑")
                    {
                        queryfilter.WhereClause = string.Format("SJLY='GJJC'");
                    }
                    else if (checkedType == "自主变更图斑")
                    {
                        queryfilter.WhereClause = string.Format("SJLY='ZZBG'");
                    }
                    else if (checkedType == "无人机举证图斑")
                    {
                        queryfilter.WhereClause = string.Format("SJLY='WRJJZ'");
                    }
                    else
                    {
                        queryfilter.WhereClause = string.Format("1=1");
                    }
                    var FeatureCount = t_FC.FeatureCount(queryfilter);
                    if (FeatureCount > 0)
                    {
                        if (MessageHelper.ShowYesNoAndTips(string.Format("是否确定要覆盖当前{0}数据?覆盖后数据不可恢复,请谨慎操作!", checkedType)) == System.Windows.Forms.DialogResult.Yes)
                        {
                            //清除数据
                            ITable pTable = t_FC as ITable;
                            pTable.DeleteSearchedRows(queryfilter);
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                this.ShowLoading("正在载入数据中.........", 0, 0);
                System.Threading.Thread.Sleep(1000);
                //修复自相交及空图形数据
                if ((t_FC as IDataset).Name == "DLTBBG")
                    RepairGeoData(SourceFeatureClass, true);
                string str = btnSQLDataPath.Text;
                IQueryFilter filter = GeoDBAPI.CreateQueryFilter(str);
                object BGInsertIndex = null;
                using (ComReleaser releaser = new ComReleaser())
                {
                    //字段映射信息
                    List mFieldMapping = dgFieldMapping.ItemsSource as List;
                    #region 新增字段
                    //提示不明确或缺少提示    王欢  2018-09-19
                    if (mFieldMapping == null)
                    {
                        MessageHelper.ShowTips("无法获取字段映射信息,数据导入失败!");
                        return;
                    }
                    List addFields = mFieldMapping.FindAll(f => f.T_FieldIndex == -2);
                    IFeatureClassAPI t_FcAPI = new FeatureClassAPI(t_FC);
                    foreach (FieldMapping item in addFields)
                    {
                        IField f = SourceFeatureClass.Fields.get_Field(item.S_FieldIndex);
                        if (t_FC.FindField(f.Name) > -1)
                        {
                            t_FcAPI.AddField(f.Name + "_a", f.Type, f.AliasName);
                            item.T_FieldIndex = t_FC.Fields.FindField(f.Name + "_a");
                        }
                        else
                        {
                            t_FcAPI.AddField(f.Name, f.Type, f.AliasName);
                            item.T_FieldIndex = t_FC.Fields.FindField(f.Name);
                        }
                    }
                    #endregion
                    IFeatureClassLoad t_FClsLoad = t_FC as IFeatureClassLoad;
                    if (t_FClsLoad != null)
                        t_FClsLoad.LoadOnlyMode = true;
                    IFeatureCursor cursor = t_FC.Insert(true);
                    IFeatureBuffer newFeature = null;
                    releaser.ManageLifetime(cursor);
                    IFeatureCursor s_Cursor = SourceFeatureClass.Update(filter, true);
                    releaser.ManageLifetime(s_Cursor);
                    this.UpdateMsg(string.Format("正在导入【{0}】数据……", TargetLayer.Name));
                    int Count = SourceFeatureClass.FeatureCount(filter);
                    RowCount = Count;
                    int i = 0;
                    IFeature feature = null;
                    int idxGXSJ = t_FC.FindField("GXSJ");
                    ISpatialReference t_SR = (t_FC as IGeoDataset).SpatialReference;
                    int idxSJLY, idxSFJZ, idxBSM, idxTBBH, idxJCBH, idxTBYBH;
                    idxSJLY = t_FC.FindField("SJLY");
                    idxSFJZ = t_FC.FindField("SFJZ");
                    idxBSM = t_FC.FindField("BSM");
                    idxTBBH = t_FC.FindField("TBBH");
                    idxJCBH = t_FC.FindField("JCBH");
                    idxTBYBH = t_FC.FindField("TBYBH");
                    int idxS_JCBH = SourceFeatureClass.FindField("JCBH");
                    int idxS_TBYBH = SourceFeatureClass.FindField("TBYBH");
                    while ((feature = s_Cursor.NextFeature()) != null)
                    {
                        newFeature = t_FC.CreateFeatureBuffer();
                        IGeometry pGeo = feature.ShapeCopy;
                        //白明雅 2019-02-13 自己画的数据报错,添加判断
                        if (pGeo == null || pGeo.IsEmpty == true)
                        {
                            LogAPI.Debug("OID:" + feature.OID + " 缺少图像数据(IGeometry)");
                            continue;
                        }
                        //-------------------------
                        if (AllowProject)
                        {
                            pGeo.Project(t_SR);
                        }
                        IZAware pZAware = pGeo as IZAware;
                        pZAware.ZAware = false;
                        newFeature.Shape = pGeo;
                        foreach (FieldMapping item in mFieldMapping)
                        {
                            if (item.S_FieldIndex < 0 || item.T_FieldIndex < 0)
                                continue;
                            #region 判断字段类型是否需要保存精度
                            if (ruleTableEntity != null)
                            {
                                RuleColumnEntity ruleColumnEntity = ruleTableEntity.Columns.FirstOrDefault(x => x.ColumnName == t_FC.Fields.Field[item.T_FieldIndex].Name.ToString());
                                if (ruleColumnEntity != null && ruleColumnEntity.Precision > 0 && !(feature.get_Value(item.S_FieldIndex) is DBNull))
                                {
                                    switch (ruleColumnEntity.DataType.ToLower())
                                    {
                                        case "float":
                                            float valueFloat;
                                            if (float.TryParse((feature.get_Value(item.S_FieldIndex).ToString()), out valueFloat))
                                            {
                                                newFeature.set_Value(item.T_FieldIndex, feature.get_Value(item.S_FieldIndex));
                                                continue;
                                            }
                                            break;
                                        case "double":
                                            double valueDouble;
                                            if (double.TryParse((feature.get_Value(item.S_FieldIndex).ToString()), out valueDouble))
                                            {
                                                newFeature.set_Value(item.T_FieldIndex, Math.Round(valueDouble, ruleColumnEntity.Precision, MidpointRounding.AwayFromZero));
                                                continue;
                                            }
                                            break;
                                    }
                                }
                            }
                            #endregion
                            IField T_field = t_FC.Fields.Field[item.T_FieldIndex];
                            if (feature.get_Value(item.S_FieldIndex) is DBNull)
                            {
                                newFeature.set_Value(item.T_FieldIndex, DBNull.Value);
                            }
                            else if (T_field != null && feature.get_Value(item.S_FieldIndex).ToTrim().Length > T_field.Length)
                            {   //截取字段长度值赋值
                                string S_Value = feature.get_Value(item.S_FieldIndex).ToString().Substring(0, T_field.Length);
                                newFeature.Value[item.T_FieldIndex] = S_Value;
                            }
                            else
                            {
                                newFeature.set_Value(item.T_FieldIndex, feature.get_Value(item.S_FieldIndex));
                            }
                        }
                        if (IsJCTB)
                        {
                            int ztIndex = t_FC.FindField("ZT");
                            if (idxSJLY != -1)
                            {
                                newFeature.Value[idxSJLY] = rdGJJC.IsChecked == true ? "GJJC" : "ZZBG";
                            }
                            if (idxSFJZ != -1)
                            {
                                newFeature.set_Value(idxSFJZ, "0");//“是否举证”暂设置默认值
                            }
                            if (idxBSM != -1)
                            {
                                string bsm = newFeature.Value[idxBSM].ToTrim();
                                if (string.IsNullOrWhiteSpace(bsm) || bsm.Length > 18)
                                {
                                    bsm = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 18);
                                    newFeature.Value[idxBSM] = bsm;
                                }
                            }
                            //源数据同步加载到变更范围图层-举证包设置功能
                            if (idxTBBH != -1)
                            {
                                string TBBHValue = newFeature.Value[idxTBBH].ToTrim();
                                if (string.IsNullOrWhiteSpace(TBBHValue) && idxS_JCBH != -1)
                                {
                                    newFeature.Value[idxTBBH] = feature.Value[idxS_JCBH];
                                }
                            }
                            if (ztIndex != -1)
                            {
                                newFeature.Value[ztIndex] = "未完成";
                            }
                        }
                        else if (IsBGTB)
                        {
                            //源数据同步到监测图层并挂接变更图层-建库图斑变更功能
                            if (idxS_TBYBH != -1 && idxTBYBH != -1 && cbHitchBGData.IsChecked == true)
                            {
                                string ValueTBYBH = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 18).ToUpper();
                                newFeature.Value[idxTBYBH] = ValueTBYBH;
                                newFeature.Value[idxBSM] = ValueTBYBH;
                            }
                        }
                        if (idxGXSJ != -1)
                        {
                            newFeature.Value[idxGXSJ] = DateTime.Now.Month >= 10 ? new DateTime(DateTime.Now.Year, 12, 31) : new DateTime(DateTime.Now.Year - 1, 12, 31);
                        }
                        object OIDInsert = cursor.InsertFeature(newFeature);
                        if (i == 0) BGInsertIndex = OIDInsert;
                        i++;
                        ImportRowCount = i;
                        newFeature = null;
                    }
                    pWsEdit.StopEditOperation();
                    cursor?.Flush();
                    if (t_FClsLoad != null)
                        t_FClsLoad.LoadOnlyMode = false;
                    if (s_Cursor != null && IsJCTB)
                        s_Cursor.Flush();
                    if ((t_FC as FeatureClass).Workspace.Type != esriWorkspaceType.esriRemoteDatabaseWorkspace)
                    {
                        IFeatureClassManage fcManage = t_FC as IFeatureClassManage;
                        fcManage.UpdateExtent();
                    }
                    try
                    {
                        t_FcAPI.AddIndex();
                    }
                    catch (Exception ex)
                    {
                        LogAPI.Debug("重建空间索引失败!");
                        LogAPI.Debug(ex);
                    }
                }
                ImpComplate?.Invoke(true);
                IFeatureClass featureClass = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBBG");
                //同步加载到变更范围图斑
                if (cbTBLoadBGData.IsChecked == true)
                {
                    ProjectInfo info = MapsManager.Instance.CurrProjectInfo as ProjectInfo;
                    IFeatureClassAPI featureClassAPI_GJJCTB = new FeatureClassAPI(MapsManager.Instance.MapService.GetFeatureClassByName("JCTB"));
                    int JCJCBHIndex = featureClassAPI_GJJCTB.FeatureClass.FindField("JCBH");
                    int JCBGDLIndex = featureClassAPI_GJJCTB.FeatureClass.FindField("TBLX");
                    int JCBGFWIndex = featureClassAPI_GJJCTB.FeatureClass.FindField("KZXX");
                    //清除数据
                    ITable tablebg = featureClass as ITable;
                    tablebg.DeleteSearchedRows(null);
                    int BGTBYBHIndex = featureClass.FindField("TBYBH");
                    int BGDLBMIndex = featureClass.FindField("DLBM");
                    int BGSFJCTBIndex = featureClass.FindField("SFJCTB");
                    int TZIndex = featureClass.FindField("TZ");
                    int BGDLIndex = featureClass.FindField("BGDL");
                    int BGFWIndex = featureClass.FindField("BGFW");
                    int WBGLXIndex = featureClass.FindField("WBGLX");
                    int SJLYIndex = featureClass.FindField("SJLY");
                    int BSMIndex = featureClass.FindField("BSM");//变更范围BSM
                    //检测图斑
                    IFeatureCursor JCTB_Cursor = null;
                    IFeatureCursor T_Cursor = null;
                    if (featureClassAPI_GJJCTB.FeatureClass != null && featureClassAPI_GJJCTB.FeatureClass.FeatureCount(null) != 0)
                    {
                        IFeatureClassLoad pFclsLoad = featureClass as IFeatureClassLoad;
                        if (pFclsLoad != null)
                            pFclsLoad.LoadOnlyMode = true;
                        //此处写编辑的代码
                        JCTB_Cursor = featureClassAPI_GJJCTB.FeatureClass.Search(null, true);
                        IFeature S_F = null;
                        //地类变更图斑
                        IFeatureBuffer buffer = featureClass.CreateFeatureBuffer();
                        T_Cursor = featureClass.Insert(true);
                        while ((S_F = JCTB_Cursor.NextFeature()) != null)
                        {
                            buffer.Shape = S_F.ShapeCopy;
                            buffer.Value[SJLYIndex] = "1";//变更数据来源-监测图斑
                            buffer.Value[BGTBYBHIndex] = S_F.Value[JCJCBHIndex];
                            buffer.Value[BGDLBMIndex] = S_F.Value[JCBGDLIndex];
                            if (BSMIndex != -1)
                                buffer.Value[BSMIndex] = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 18);
                            buffer.Value[BGSFJCTBIndex] = "Y";
                            T_Cursor.InsertFeature(buffer);
                        }
                        T_Cursor.Flush();
                        if (pFclsLoad != null)
                            pFclsLoad.LoadOnlyMode = false;
                    }
                }
                else if (cbHitchBGData.IsChecked == true)
                {
                    //由源数据同步挂接到变更范围图斑
                    IFeatureClassAPI featureClassAPIBG = new FeatureClassAPI(t_FC);//当前作为目标图层(监测图层)
                    featureClassAPIBG.FcToFc(featureClass, filter, false);
                    string SJLYData = rdGJJC.IsChecked == true ? "GJJC" : "ZZBG";
                    ((IDataset)featureClass).Workspace.ExecuteSQL($"Update DLTBBG set SJLY = '{SJLYData}'");
                    ((IDataset)featureClass).Workspace.ExecuteSQL($"Update DLTBBG set TBYBH = '-1'");
                    ((IDataset)featureClass).Workspace.ExecuteSQL($"Update DLTBBG set TBYBH = TBBH Where TBBH IS NOT NULL");
                }
                else if (cbTBLoadJCData.IsChecked == true)
                {   //同步加载监测图层并挂接到变更范围
                    if (!(MapsManager.Instance.MapService.GetProjectInfo() is ProjectInfo projectInfo)) return;
                    IWorkspaceAPI wsAPI = null;
                    IFeatureClassAPI jctbFcAPI = null;
                    IFeatureLayer JcTBLayer = null;
                    IFeatureCursor JCCurosr = null;
                    IFeatureClassAPI featureClassAPIBG = null;//已导入数据后的变更范围
                    try
                    {
                        wsAPI = new WorkspaceAPI(projectInfo.BGDatabase, KGIS.Framework.AE.Enum.WorkspaceTypeEnum.GDBFile);
                        jctbFcAPI = wsAPI.OpenFeatureClass2("JCTB");
                        if (jctbFcAPI == null) return;
                        JcTBLayer = new FeatureLayer() { Name = jctbFcAPI.FeatureClass.AliasName, FeatureClass = jctbFcAPI.FeatureClass };
                        JCCurosr = JcTBLayer.FeatureClass.Insert(true);
                        featureClassAPIBG = new FeatureClassAPI(featureClass);//已导入数据后的变更范围
                        IQueryFilter queryFilter = new QueryFilterClass() { WhereClause = "" };
                        if (JcTBLayer.FeatureClass.FeatureCount(null) == 0)
                        {
                            //直接加载数据到自主变更图层
                            featureClassAPIBG.FcToFc(jctbFcAPI.FeatureClass, filter, false);
                            (jctbFcAPI.FeatureClass as FeatureClass).Workspace.ExecuteSQL("Update JCTB set JCBH = '-1'");//避免空赋值
                            (jctbFcAPI.FeatureClass as FeatureClass).Workspace.ExecuteSQL("Update JCTB set SJLY='ZZBG' WHERE SJLY IS NULL");
                            (jctbFcAPI.FeatureClass as FeatureClass).Workspace.ExecuteSQL("Update JCTB set JCBH=BSM WHERE SJLY='ZZBG'");
                        }
                        else
                        {
                            //创建临时变更图层-填充要导入的变更数据
                            IFeatureLayer BGTemp_Layer = GeoDBAPI.CreateFeatureLayerInmemeory("DLTBBG", "地类图斑变更", (featureClass as IGeoDataset).SpatialReference, featureClass.ShapeType, featureClass.Fields);
                            queryFilter.WhereClause = $"OBJECTID >={BGInsertIndex.ToString().ToInt()}";
                            featureClassAPIBG.FcToFc(BGTemp_Layer.FeatureClass, queryFilter, false);
                            int JCJCBHIndex = JcTBLayer.FeatureClass.FindField("JCBH");
                            int JCSJLYIndex = JcTBLayer.FeatureClass.FindField("SJLY");
                            int BGTBYBHIndex = featureClass.FindField("TBYBH");
                            int BGSJLYIndex = featureClass.FindField("SJLY");
                            if (JCJCBHIndex == -1 || JCSJLYIndex == -1 || BGTBYBHIndex == -1 || BGSJLYIndex == -1) return;
                            #region 创建临时融合GDB文件
                            string gdbFileName = Guid.NewGuid().ToString().Replace("-", "") + ".gdb";
                            string gdbFolder = Directory.GetCurrentDirectory() + "\\Temp\\BGTBGLJCTB";//变更图斑挂接监测图斑
                            if (!Directory.Exists(gdbFolder))
                                Directory.CreateDirectory(gdbFolder);
                            PluginServiceInterface.CommonHelper.DelectDir(gdbFolder);
                            string path = System.IO.Path.Combine(gdbFolder, gdbFileName);
                            IWorkspaceFactory pFtWsFct = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactory();
                            IWorkspaceName workspaceName = pFtWsFct.Create(gdbFolder, gdbFileName, null, 0);
                            #endregion
                            IFeatureLayer pjbntFeatureLayer = null;
                            GPParamClass gPParamClass = new GPParamClass
                            {
                                FirstFeatureLayer = JcTBLayer,
                                SecondFeatureLayer = BGTemp_Layer,
                                OutFeatureClassPath = path + "\\" + "DLTBGJJC",
                                IsGetOutPutFeature = true
                            };//监测图层与临时变更范围数据进行Union
                            GeoprocessorHelper.UnionAnalysis(gPParamClass, ref pjbntFeatureLayer);
                            string InsertJCOIDs = string.Empty;
                            string GLJCOIDs = string.Empty;
                            ICursor pCur = null;
                            IRow row = null;
                            #region 挂接处理 1.
                            IQueryDef pQDef = ((pjbntFeatureLayer.FeatureClass as FeatureClass).Workspace as IFeatureWorkspace).CreateQueryDef();
                            pQDef.Tables = "DLTBGJJC";
                            pQDef.WhereClause = " 1=1 AND FID_JCTB=-1 AND FID_DLTBBG<>-1";
                            pQDef.SubFields = "FID_JCTB,FID_DLTBBG,TBYBH";
                            pCur = pQDef.Evaluate();
                            while ((row = pCur.NextRow()) != null)
                            {
                                //需插入自主变更图层的数据OIDs
                                InsertJCOIDs += $"'{row.get_Value(2).ToString()}',";
                            }
                            if (!string.IsNullOrWhiteSpace(InsertJCOIDs))
                            {
                                ((IDataset)featureClass).Workspace.ExecuteSQL($"Update DLTBBG set SJLY='ZZBG',BSM=TBYBH WHERE TBYBH In({InsertJCOIDs.Trim(',')})");
                                queryFilter.WhereClause = $"TBYBH In({InsertJCOIDs.Trim(',')})";
                                featureClassAPIBG.FcToFc(jctbFcAPI.FeatureClass, queryFilter, false);
                                ((IDataset)jctbFcAPI.FeatureClass).Workspace.ExecuteSQL("Update JCTB set SJLY='ZZBG' WHERE SJLY IS NULL");
                                ((IDataset)jctbFcAPI.FeatureClass).Workspace.ExecuteSQL("Update JCTB set JCBH='-1' WHERE SJLY='ZZBG'");
                                ((IDataset)jctbFcAPI.FeatureClass).Workspace.ExecuteSQL("Update JCTB set JCBH=BSM WHERE SJLY='ZZBG'");
                            }
                            pQDef = ((pjbntFeatureLayer.FeatureClass as FeatureClass).Workspace as IFeatureWorkspace).CreateQueryDef();
                            pQDef.Tables = "DLTBGJJC";
                            pQDef.WhereClause = " 1=1 AND FID_JCTB<>-1 AND FID_DLTBBG<>-1 ";
                            pQDef.SubFields = "TBYBH,FID_DLTBBG,JCBH";
                            pCur = pQDef.Evaluate();
                            string TBYBHValues = string.Empty;
                            Dictionary keyValuePairs = new Dictionary();
                            while ((row = pCur.NextRow()) != null)
                            {
                                //需关联到监测图层的数据
                                TBYBHValues += $"'{row.get_Value(0).ToString()}',";
                                keyValuePairs[row.get_Value(0).ToString()] = row.get_Value(2).ToString();
                            }
                            #endregion
                            if (!string.IsNullOrWhiteSpace(TBYBHValues))
                            {
                                queryFilter.WhereClause = $"TBYBH In({TBYBHValues.Trim(',')})";
                                ICursor cursorBG = (featureClass as ITable).Update(queryFilter, true);
                                while ((row = cursorBG.NextRow()) != null)
                                {
                                    if (keyValuePairs.Keys.FirstOrDefault(x => x.Equals(row.Value[BGTBYBHIndex].ToString())) != null)
                                    {
                                        row.Value[BGTBYBHIndex] = keyValuePairs[row.Value[BGTBYBHIndex].ToString()];
                                        cursorBG.UpdateRow(row);
                                    }
                                }
                                cursorBG.Flush();
                            }
                        }
                        if (Platform.Instance.SystemType == SystemTypeEnum.DTBJK)
                        {
                            (jctbFcAPI.FeatureClass as FeatureClass).Workspace.ExecuteSQL("Update JCTB set ZT='未完成'");
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                        featureClassAPIBG?.CloseFeatureClass();
                        if (JCCurosr != null)
                        {
                            Marshal.ReleaseComObject(JCCurosr);
                        }
                        if (JcTBLayer != null)
                        {
                            Marshal.ReleaseComObject(JcTBLayer);
                        }
                        jctbFcAPI?.CloseFeatureClass();
                        wsAPI?.CloseWorkspace();
                    }
                }
                if (SourceFeatureClass != null)
                    Marshal.ReleaseComObject(SourceFeatureClass);
                UpdateZYQ();
                this.CloseLoading();
                int FailedRowCount = RowCount - ImportRowCount;
                string message = string.Format("共导入{0}条,成功{1}条,失败{2}条", RowCount, ImportRowCount, FailedRowCount);
                MessageHelper.ShowTips(message);
                if (Platform.Instance.SystemType == SystemTypeEnum.DTBJK)
                {
                    ProjectInfo projectInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
                    if (projectInfo.CODE.StartsWith("33") || projectInfo.CODE.StartsWith("65"))
                    {
                        Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { Content = SystemTypeEnum.DTBJK, MsgType = "LoadDTBViewData" });
                    }
                }
                this.Close();
            }
            catch (Exception ex)
            {
                PluginServiceInterface.CommonHelper.RecordsErrLog("数据导入异常:", ex);
                this.CloseLoading();
                int FailedRowCount = RowCount - ImportRowCount;
                string message = string.Format("共导入{0}条,成功{1}条,失败{2}条, 失败原因:{3}", RowCount, ImportRowCount, FailedRowCount, "发生异常请查看日志!");
                MessageHelper.ShowWarning(message);
            }
            finally
            {
                this.CloseLoading();
            }
        }
        /// 
        /// 修复Geometry
        /// 
        /// 
        /// 
        public void RepairGeoData(IFeatureClass inFC, bool IsDeleteNullData)
        {
            Geoprocessor gp = new Geoprocessor();
            RepairGeometry repairgeo = new RepairGeometry
            {
                in_features = inFC,
                delete_null = IsDeleteNullData ? "TRUE" : "FALSE"
            }; 
            gp.OverwriteOutput = true;
            gp.SetEnvironmentValue("parallelProcessingFactor", "100%"); // 利用多核CPU
            IGeoProcessorResult tGeoResult = (IGeoProcessorResult)gp.Execute(repairgeo, null);
            if (tGeoResult == null || tGeoResult.Status != esriJobStatus.esriJobSucceeded)
            {
                LogAPI.Debug("RepairGeo检查图形失败:");
            }
        }
        private void UpdateZYQ()
        {
            ProjectInfo ProInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
            if (ProInfo != null && ProInfo.ProjType == EnumProjType.BHTBTQ && Platform.Instance.SystemType == SystemTypeEnum.BGFWCG)
            {
                //添加作业区标注
                //MarkLayer();
                IUcZYQMagrHelper ucZYQMagrHelper = BundleRuntime.Instance.GetFirstOrDefaultService();
                if (ucZYQMagrHelper != null)
                {
                    ucZYQMagrHelper.UpdataData();
                }
                IUcMulitMapControlHelper ucMulitMapControlHelper = BundleRuntime.Instance.GetFirstOrDefaultService();
                if (ucMulitMapControlHelper != null)
                {
                    ucMulitMapControlHelper.ClearData();
                    ucMulitMapControlHelper.SetLayer();
                    ucMulitMapControlHelper.MarkLabelLayer();
                }
                MapsManager.Instance.MapService.getAxMapControl().Refresh();
            }
        }
        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        private void BtnSelectedSQLDataPath_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                IFeatureClass pFeatureClass = SourceFeatureClass;
                if (pFeatureClass == null)
                {
                    MessageHelper.Show("请添加数据源图层!");
                    return;
                }
                else
                {
                    UCSQLFilterCondition ucSQLFilterContion = new UCSQLFilterCondition(pFeatureClass);
                    ucSQLFilterContion.SetValue += (wheresql) =>
                    {
                        btnSQLDataPath.Text = wheresql;
                    };
                    ucSQLFilterContion.ShowInMainWindow();
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex.Message);
            }
        }
        #region 代码注释
        /// 
        /// 勿删
        /// 
        private void Test()
        {
            //string dbPath = @"F:\软件产品\年度变更建库软件\CodeBase.db";
            //DataTable dt = KGIS.Framework.DBOperator.SQLiteDBOperate.Instance.ExceDataTable(dbPath, "select * from AreaCityInfo");
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    foreach (DataRow dr in dt.Rows)
            //    {
            //        string name = dr["XzqName"].ToString();
            //        string key = RunIDService2.Instance.Secretkey;
            //        name = AesEncrypt(name, key);
            //        string newCode = dr["Code"].ToString();
            //        newCode = AesEncrypt(newCode, key);
            //        string Coordinate = dr["Coordinate"].ToString();
            //        Coordinate = AesEncrypt(Coordinate, key);
            //        string sortNo = dr["SortNo"].ToString();
            //        sortNo = AesEncrypt(sortNo, key);
            //        string sql = string.Format("UPDATE AreaCityInfo SET XzqName='{0}',Code='{1}',Coordinate='{2}',SortNo='{3}' where id={4}", name, newCode, Coordinate, sortNo, dr["ID"]);
            //        bool i = KGIS.Framework.DBOperator.SQLiteDBOperate.Instance.ExecuteNonQuery(dbPath, sql, null);
            //    }
            //}
        }
        private string AesEncrypt(string str, string strKey)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(strKey))
                    throw new Exception("加密秘钥为空!");
                byte[] Key = Encoding.UTF8.GetBytes(strKey);
                if (Key.Length != 32)
                    throw new Exception("秘钥长度不符合要求!");
                if (string.IsNullOrEmpty(str)) return null;
                Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
                string strBase64 = Convert.ToBase64String(toEncryptArray);
                byte[] contentArray = Encoding.UTF8.GetBytes(strBase64);
                #region 加密
                System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
                {
                    Key = Key,
                    Mode = System.Security.Cryptography.CipherMode.ECB,
                    Padding = System.Security.Cryptography.PaddingMode.PKCS7
                };
                System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(contentArray, 0, contentArray.Length);
                #endregion
                return Convert.ToBase64String(resultArray);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        private void RdGJJC_Click(object sender, RoutedEventArgs e)
        {
            txtTargetLayer.EditValue = rdGJJC.IsChecked == true ? "国家监测图斑" : "自主变更图斑";
        }
    }
    public class FieldMapping
    {
        /// 
        /// 目标字段名
        /// 
        public string T_FieldName { get; set; }
        /// 
        /// 目标字段索引
        /// 
        public int T_FieldIndex { get; set; }
        /// 
        /// 源字段名
        /// 
        public string S_FieldName { get; set; }
        /// 
        /// 源字段索引
        /// 
        public int S_FieldIndex { get; set; }
        /// 
        /// 字段集合
        /// 
        public List FieldList { get; set; }
    }
    /// 
    /// 检查规则对应的表结构实体
    /// 
    public class RuleTableEntity : INotifyPropertyChanged
    {
        /// 
        /// 表名
        /// 
        public string TableName { get; set; }
        /// 
        /// 表中文名
        /// 
        public string TableAliasName { get; set; }
        /// 
        /// 检查说明
        /// 
        public string CheckDescription { get; set; }
        /// 
        /// 图层类型:点,线,面
        /// 
        public string Type { get; set; }
        /// 
        /// 是否必须图层
        /// 
        public bool IsNecessary { get; set; }
        /// 
        /// 要素代码
        /// 
        public string YSDM { get; set; }
        /// 
        /// 层代码
        /// 
        public string CDM { get; set; }
        bool _IsChecked = false;
        /// 
        /// 是否检查
        /// 
        public bool IsChecked
        {
            set
            {
                _IsChecked = value;
                if (PropertyChanged != null)//有改变
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));//对Name进行监听  
                }
            }
            get
            {
                return _IsChecked;
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        public List Columns { get; set; }
    }
    /// 
    /// 检查规则对应的表字段实体
    /// 
    public class RuleColumnEntity
    {
        /// 
        /// 列名
        /// 
        public string ColumnName { get; set; }
        /// 
        /// 字段说明
        /// 
        public string AliasName { get; set; }
        /// 
        /// 字段是否可为空
        /// 
        public bool AllowDBNull { get; set; }
        /// 
        /// 值是否唯一
        /// 
        public bool IsUnique { get; set; }
        /// 
        /// 是否做非法字符检查 true:检查  false:不检查
        /// 
        public bool IllegalityCheck { get; set; }
        /// 
        /// 字段类型
        /// 
        public string DataType { get; set; }
        /// 
        /// 字段长度
        /// 
        public int MaxLength { get; set; }
        /// 
        /// 字段精度
        /// 
        public int Precision { get; set; }
        /// 
        /// 值域
        /// 
        public string Range { get; set; }
        /// 
        /// 字典
        /// 
        public string DIC { get; set; }
        /// 
        /// 当前字段值是否应该是椭球面积 true:是  false:不是
        /// 
        public bool IsEllipsoidArea { get; set; }
        /// 
        /// 是否是扩展字段
        /// 
        public bool ExtendField
        { get; set; }
        /// 
        /// 字段显示标注说明
        /// 
        public string ToolTip { get; set; }
        /// 
        /// 字段名显示约束条件
        /// 
        public string Pic { get; set; }
    }
}