using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ExcelDataReader;
using KGIS.Framework.AE;
using KGIS.Framework.AE.GPHelper;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.OpenData.Control;
using KGIS.Framework.OpenData.Filter;
using KGIS.Framework.OpenData.InterFace;
using KGIS.Framework.Platform.Helper;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Dialog;
using KGIS.Framework.Utils.ExtensionMethod;
using KGIS.Framework.Utils.Helper;
using Kingo.PluginServiceInterface;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using IRDBHelper = KGIS.Framework.DBOperator.IRDBHelper;
namespace Kingo.Plugin.LocationChange.View
{
    /// 
    /// FrmLocationChange.xaml 的交互逻辑
    /// 
    public partial class FrmLocationChange : BaseWindow
    {
        /// 
        /// 选择范围的变更数据
        /// 
        private IFeatureLayer SelLocation_Layer = null;
        /// 
        /// 视图数据表
        /// 
        DataTable DT = new DataTable();
        private string dbPath = Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
        public FrmLocationChange()
        {
            InitializeComponent();
            DT.Columns.Add(new DataColumn("变更前代码"));
            DT.Columns.Add(new DataColumn("变更前名称"));
            DT.Columns.Add(new DataColumn("变更后代码"));
            DT.Columns.Add(new DataColumn("变更后名称"));
            gvCtrl.ItemsSource = DT;
            tvAttr2.AddNewRow();
        }
        /// 
        /// 得到要素类集合
        /// 
        /// 
        /// 路径集合
        public static IFeatureClass GetFeatureClass(string title, ref string paths)
        {
            IFeatureClass result = null;
            try
            {
                // 获取源数据
                OpenDataDialog pDialog = new OpenDataDialog();
                ISpatialDataObjectFilter pOFilter;
                pOFilter = new FilterFeatureDatasetsAndFeatureClasses();
                pDialog.AddFilter(pOFilter, true);
                if (!string.IsNullOrWhiteSpace(title))
                    pDialog.Title = title;
                else
                    pDialog.Title = "选择数据";
                pDialog.AllowMultiSelect = false;
                pDialog.RestoreLocation = true;
                pDialog.StartLocation = pDialog.FinalLocation;
                if (pDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && pDialog.Selection.Count > 0)
                {
                    List distObj = pDialog.Selection;
                    foreach (var obj in distObj)
                    {
                        if (obj.DatasetType == esriDatasetType.esriDTFeatureClass)
                        {
                            IFeatureClass featureclass = (obj.DatasetName as IName).Open() as IFeatureClass;
                            result = featureclass;
                            //paths += obj.FullName;//展示完整路径
                            paths = featureclass.AliasName;//展示文件名
                        }
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                LogAPI.Debug("选择数据失败:" + ex.Message.ToString());
                return result;
            }
        }
        /// 
        /// 打开文件
        /// 
        /// 
        /// 
        private void BtnOpenFile_Click(object sender, RoutedEventArgs e)
        {
            string filePath = string.Empty;
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.DefaultExt = "xls";
            dialog.Filter = "Excel文件|*.xls;*.xlsx";
            if (dialog.ShowDialog())
            {
                filePath = dialog.FileName;
                using (var streamData = File.Open(filePath, FileMode.Open, FileAccess.Read))
                {
                    using (var readerData = ExcelReaderFactory.CreateReader(streamData))
                    {
                        var result = readerData.AsDataSet();
                        DataTable tempDT = result.Tables[0];
                        tempDT.Columns[0].ColumnName = "变更前代码";
                        tempDT.Columns[1].ColumnName = "变更前名称";
                        tempDT.Columns[2].ColumnName = "变更后代码";
                        tempDT.Columns[3].ColumnName = "变更后名称";
                        tempDT.Rows.RemoveAt(0);
                        DT = tempDT;
                        gvCtrl.ItemsSource = DT;
                    }
                }
            }
        }
        /// 
        /// 添加行
        /// 
        /// 
        /// 
        private void BtnAddRow_Click(object sender, RoutedEventArgs e)
        {
            tvAttr2.AddNewRow();
        }
        /// 
        /// 删除选中
        /// 
        /// 
        /// 
        private void BtnDelRow_Click(object sender, RoutedEventArgs e)
        {
            int[] rows = gvCtrl.GetSelectedRowHandles();
            foreach (var item in rows)
            {
                tvAttr2.DeleteRow(item);
            }
        }
        /// 
        /// 选择范围
        /// 
        /// 
        /// 
        private void BtnSelTB_Click(object sender, RoutedEventArgs e)
        {
            string xzdltbPaths = "";
            IFeatureClass dltbFc = GetFeatureClass("请选择新增的地类图斑数据", ref xzdltbPaths);
            if (dltbFc != null)
            {
                btnNewData.Text = xzdltbPaths;
                SelLocation_Layer = GeoDBAPI.CreateFeatureLayerInmemeory("SelLocation", "选择范围图斑数据", (dltbFc as IGeoDataset).SpatialReference, dltbFc.ShapeType, dltbFc.Fields);
                (SelLocation_Layer.FeatureClass as ITable).DeleteSearchedRows(null);
                InsertDataToMemeoryLayer(dltbFc, SelLocation_Layer.FeatureClass, null);
            }
        }
        /// 
        /// 更新坐落信息
        /// 
        /// 
        /// 
        private void BtnOK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ProgressHelper.ShowProcessBar("正在进行数据处理......");
                bool isSucceed = false;
                //给定图斑进行变更
                if (SelLocation_Layer != null && SelLocation_Layer.FeatureClass.FeatureCount(null) != 0)
                {
                    SelTBZLBG();
                    isSucceed = true;
                }
                //给定坐落信息进行变更
                if (DT.Rows.Count != 0)
                {
                    bool isXDM = false;
                    foreach (DataRow dr in DT.Rows)
                    {
                        if (string.IsNullOrWhiteSpace(dr["变更前代码"].ToTrim()) || string.IsNullOrWhiteSpace(dr["变更后代码"].ToTrim())) continue;
                        if (dr["变更前代码"].ToTrim().Length == 6 && dr["变更后代码"].ToTrim().Length == 6)
                        {
                            isXDM = true;
                        }
                        ExeUpZLInfo(dr["变更前代码"].ToTrim(), dr["变更前名称"].ToTrim(), dr["变更后代码"].ToTrim(), dr["变更后名称"].ToTrim());
                    }
                    if (isXDM)//县代码发生改变
                    {
                        IFeatureClass fc = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGXGC");
                        IRDBHelper dbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
                        dbHelper.ExecuteSQL("UPDATE BHXXB set XZQTZLX='5' where XZQTZLX='0'");
                        (fc as FeatureClass).Workspace.ExecuteSQL("UPDATE DLTBGXGC set XZQTZLX='5' where XZQTZLX='0'");
                    }
                    isSucceed = true;
                }
                ProgressHelper.CloseProcessBar();
                if (isSucceed) MessageHelper.Show("变更完成。");
            }
            catch (Exception ex)
            {
                MessageHelper.ShowError("变更失败:" + ex.Message);
                LogAPI.Debug("坐落变更失败:" + ex);
            }
            finally
            {
                ProgressHelper.CloseProcessBar();
                if (SelLocation_Layer != null) SelLocation_Layer = null;
            }
        }
        /// 
        /// 选择图斑进行坐落变更
        /// 
        private void SelTBZLBG()
        {
            //获取左侧新加载的图层
            IFeatureLayer JC_Fc = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("地类图斑");
            IFeatureLayer DLTBGX_FL = MapsManager.Instance.MapService.GetFeatureLayerByName("DLTBGX");
            IFeatureClass DLTBGX_Fc = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGX");
            IFeatureCursor featureSelTB = SelLocation_Layer.FeatureClass.Search(null, true);
            IFeature Sel_F = null;
            //基础库图斑字段
            int BGQZLDM_JC = JC_Fc.FeatureClass.FindField("ZLDWDM");
            int BGQZLMC_JC = JC_Fc.FeatureClass.FindField("ZLDWMC");
            int JC_BSM = JC_Fc.FeatureClass.FindField("BSM");
            int JC_TBBH_Index = JC_Fc.FeatureClass.FindField("TBBH");
            //更新层图斑字段
            int GX_BSM = DLTBGX_Fc.FindField("BSM");
            int GX_ZLDWMC = DLTBGX_Fc.FindField("ZLDWDM");
            int GX_ZLDWDM = DLTBGX_Fc.FindField("ZLDWMC");
            int GX_TBBH_Index = DLTBGX_Fc.FindField("TBBH");
            //获取选择范围图斑字段
            int BGHZLDM_Sel = SelLocation_Layer.FeatureClass.FindField("ZLDWDM");
            int BGHZLMC_Sel = SelLocation_Layer.FeatureClass.FindField("ZLDWMC");
            string BGQZLDWDM = string.Empty;
            string BGQZLDWMC = string.Empty;
            string BGHZLDWMC = string.Empty;
            string BGHZLDWDM = string.Empty;
            string UpDataGXBSM = string.Empty;
            string UpDataJCBSM = string.Empty;
            string JC_TBBH = string.Empty;
            string GX_TBBH = string.Empty;
            while ((Sel_F = featureSelTB.NextFeature()) != null)
            {
                BGHZLDWDM = Sel_F.Value[BGHZLDM_Sel].ToString();//要改变的坐落信息
                BGHZLDWMC = Sel_F.Value[BGHZLMC_Sel].ToString();
                //压盖基础基础库
                List JC_fs = FeatureAPI.Identify2(Sel_F.ShapeCopy, JC_Fc);
                foreach (IFeature item_JC in JC_fs)//压盖到的基础库图斑
                {
                    if (FeatureAPI.IsContains(Sel_F.ShapeCopy, item_JC.ShapeCopy))
                    {
                        List DLTBGX_fs = FeatureAPI.Identify2(item_JC.ShapeCopy, DLTBGX_FL);
                        foreach (IFeature item_GX in DLTBGX_fs)
                        {
                            if (FeatureAPI.IsContains(item_JC.ShapeCopy, item_GX.ShapeCopy))
                            {
                                JC_TBBH = item_JC.Value[JC_TBBH_Index].ToTrim();
                                GX_TBBH = item_GX.Value[GX_TBBH_Index].ToTrim();
                                UpDataJCBSM = item_JC.Value[JC_BSM].ToString();
                                UpDataGXBSM = item_GX.Value[GX_BSM].ToString();
                                BGQZLDWDM = item_GX.Value[GX_ZLDWDM].ToString();//改变前的坐落信息
                                BGQZLDWMC = item_GX.Value[GX_ZLDWMC].ToString();
                                SelUpdateZLInfo(BGQZLDWDM, BGQZLDWMC, UpDataJCBSM, UpDataGXBSM, JC_TBBH, GX_TBBH, item_GX.OID);
                            }
                            else
                            {
                                MessageHelper.ShowError("该图斑与地类图斑更新层图斑范围不套合,已记录日志!");
                                LogAPI.Debug("不套合图斑OID:" + Sel_F.OID);
                            }
                        }
                        if (DLTBGX_fs.Count == 0)//指定图斑只在基础图斑范围内
                        {
                            BGQZLDWDM = item_JC.Value[BGQZLDM_JC].ToString();
                            BGQZLDWMC = item_JC.Value[BGQZLMC_JC].ToString();
                            UpDataJCBSM = item_JC.Value[JC_BSM].ToString();
                            XZZLInfoBySelTB(BGHZLDWDM, BGHZLDWMC, BGQZLDWDM, BGQZLDWMC, UpDataJCBSM);
                        }
                    }
                    else
                    {
                        MessageHelper.ShowError("该图斑与基础库图斑范围不套合,已记录日志!");
                        LogAPI.Debug("不套合图斑OID:" + Sel_F.OID);
                    }
                }
            }
        }
        /// 
        /// 根据选择图斑数据新增坐落信息至BHXXB
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 指定图斑BSM是否新增坐落信息
        private void XZZLInfoBySelTB(string BGHZLDWDM, string BGHZLDWMC, string BGQZLDWDM, string BGQZLDWMC, string UpDataJCBSM = "")
        {
            IRDBHelper dbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
            if (!dbHelper.TableIsExist("BHXXB"))
            {
                dbHelper.ExecuteSQL(" Create TABLE BHXXB ( BGQTBBSM text(100),BGHTBBSM text(100),BGQTBBH text(100),BGHTBBH text(100),BGQZLDWDM text(100),BGHZLDWDM text(100)," +
                    "BGQZLDWMC text(100),BGHZLDWMC text(100),BGQQSDWDM text(100),BGHQSDWDM text(100),BGQQSDWMC text(100),BGHQSDWMC text(100),BGQQSXZ text(100),BGHQSXZ text(100)," +
                    "BGQDLBM text(100),BGHDLBM text(100),BGQKCDLBM text(100),BGHKCDLBM text(100),BGQKCXS text(100),BGHKCXS text(100),BGQKCMJ NUMERIC,BGHKCMJ NUMERIC,BGQGDLX text(100),BGHGDLX text(100),BGQGDPDJB text(100),BGHGDPDJB text(100),BGQCZCSXM text(100),BGHCZCSXM text(100)," +
                    "BGQTBXHDM text(100),BGHTBXHDM text(100),BGQZZSXDM text(100),BGHZZSXDM text(100),BGQMSSM text(100),BGHMSSM text(100),BGQGDDB text(100),BGHGDDB text(100)," +
                    "BGMJ NUMERIC,XZQTZLX text(100),BZ text(10),BGXW text(10) ) ");
            }
            IQueryFilter filter = new QueryFilterClass();
            //范围内基础图斑(新增坐落信息UpDataJCBSM-基础BSM)
            filter.WhereClause = string.Format("ZLDWDM like '{0}%' AND BSM = '{1}'", BGQZLDWDM.ToTrim(), UpDataJCBSM);//定位唯一的一个图斑
            IFeatureClass fc = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("地类图斑").FeatureClass as IFeatureClass;
            IFeatureClass fc2 = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGX");
            ITable itb = fc as ITable;
            ICursor cur = itb.Search(filter, true);
            IRow row = null;
            int bsmIdx = itb.FindField("BSM");
            int zldmIdx = itb.FindField("ZLDWDM");
            int zlmcIdx = itb.FindField("ZLDWMC");
            int qsdmIdx = itb.FindField("QSDWDM");
            int qsmcIdx = itb.FindField("QSDWMC");
            string bhxxbField = "BGQTBBSM,BGHTBBSM,BGQTBBH,BGHTBBH,BGQZLDWDM,BGHZLDWDM,BGQZLDWMC,BGHZLDWMC,BGQQSDWDM,BGHQSDWDM,BGQQSDWMC,BGHQSDWMC,BGQQSXZ,BGHQSXZ,BGQDLBM,BGHDLBM,BGQKCDLBM,BGHKCDLBM,BGQKCXS,BGHKCXS,BGQKCMJ,BGHKCMJ,BGQGDLX,BGHGDLX,BGQGDPDJB,BGHGDPDJB,BGQCZCSXM,BGHCZCSXM,BGQTBXHDM,BGHTBXHDM,BGQZZSXDM,BGHZZSXDM,BGQMSSM,BGHMSSM,BGQGDDB,BGHGDDB,BGMJ,XZQTZLX,BZ,BGXW";
            string[] bhxxbfieldArr = bhxxbField.Split(',');
            Dictionary dicTBBH = new Dictionary();
            GetMaxTBBH(fc, ref dicTBBH);
            GetMaxTBBH(fc2, ref dicTBBH);
            DataTable bhxxDt = dbHelper.ExecuteDatatable("BHXXB", string.Format("select * from BHXXB"), true);
            List bgqbsmList = new List();
            if (bhxxDt != null)
            {
                foreach (DataRow dr in bhxxDt.Rows)
                {
                    string strBGQBSM = dr["BGQTBBSM"].ToTrim();
                    if (!bgqbsmList.Contains(strBGQBSM))
                        bgqbsmList.Add(strBGQBSM);//获取变化信息表中变更前BSM
                    string strBGHZLDWDM = dr["BGHZLDWDM"].ToTrim();
                    if (!dicTBBH.ContainsKey(strBGHZLDWDM))
                    {
                        dicTBBH.Add(strBGHZLDWDM, dr["BGHTBBH"].ToInt());//变更后坐落单位代码及变更后图斑编号
                    }
                    else
                    {
                        int bghtbbh = dr["BGHTBBH"].ToInt();
                        if (dicTBBH[strBGHZLDWDM] < bghtbbh)
                            dicTBBH[strBGHZLDWDM] = bghtbbh;//获取相同变更后坐落单位代码下的最大变更后图版编号
                    }
                }
            }
            List strSQL = new List();
            int count = itb.RowCount(filter);
            int num = 0;
            while ((row = cur.NextRow()) != null)//JC_DLTB
            {
                num++;
                string bhxxbValue = string.Empty;
                if (zldmIdx == -1) break;
                string bsm = row.Value[bsmIdx].ToTrim();
                if (bgqbsmList.Contains(bsm)) continue;//过滤掉变化信息表中已存在的
                string zldm = row.Value[zldmIdx].ToTrim();//坐落代码
                string zlmc = string.Empty;
                string qsdm = row.Value[qsdmIdx].ToTrim();//权属代码
                string qsmc = string.Empty;
                if (qsmcIdx != -1)
                    qsmc = row.Value[qsmcIdx].ToTrim();
                if (zlmcIdx != -1)
                    zlmc = row.Value[zlmcIdx].ToTrim();//坐落名称
                string bghzldm = zldm.Replace(BGQZLDWDM.ToTrim(), BGHZLDWDM.ToTrim());
                string bghzlmc = zlmc;
                if (!string.IsNullOrWhiteSpace(BGHZLDWMC.ToTrim()))
                    bghzlmc = zlmc.Replace(BGQZLDWMC.ToTrim(), BGHZLDWMC.ToTrim());//改变后坐落名称
                string bghqsdm = qsdm.Replace(BGQZLDWDM.ToTrim(), BGHZLDWDM.ToTrim());
                string bghqsmc = qsmc;
                if (!string.IsNullOrWhiteSpace(BGHZLDWMC.ToTrim()))
                    bghqsmc = qsmc.Replace(BGQZLDWMC.ToTrim(), BGHZLDWMC.ToTrim());//改变后权属名称
                //填充属性和属性赋值
                foreach (var item in bhxxbfieldArr)
                {
                    string name = item.ToTrim().Replace("BGQ", "").Replace("BGH", "");
                    if (name == "TBBSM")
                        name = "BSM";
                    if (item == "BGMJ")
                        name = "TBMJ";
                    if (item == "BZ")
                        name = "Temp_BZ";
                    int idx = row.Fields.FindField(name);
                    if (idx != -1)
                    {
                        if (item == "BGHTBBSM")
                        {
                            bhxxbValue += string.Format("'{0}',", row.Value[idx]);
                        }
                        else if (item == "BGHTBBH")
                        {
                            string bghTBBH = string.Empty;
                            if (dicTBBH.ContainsKey(bghzldm))
                            {
                                dicTBBH[bghzldm] = dicTBBH[bghzldm] + 1;//最大图斑编号-去最新值
                                bghTBBH = dicTBBH[bghzldm].ToTrim();
                            }
                            else
                            {   //(变化信息表中的新增村落)新增村
                                dicTBBH.Add(bghzldm, 1);//图斑编号从一开始
                                bghTBBH = dicTBBH[bghzldm].ToTrim();
                            }
                            bhxxbValue += string.Format("'{0}',", bghTBBH);
                        }
                        else if (item == "BGHZLDWDM")
                        {
                            bhxxbValue += string.Format("'{0}',", bghzldm);
                        }
                        else if (item == "BGHZLDWMC")
                        {
                            bhxxbValue += string.Format("'{0}',", bghzlmc);
                        }
                        else if (item == "BGHQSDWDM")
                        {
                            bhxxbValue += string.Format("'{0}',", bghqsdm);
                        }
                        else if (item == "BGHQSDWMC")
                        {
                            bhxxbValue += string.Format("'{0}',", bghqsmc);
                        }
                        else if (item.EndsWith("MJ"))
                        {
                            bhxxbValue += string.Format("{0},", row.Value[idx]);
                        }
                        else
                        {
                            bhxxbValue += string.Format("'{0}',", row.Value[idx]);
                        }
                    }
                    else if (item == "BZ")
                    {
                        bhxxbValue += string.Format("'{0}',", "ZLBG");
                    }
                    else if (item == "XZQTZLX")
                    {
                        bhxxbValue += string.Format("'{0}',", "0");
                    }
                    else if (item == "BGXW")
                    {
                        bhxxbValue += string.Format("'{0}',", "1");
                    }
                }
                bhxxbValue = bhxxbValue.TrimEnd(',');
                string strSQLTemp = string.Format("Insert into BHXXB ({0}) values ({1})", bhxxbField, bhxxbValue);
                strSQL.Add(strSQLTemp);
                Marshal.ReleaseComObject(row);
            }
            InsertDB(strSQL, dbPath);
            strSQL.Clear();
        }
        /// 
        /// 处理同属性图斑合并
        /// 
        /// 
        /// 
        private void BtnOK2_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UnionDLTBGX();
                IFeatureClass fc = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGXGC");
                IFeatureClass fc2 = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGX");
                IRDBHelper dbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
                DataTable dtbhxx = dbHelper.ExecuteDatatable("BHXXB", "select * from bhxxb", true);
                DataTable dtZL = dbHelper.ExecuteDatatable("ZLGroup", "select BGHZLDWDM from bhxxb group by BGHZLDWDM", true);
                try
                {
                    dbHelper.BeginTransaction();
                    foreach (DataRow dr in dtZL.Rows)
                    {
                        DataRow[] drs = dtbhxx.Select(string.Format(" BGHZLDWDM='{0}'", dr["BGHZLDWDM"]));
                        Dictionary temp = new Dictionary();
                        Dictionary temp3 = new Dictionary();
                        List tbbhs = new List();
                        int maxTBBH = 0;
                        foreach (DataRow subdr in drs)
                        {
                            int bghtbbh = subdr["BGHTBBH"].ToInt();
                            if (maxTBBH < bghtbbh)
                                maxTBBH = bghtbbh;
                        }
                        foreach (DataRow subdr in drs)
                        {
                            string bghtbbsm = subdr["BGHTBBSM"].ToTrim();
                            int bghtbbh = subdr["BGHTBBH"].ToInt();
                            if (!temp.ContainsKey(bghtbbsm))
                            {
                                temp.Add(bghtbbsm, bghtbbh);
                                if (!tbbhs.Contains(bghtbbh))
                                {
                                    tbbhs.Add(bghtbbh);
                                }
                                else
                                {
                                    maxTBBH++;
                                    temp3.Add(bghtbbsm, maxTBBH);
                                }
                            }
                        }
                        foreach (var key in temp3.Keys)
                        {
                            dbHelper.ExecuteSQL(string.Format("update bhxxb set bghtbbh='{0}' where bghtbbsm='{1}'", temp3[key], key));
                            IQueryFilter filter = new QueryFilterClass();
                            filter.WhereClause = string.Format("BGHTBBSM='{0}'", key);
                            IFeatureCursor cursor = fc.Update(filter, true);
                            IFeature f = null;
                            int idx = fc.FindField("BGHTBBH");
                            while ((f = cursor.NextFeature()) != null)
                            {
                                f.Value[idx] = temp3[key].ToTrim();
                                cursor.UpdateFeature(f);
                            }
                            cursor.Flush();
                            filter.WhereClause = string.Format("BSM='{0}'", key);
                            cursor = fc2.Update(filter, true);
                            f = null;
                            idx = fc2.FindField("TBBH");
                            while ((f = cursor.NextFeature()) != null)
                            {
                                f.Value[idx] = temp3[key].ToTrim();
                                cursor.UpdateFeature(f);
                            }
                            cursor.Flush();
                        }
                    }
                    dbHelper.Commit();
                }
                catch (Exception)
                {
                    dbHelper.Rollback();
                }
                MessageHelper.ShowTips("变更完成!");
            }
            catch (Exception ex)
            {
                ProgressHelper.CloseProcessBar();
                MessageHelper.Show("坐落信息变更失败,请查看系统日志!");
                LogAPI.Debug("坐落信息变更时发生异常,异常信息如下:");
                LogAPI.Debug(ex);
            }
            finally
            {
                loading.Visibility = Visibility.Collapsed;
            }
        }
        /// 
        /// 取消按钮
        /// 
        /// 
        /// 
        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        /// 
        /// 每一条坐落变更信息
        /// 
        /// 
        /// 
        /// 
        /// 
        private void ExeUpZLInfo(string pBGQDM, string pBGQMC, string pBGHDM, string pBGHMC)
        {
            try
            {
                IRDBHelper dbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
                if (!dbHelper.TableIsExist("BHXXB"))
                {
                    dbHelper.ExecuteSQL(" Create TABLE BHXXB ( BGQTBBSM text(100),BGHTBBSM text(100),BGQTBBH text(100),BGHTBBH text(100),BGQZLDWDM text(100),BGHZLDWDM text(100)," +
                        "BGQZLDWMC text(100),BGHZLDWMC text(100),BGQQSDWDM text(100),BGHQSDWDM text(100),BGQQSDWMC text(100),BGHQSDWMC text(100),BGQQSXZ text(100),BGHQSXZ text(100)," +
                        "BGQDLBM text(100),BGHDLBM text(100),BGQKCDLBM text(100),BGHKCDLBM text(100),BGQKCXS text(100),BGHKCXS text(100),BGQKCMJ NUMERIC,BGHKCMJ NUMERIC,BGQGDLX text(100),BGHGDLX text(100),BGQGDPDJB text(100),BGHGDPDJB text(100),BGQCZCSXM text(100),BGHCZCSXM text(100)," +
                        "BGQTBXHDM text(100),BGHTBXHDM text(100),BGQZZSXDM text(100),BGHZZSXDM text(100),BGQMSSM text(100),BGHMSSM text(100),BGQGDDB text(100),BGHGDDB text(100)," +
                        "BGMJ NUMERIC,XZQTZLX text(100),BZ text(10),BGXW text(10) ) ");
                }
                IQueryFilter filter = new QueryFilterClass();
                filter.WhereClause = string.Format("ZLDWDM like '{0}%'", pBGQDM.ToTrim());
                IFeatureClass JC_fc = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("地类图斑").FeatureClass as IFeatureClass;
                IFeatureClass fc2 = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGX");
                ITable itb = JC_fc as ITable;
                ICursor JC_cur = itb.Search(filter, true);//过滤输入坐落代码改变的部分
                IRow row = null;
                int bsmIdx = itb.FindField("BSM");
                int zldmIdx = itb.FindField("ZLDWDM");
                int zlmcIdx = itb.FindField("ZLDWMC");
                int qsdmIdx = itb.FindField("QSDWDM");
                int qsmcIdx = itb.FindField("QSDWMC");
                string bhxxbField = "BGQTBBSM,BGHTBBSM,BGQTBBH,BGHTBBH,BGQZLDWDM,BGHZLDWDM,BGQZLDWMC,BGHZLDWMC,BGQQSDWDM,BGHQSDWDM,BGQQSDWMC,BGHQSDWMC,BGQQSXZ,BGHQSXZ,BGQDLBM,BGHDLBM,BGQKCDLBM,BGHKCDLBM,BGQKCXS,BGHKCXS,BGQKCMJ,BGHKCMJ,BGQGDLX,BGHGDLX,BGQGDPDJB,BGHGDPDJB,BGQCZCSXM,BGHCZCSXM,BGQTBXHDM,BGHTBXHDM,BGQZZSXDM,BGHZZSXDM,BGQMSSM,BGHMSSM,BGQGDDB,BGHGDDB,BGMJ,XZQTZLX,BZ,BGXW";
                string[] bhxxbfieldArr = bhxxbField.Split(',');
                Dictionary dicTBBH = new Dictionary();
                GetMaxTBBH(JC_fc, ref dicTBBH);
                GetMaxTBBH(fc2, ref dicTBBH);
                DataTable bhxxDt = dbHelper.ExecuteDatatable("BHXXB", string.Format("select * from BHXXB"), true);
                List bgqbsmList = new List();
                if (bhxxDt != null)
                {
                    foreach (DataRow dr in bhxxDt.Rows)
                    {
                        string strBGQBSM = dr["BGQTBBSM"].ToTrim();
                        if (!bgqbsmList.Contains(strBGQBSM))
                            bgqbsmList.Add(strBGQBSM);//存储变更前标识码
                        string strBGHZLDWDM = dr["BGHZLDWDM"].ToTrim();
                        if (!dicTBBH.ContainsKey(strBGHZLDWDM))
                        {
                            dicTBBH.Add(strBGHZLDWDM, dr["BGHTBBH"].ToInt());
                        }
                        else
                        {
                            int bghtbbh = dr["BGHTBBH"].ToInt();
                            if (dicTBBH[strBGHZLDWDM] < bghtbbh)
                                dicTBBH[strBGHZLDWDM] = bghtbbh;
                        }
                    }
                }
                List strSQL = new List();
                int count = itb.RowCount(filter);
                ProgressHelper.CountProgress = count;
                int num = 0;
                while ((row = JC_cur.NextRow()) != null)//JC_DLTB
                {
                    num++;
                    string bhxxbValue = string.Empty;
                    if (zldmIdx == -1) break;
                    string bsm = row.Value[bsmIdx].ToTrim();
                    if (bgqbsmList.Contains(bsm)) continue;
                    string zldm = row.Value[zldmIdx].ToTrim();
                    string zlmc = string.Empty;
                    string qsdm = row.Value[qsdmIdx].ToTrim();
                    string qsmc = string.Empty;
                    if (qsmcIdx != -1)
                        qsmc = row.Value[qsmcIdx].ToTrim();
                    if (zlmcIdx != -1)
                        zlmc = row.Value[zlmcIdx].ToTrim();
                    string bghzldm = zldm.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim());
                    string bghzlmc = zlmc;
                    if (!string.IsNullOrWhiteSpace(pBGHMC.ToTrim()))
                        bghzlmc = zlmc.Replace(pBGQMC.ToTrim(), pBGHMC.ToTrim());
                    string bghqsdm = qsdm.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim());
                    string bghqsmc = qsmc;
                    if (!string.IsNullOrWhiteSpace(pBGHMC.ToTrim()))
                        bghqsmc = qsmc.Replace(pBGQMC.ToTrim(), pBGHMC.ToTrim());
                    foreach (var item in bhxxbfieldArr)
                    {
                        string name = item.ToTrim().Replace("BGQ", "").Replace("BGH", "");
                        if (name == "TBBSM")
                            name = "BSM";
                        if (item == "BGMJ")
                            name = "TBMJ";
                        if (item == "BZ")
                            name = "Temp_BZ";
                        int idx = row.Fields.FindField(name);
                        if (idx != -1)
                        {
                            if (item == "BGHTBBSM")
                            {
                                bhxxbValue += string.Format("'{0}',", row.Value[idx]);
                            }
                            else if (item == "BGHTBBH")
                            {
                                string bghTBBH = string.Empty;
                                if (dicTBBH.ContainsKey(bghzldm))
                                {
                                    dicTBBH[bghzldm] = dicTBBH[bghzldm] + 1;
                                    bghTBBH = dicTBBH[bghzldm].ToTrim();
                                }
                                else
                                {//新增村
                                    dicTBBH.Add(bghzldm, 1);
                                    bghTBBH = dicTBBH[bghzldm].ToTrim();
                                }
                                bhxxbValue += string.Format("'{0}',", bghTBBH);
                            }
                            else if (item == "BGHZLDWDM")
                            {
                                bhxxbValue += string.Format("'{0}',", bghzldm);
                            }
                            else if (item == "BGHZLDWMC")
                            {
                                bhxxbValue += string.Format("'{0}',", bghzlmc);
                            }
                            else if (item == "BGHQSDWDM")
                            {
                                bhxxbValue += string.Format("'{0}',", bghqsdm);
                            }
                            else if (item == "BGHQSDWMC")
                            {
                                bhxxbValue += string.Format("'{0}',", bghqsmc);
                            }
                            else if (item.EndsWith("MJ"))
                            {
                                bhxxbValue += string.Format("{0},", row.Value[idx]);
                            }
                            else
                            {
                                bhxxbValue += string.Format("'{0}',", row.Value[idx]);
                            }
                        }
                        else if (item == "BZ")
                        {
                            bhxxbValue += string.Format("'{0}',", "ZLBG");
                        }
                        else if (item == "XZQTZLX")
                        {
                            bhxxbValue += string.Format("'{0}',", "0");
                        }
                        else if (item == "BGXW")
                        {
                            bhxxbValue += string.Format("'{0}',", "1");
                        }
                    }
                    bhxxbValue = bhxxbValue.TrimEnd(',');
                    string strSQLTemp = string.Format("Insert into BHXXB ({0}) values ({1})", bhxxbField, bhxxbValue);
                    strSQL.Add(strSQLTemp);
                    Marshal.ReleaseComObject(row);
                    if (num % 500 == 0 || num == count)
                    {
                        InsertDB(strSQL, dbPath);
                        strSQL.Clear();
                        ProgressHelper.CurrentProgress = num;
                    }
                }
                if (strSQL.Count != 0)
                    InsertDB(strSQL, dbPath);
                strSQL.Clear();
                #region 更新坐落单位代码 名称
                BGHZLExecute(pBGQDM, pBGQMC, pBGHDM, pBGHMC);
                #endregion
            }
            catch (Exception ex)
            {
                ProgressHelper.CloseProcessBar();
                MessageHelper.Show("坐落信息变更失败,请查看系统日志!");
                LogAPI.Debug("坐落信息变更时发生异常,异常信息如下:");
                LogAPI.Debug(ex);
            }
            finally
            {
                loading.Visibility = Visibility.Collapsed;
            }
        }
        private void UnionDLTBGX()
        {
            try
            {
                string gdbFolder = Directory.GetCurrentDirectory() + "\\Temp\\GXGC";
                if (!Directory.Exists(gdbFolder))
                {
                    Directory.CreateDirectory(gdbFolder);
                }
                try
                {
                    BGHelper.DelectDir(gdbFolder);//能删除就删除   删除报错不处理
                }
                catch
                { }
                IWorkspaceFactory pFtWsFct = null;
                IWorkspaceName workspaceName = null;
                pFtWsFct = new FileGDBWorkspaceFactory();
                string gdbFileName = Guid.NewGuid().ToString() + ".gdb";
                string path = Path.Combine(gdbFolder, gdbFileName);
                workspaceName = pFtWsFct.Create(gdbFolder, gdbFileName, null, 0);
                IFeatureClass _GxFc = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGX");
                IFeatureLayer memeory_dltbgx1 = GeoDBAPI.CreateFeatureLayerInmemeory("mem_PDTGX", "坡度图更新", (_GxFc as IGeoDataset).SpatialReference, _GxFc.ShapeType, _GxFc.Fields);
                IQueryFilter filter2 = new QueryFilterClass();
                filter2.WhereClause = " DLBM ='1003' or DLBM='1004' or DLBM ='1006' or DLBM='1101' or DLBM='1107' or DLBM='1107A'";
                InsertDataToMemeoryLayer(_GxFc, memeory_dltbgx1.FeatureClass, filter2);
                (_GxFc as ITable).DeleteSearchedRows(new QueryFilterClass() { WhereClause = " DLBM ='1003' or DLBM='1004' or DLBM ='1006' or DLBM='1101' or DLBM='1107' or DLBM='1107A'" });
                IFeatureLayer tempLayer = null;
                GPParamClass gPParamClass = new GPParamClass();
                gPParamClass = new GPParamClass();
                gPParamClass.FirstFeatureClass = _GxFc;
                gPParamClass.OutFeatureClassPath = path + "\\" + "DLTBGX_Diss";
                gPParamClass.ListDissolveFiledName = new List() { "DLBM", "DLMC", "QSXZ", "QSDWDM", "QSDWMC", "ZLDWDM", "ZLDWMC", "KCDLBM", "KCXS", "GDLX", "GDPDJB", "XZDWKD", "TBXHDM", "TBXHMC", "ZZSXDM", "ZZSXMC", "GDDB", "FRDBS", "CZCSXM", "MSSM", "HDMC", "XZQTZLX" };//
                gPParamClass.IsGetOutPutFeature = true;
                GeoprocessorHelper.DissolveAnalysis(gPParamClass, ref tempLayer);
                (_GxFc as ITable).DeleteSearchedRows(null);
                InsertDataToMemeoryLayer(memeory_dltbgx1.FeatureClass, _GxFc);
                InsertDataToMemeoryLayer(tempLayer.FeatureClass, _GxFc);
                IFeatureCursor gxCursor = _GxFc.Update(null, true);
                int kcdlbmIndex = _GxFc.FindField("GXSJ");
                IFeature gxFeature = null;
                while ((gxFeature = gxCursor.NextFeature()) != null)
                {
                    gxFeature.Value[kcdlbmIndex] = new DateTime(DateTime.Now.Year - 1, 12, 31);
                    gxCursor.UpdateFeature(gxFeature);
                }
                gxCursor.Flush();
                BGHelper.GenerateGxgcData();
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex.Message);
                throw;
            }
        }
        /// 
        /// 指定图斑修改坐落信息变更
        /// 
        private void SelUpdateZLInfo(string pBGHDM, string pBGHMC, string BGQBSM, string BGHBSM, string BGQTBBH, string BGHTBBH, int GXOID)
        {
            IRDBHelper rdbHelper = null;
            string sql = string.Empty;
            IQueryFilter filter = new QueryFilterClass();
            try
            {
                IFeatureClass gxfc = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGX");
                int QSDWDMIndex = gxfc.FindField("QSDWDM");
                int QSDWMCIndex = gxfc.FindField("QSDWMC");
                string sqdwdm = gxfc.GetFeature(GXOID).Value[QSDWDMIndex].ToString();
                string sqdwmc = gxfc.GetFeature(GXOID).Value[QSDWMCIndex].ToString();
                //(不用区分村级与行政区)不区分县区村
                IFeatureClass DLTBGCFC = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGX");
                if (DLTBGCFC != null)
                {
                    //更新层BSM作为唯一条件
                    sql = $"UPDATE DLTBGX SET ZLDWDM ='{pBGHDM.ToTrim()}',ZLDWMC='{pBGHMC.ToTrim()}',QSDWDM ='{sqdwdm.ToTrim()}',QSDWMC='{sqdwmc.ToTrim()}' WHERE BSM='{BGHBSM}'";
                    (DLTBGCFC as FeatureClass).Workspace.ExecuteSQL(sql);
                }
                IFeatureClass TempGXGC = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGXGC");
                if (TempGXGC != null)
                {
                    //变更后BSM作为唯一条件
                    sql = $"UPDATE DLTBGXGC SET BGHZLDWDM='{pBGHDM.ToTrim()}',BGHZLDWMC='{pBGHMC.ToTrim()}',BGHQSDWDM='{sqdwdm.ToTrim()}',BGHQSDWMC='{sqdwmc.ToTrim()}' WHERE BGHTBBSM='{BGHBSM}' ";
                    (TempGXGC as FeatureClass).Workspace.ExecuteSQL(sql);
                }
                rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
                if (rdbHelper.TableIsExist("BHXXB"))
                {
                    //单图斑坐落信息变更确认修改变化信息表数据根据(变更前后BSM,变更前后TBBH)来确定当前唯一数据
                    sql = $"UPDATE BHXXB SET BGHZLDWDM='{pBGHDM.ToTrim()}',BGHZLDWMC='{pBGHMC.ToTrim()}',BGHQSDWDM='{sqdwdm.ToTrim()}',BGHQSDWMC='{sqdwmc.ToTrim()}' WHERE BGQTBBSM='{BGQBSM}' and BGHTBBSM='{BGHBSM}' and BGQTBBH='{BGQTBBH}' and BGHTBBH='{BGHTBBH}' ";
                    rdbHelper.ExecuteNonQuery(sql);
                }
            }
            catch (Exception ex)
            {
                ProgressHelper.CloseProcessBar();
                LogAPI.Debug("坐落属性赋值失败:" + ex.Message);
                MessageHelper.ShowError("坐落属性赋值失败:" + ex.Message);
            }
            finally
            {
                if (rdbHelper != null)
                {
                    rdbHelper.DisConnect();
                }
            }
        }
        /// 
        /// 更新坐落单位代码 名称
        /// 
        /// 
        /// 
        /// 
        /// 
        public void BGHZLExecute(string pBGQDM, string pBGQMC, string pBGHDM, string pBGHMC)
        {
            //IWorkspaceAPI wsAPI = null;
            //IWorkspace pWorkspace = null;
            IRDBHelper rdbHelper = null;
            string sql = string.Empty;
            IQueryFilter filter = new QueryFilterClass();
            IRow row = null;
            try
            {
                //string gdbpath = (MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetSchemeDBPath();
                //wsAPI = new WorkspaceAPI(gdbpath, KGIS.Framework.AE.Enum.WorkspaceTypeEnum.GDBFile);
                //pWorkspace = wsAPI.CurrentWorkspace;
                IFeatureClass DlTBGXFC = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGX");
                if (DlTBGXFC != null)
                {
                    ProgressHelper.Message = string.Format("【地类图斑更新层】正在进行坐落属性赋值,请稍后...");
                    if (rbtCJ.IsChecked.Value)//村级调查区
                    {
                        sql = $"UPDATE DLTBGX SET ZLDWDM ='{pBGHDM.ToTrim()}',ZLDWMC='{pBGHMC.ToTrim()}' WHERE ZLDWDM='{pBGQDM.ToTrim()}' and ZLDWMC='{pBGQMC.Trim()}' ";
                        (DlTBGXFC as FeatureClass).Workspace.ExecuteSQL(sql);
                        sql = $"UPDATE DLTBGX SET QSDWDM ='{pBGHDM.ToTrim()}',QSDWMC='{pBGHMC.ToTrim()}' WHERE QSDWDM='{pBGQDM.ToTrim()}' and QSDWMC='{pBGQMC.Trim()}' ";
                        (DlTBGXFC as FeatureClass).Workspace.ExecuteSQL(sql);
                    }
                    else//行政区(镇级)
                    {
                        filter.WhereClause = string.Format("ZLDWDM like '{0}%'", pBGQDM.ToTrim());
                        filter.SubFields = "OBJECTID,BSM,ZLDWDM,QSDWDM";
                        IFeatureClass fc = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGX");
                        ITable itb = fc as ITable;
                        ICursor cur = itb.Search(filter, true);
                        Dictionary keyValuePairs = new Dictionary();
                        int iBSM = itb.FindField("BSM");
                        int iZLDWDM = itb.FindField("ZLDWDM");
                        int iQSDWDM = itb.FindField("QSDWDM");
                        while ((row = cur.NextRow()) != null)
                        {
                            keyValuePairs.Add(row.OID, $"{row.Value[iZLDWDM]},{row.Value[iQSDWDM]},{row.Value[iBSM]}");//C# 6.0字符串拼接
                        }
                        foreach (var item in keyValuePairs)
                        {
                            var ZLDWDM = item.Value.Split(',')[0];
                            var QSDWDM = item.Value.Split(',')[1];
                            var BSM = item.Value.Split(',')[2];
                            if (pBGQDM.Length == 6 && pBGHDM.Length == 6)
                            {
                                sql = $"UPDATE DLTBGX SET BSM='{BSM.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim())}',ZLDWDM='{ZLDWDM.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim())}',QSDWDM='{QSDWDM.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim())}' WHERE OBJECTID={item.Key} ";
                            }
                            else
                            {
                                sql = $"UPDATE DLTBGX SET ZLDWDM='{ZLDWDM.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim())}',QSDWDM='{QSDWDM.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim())}' WHERE OBJECTID={item.Key} ";
                            }
                            (DlTBGXFC as FeatureClass).Workspace.ExecuteSQL(sql);
                        }
                    }
                }
                IFeatureClass DlTBGXGCFC = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGXGC");
                if (DlTBGXGCFC != null)
                {
                    ProgressHelper.Message = string.Format("【地类图斑更新过程层】正在进行坐落属性赋值,请稍后...");
                    if (rbtCJ.IsChecked.Value)
                    {
                        sql = $"UPDATE DLTBGXGC SET BGHZLDWDM='{pBGHDM.ToTrim()}',BGHZLDWMC='{pBGHMC.ToTrim()}' WHERE BGQZLDWDM='{pBGQDM.ToTrim()}' and BGQZLDWMC='{pBGQMC.Trim()}' ";
                        (DlTBGXGCFC as FeatureClass).Workspace.ExecuteSQL(sql);
                        sql = $"UPDATE DLTBGXGC SET BGHQSDWDM='{pBGHDM.ToTrim()}',BGHQSDWMC='{pBGHMC.ToTrim()}' WHERE BGQQSDWDM='{pBGQDM.ToTrim()}' and BGQQSDWMC='{pBGQMC.Trim()}' ";
                        (DlTBGXGCFC as FeatureClass).Workspace.ExecuteSQL(sql);
                    }
                    else
                    {
                        filter.WhereClause = string.Format("BGQZLDWDM like '{0}%'", pBGQDM.ToTrim());
                        filter.SubFields = "OBJECTID,BGHTBBSM,BGHZLDWDM,BGHQSDWDM";
                        IFeatureClass fc = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGXGC");
                        ITable itb = fc as ITable;
                        ICursor cur = itb.Search(filter, true);
                        Dictionary keyValuePairs = new Dictionary();
                        int iBGHTBBSM = itb.FindField("BGHTBBSM");
                        int iBGHZLDWDM = itb.FindField("BGHZLDWDM");
                        int iBGHQSDWDM = itb.FindField("BGHQSDWDM");
                        while ((row = cur.NextRow()) != null)
                        {
                            keyValuePairs.Add(row.OID, $"{row.Value[iBGHZLDWDM]},{row.Value[iBGHQSDWDM]},{row.Value[iBGHTBBSM]}");
                        }
                        foreach (var item in keyValuePairs)
                        {
                            var BGHZLDWDM = item.Value.Split(',')[0];
                            var BGHQSDWDM = item.Value.Split(',')[1];
                            var BGHTBBSM = item.Value.Split(',')[2];
                            if (pBGQDM.Length == 6 && pBGHDM.Length == 6)
                            {
                                sql = $"UPDATE DLTBGXGC SET BGHTBBSM='{BGHTBBSM.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim())}',BGHZLDWDM='{BGHZLDWDM.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim())}',BGHQSDWDM='{BGHQSDWDM.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim())}' WHERE OBJECTID={item.Key} ";
                            }
                            else
                            {
                                sql = $"UPDATE DLTBGXGC SET BGHZLDWDM='{BGHZLDWDM.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim())}',BGHQSDWDM='{BGHQSDWDM.Replace(pBGQDM.ToTrim(), pBGHDM.ToTrim())}' WHERE OBJECTID={item.Key} ";
                            }
                            (DlTBGXGCFC as FeatureClass).Workspace.ExecuteSQL(sql);
                        }
                    }
                }
                rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
                if (rdbHelper.TableIsExist("BHXXB"))
                {
                    ProgressHelper.Message = string.Format("【变化信息表】正在进行坐落属性赋值,请稍后...");
                    if (rbtCJ.IsChecked.Value)
                    {
                        sql = $"UPDATE BHXXB SET BGHZLDWDM='{pBGHDM.ToTrim()}',BGHZLDWMC='{pBGHMC.ToTrim()}' WHERE BGQZLDWDM='{pBGQDM.ToTrim()}' and BGQZLDWMC='{pBGQMC.Trim()}' ";
                        rdbHelper.ExecuteNonQuery(sql);
                        sql = $"UPDATE BHXXB SET BGHQSDWDM='{pBGHDM.ToTrim()}',BGHQSDWMC='{pBGHMC.ToTrim()}' WHERE BGQQSDWDM='{pBGQDM.ToTrim()}' and BGQQSDWMC='{pBGQMC.Trim()}' ";
                        rdbHelper.ExecuteNonQuery(sql);
                    }
                    else
                    {
                        if (pBGQDM.Length == 6 && pBGHDM.Length == 6)
                        {
                            sql = $"UPDATE BHXXB SET  BGHTBBSM=replace(BGHTBBSM,'{pBGQDM.ToTrim()}','{pBGHDM.ToTrim()}'),BGHZLDWDM=replace(BGHZLDWDM,'{pBGQDM.ToTrim()}','{pBGHDM.ToTrim()}'),BGHQSDWDM=replace(BGHQSDWDM,'{pBGQDM.ToTrim()}','{pBGHDM.ToTrim()}') ";
                        }
                        else
                        {
                            sql = $"UPDATE BHXXB SET  BGHZLDWDM=replace(BGHZLDWDM,'{pBGQDM.ToTrim()}','{pBGHDM.ToTrim()}'),BGHQSDWDM=replace(BGHQSDWDM,'{pBGQDM.ToTrim()}','{pBGHDM.ToTrim()}') WHERE BGHZLDWDM like '{pBGQDM.ToTrim()}%' ";
                        }
                        rdbHelper.ExecuteNonQuery(sql);
                    }
                }
            }
            catch (Exception ex)
            {
                ProgressHelper.CloseProcessBar();
                LogAPI.Debug("坐落属性赋值失败:" + ex.Message);
                MessageHelper.ShowError("坐落属性赋值失败:" + ex.Message);
            }
            finally
            {
                if (rdbHelper != null)
                {
                    rdbHelper.DisConnect();
                }
            }
        }
        /// 
        /// 多线程插入数据到db中
        /// 
        /// 
        /// 
        private void InsertDB(List listSQL, string dbPath)
        {
            try
            {
                using (BlockingCollection blockingCollection = new BlockingCollection())
                {
                    listSQL.ForEach(x => blockingCollection.Add(x));
                    blockingCollection.CompleteAdding();
                    int taskNum = 5;
                    Task[] tasks = new Task[taskNum];
                    for (int i = 0; i < taskNum; i++)
                    {
                        tasks[i] = Task.Factory.StartNew(() =>
                        {
                            ExcuteThead(blockingCollection, dbPath);
                        });
                    }
                    Task.WaitAll(tasks);
                    for (int i = 0; i < taskNum; i++)
                    {
                        tasks[i].Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void ExcuteThead(BlockingCollection blockingCollection, string dbPath)
        {
            IRDBHelper rdbHelper = null;
            string sqlDe = string.Empty;
            try
            {
                rdbHelper = RDBFactory.CreateDbHelper(string.Format("Data Source={0};Initial Catalog=sqlite;Integrated Security=True;Max Pool Size=10;", dbPath), DatabaseType.SQLite);
                if (rdbHelper == null)
                {
                    throw new Exception("执行成果接收时打开数据库连接字符串失败!");
                }
                rdbHelper.BeginTransaction();
                foreach (string sql in blockingCollection.GetConsumingEnumerable())
                {
                    sqlDe = sql;
                    rdbHelper.ExecuteNonQueryWithException(sql, CommandType.Text);
                }
                rdbHelper.Commit();
            }
            catch (Exception ex)
            {
                if (rdbHelper != null)
                    rdbHelper.Rollback();
                LogAPI.Debug(ex);
                throw ex;
            }
            finally
            {
                if (rdbHelper != null)
                    rdbHelper.DisConnect();
            }
        }
        private void InsertDataToMemeoryLayer(IFeatureClass pSource, IFeatureClass pTarget, IQueryFilter pFilter = null)
        {
            try
            {
                if (pSource == null || pTarget == null) return;
                IFeatureClassAPI fcAPI = new FeatureClassAPI(pSource);
                if (pTarget != null)
                    fcAPI.FcToFc(pTarget, pFilter, false);
            }
            catch (Exception ex)
            {
                LogAPI.Debug("插入数据失败:");
                LogAPI.Debug(ex);
            }
        }
        private static void GetMaxTBBH(IFeatureClass fc, ref Dictionary result)
        {
            try
            {
                ICursor cursor = (fc as ITable).Search(new QueryFilterClass() { SubFields = "ZLDWDM,TBBH" }, true);
                IRow row = null;
                int zlIndex = fc.FindField("ZLDWDM");
                int bhIndex = fc.FindField("TBBH");
                while ((row = cursor.NextRow()) != null)
                {
                    if (zlIndex != -1 && bhIndex != -1)
                    {
                        string zl = row.Value[zlIndex].ToTrim();
                        if (string.IsNullOrWhiteSpace(zl)) continue;
                        zl = zl.Replace(zl.Substring(0, 6), (MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).CODE);
                        int tbbh = 0;
                        int.TryParse(row.Value[bhIndex].ToString(), out tbbh);
                        if (result.ContainsKey(zl))
                        {
                            if (result[zl] < tbbh)
                                result[zl] = tbbh;
                        }
                        else
                        {
                            result.Add(zl, tbbh);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("获取图层图斑编号失败:" + ex.Message);
                throw;
            }
        }
    }
}