using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geodatabase;
using KGIS.Framework.AE;
using KGIS.Framework.OpenData.InterFace;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Helper;
using KGIS.Framework.Maps;
using Path = System.IO.Path;
using KGIS.Framework.Platform;
using Kingo.PluginServiceInterface;
using KGIS.Framework.AE.Enum;
using UIShell.OSGi;
using KGIS.Framework.DBOperator;
using System.Data;
using KGIS.Framework.Utils.Utility;
using KUI.Windows;
using Kingo.PluginServiceInterface.Helper.VCT;
using Kingo.PluginServiceInterface.Model;
namespace Kingo.Plugin.DataLoad.View
{
    /// 
    /// 参考数据加载 的交互逻辑
    /// 
    public partial class FrmLoadOtherData : BaseWindow
    {
        private IDataCatalogService _DataCatalog = null;
        public bool shutDown = false;
        /// 
        /// 导入数据类型(mdb文件为空,Shape文件为Shape)
        /// 
        public string ImportDataType { get; set; }
        private List pSourceFCList;
        private string SourceMDBPath { get; set; }
        /// 
        /// 拷贝参考数据路径
        /// 
        private string TempFinalLocation { get; set; }
        private List TempSelection = new List();
        /// 
        /// 当前工程参考数据路径
        /// 
        private string projectOtherDataPath = string.Empty;
        public FrmLoadOtherData()
        {
            InitializeComponent();
            if (_DataCatalog == null)
                _DataCatalog = BundleRuntime.Instance.GetFirstOrDefaultService();
            BindOtherDataPath();
            //隐藏复选框
            cbCopyBaseData.Height = 0;
        }
        #region 最新数据加载
        private void BindOtherDataPath()
        {
            try
            {
                IWorkCatalog workCatalog = BundleRuntime.Instance.GetFirstOrDefaultService();
                string code = (MapsManager.Instance.CurrProjectInfo as ProjectInfo).CODE;
                string xzqmc = GetXZQMC(code);
                string xzqDir = string.Format("{0}({1})", xzqmc, code);
                if (workCatalog != null && !string.IsNullOrWhiteSpace(code))
                {
                    string projectPath = Path.Combine(workCatalog.SaveWorkSapcePath, xzqDir, "参考数据");
                    if (Directory.Exists(projectPath))
                    {
                        List dataPathList = new List();
                        GetOtherDataPath(projectPath, dataPathList);
                        if (dataPathList.Count != 0)
                        {
                            this.cobDataBase.ItemsSource = dataPathList;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("获取参考数据文件失败:" + ex);
                MessageHelper.Show("获取参考数据文件失败:" + ex);
            }
        }
        private string GetXZQMC(string xzqdm)
        {
            string xzqmc = string.Empty;
            KGIS.Framework.DBOperator.IRDBHelper rdbHelper = null;
            try
            {
                string systemPath = SysAppPath.GetDataBasePath() + "System.mdb";
                if (File.Exists(systemPath))
                {
                    string connStr = SysConfigsOprator.GetDBConnectionByName("MDBOledbConnection");
                    connStr = string.Format(connStr, systemPath);
                    rdbHelper = RDBFactory.CreateDbHelper(connStr, DatabaseType.MSAccess);
                    //string strSQL = "select OBJECTID AS ID, XZQ AS CODE,XZQMC AS NAME from XZQ Where XZQ LIKE '" + xzqdm + "%'";
                    string strSQL = string.Format("select OBJECTID AS ID, XZQ AS CODE,XZQMC AS NAME from XZQ  Where XZQ = '{0}'", xzqdm);
                    DataTable dt = rdbHelper.ExecuteDatatable("Dic", strSQL, true);
                    if (dt != null)
                    {
                        List xzqCoderesult = TBToList.ToList(dt);
                        foreach (var item in xzqCoderesult)
                        {
                            if (dt.Rows.Count == 1)
                                xzqmc = item.NAME;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
            }
            finally
            {
                if (rdbHelper != null)
                    rdbHelper.DisConnect();
            }
            return xzqmc;
        }
        private void GetOtherDataPath(string dirPath, List pathList)
        {
            try
            {
                string[] dirArr = Directory.GetDirectories(dirPath);
                string[] fileArr = Directory.GetFiles(dirPath);
                // 遍历所有文件
                if (fileArr.Length > 0)
                {
                    string fileName;
                    foreach (string file in fileArr)
                    {
                        fileName = Path.GetFileName(file);
                        if ((fileName.ToLower().Contains(".vct") || fileName.ToLower().Contains(".mdb")) && !pathList.Contains(file))
                        {
                            pathList.Add(file);
                        }
                    }
                }
                // 遍历所有文件夹
                if (dirArr.Length > 0)
                {
                    string folderName;
                    foreach (string dir in dirArr)
                    {
                        folderName = Path.GetFileName(dir);
                        if (folderName.ToLower().Contains(".gdb") && !pathList.Contains(dir))
                        {
                            pathList.Add(dir);
                        }
                        GetOtherDataPath(dir, pathList);
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("获取参考数据文件失败:" + ex);
            }
        }
        /// 
        /// 文件路径加载切换事件
        /// 
        /// 
        /// 
        private void CobDataBase_SelectedIndexChanged(object sender, RoutedEventArgs e)
        {
            if (this.cobDataBase.ItemsSource != null)
            {
                try
                {
                    IFeatureClass pSourceFeatureClass = null;
                    if (this.cobDataBase.SelectedItem == null) return;
                    string selectedPath = this.cobDataBase.SelectedItem.ToString();
                    using (ComReleaser com = new ComReleaser())
                    {
                        IWorkspaceFactory pWorkspaceFactory = null;
                        IWorkspace pWorkspace = null;
                        IFeatureWorkspace pFeatureWorkspace = null;
                        if (string.IsNullOrWhiteSpace(ImportDataType))
                            ImportDataType = Path.GetExtension(selectedPath).ToUpper().Replace('.', ' ').TrimStart();
                        this.ShowLoading("正在打开数据文件...", 0, 0);
                        System.Threading.Thread.Sleep(1000);
                        string fileName = string.Empty;
                        if (string.IsNullOrWhiteSpace(ImportDataType))
                        {
                            ImportDataType = "Shape";
                            List shpPathList = new List();
                            if (shpPathList.Count == 0)
                            {
                                (this.cobDataBase.ItemsSource as List).Remove(selectedPath);
                                this.cobDataBase.RefreshData();
                                MessageHelper.ShowError("当前路径错误,请重新选择!");
                                return;
                            }
                            if (Directory.Exists(selectedPath))
                            {
                                string[] fileArr = Directory.GetFiles(selectedPath);
                                // 遍历所有文件
                                if (fileArr.Length > 0)
                                {
                                    foreach (string file in fileArr)
                                    {
                                        string extension = Path.GetExtension(file);
                                        if (extension.ToLower() == ".shp" && !shpPathList.Contains(file))
                                            shpPathList.Add(file);
                                    }
                                }
                                pSourceFCList = new List();
                                for (int i = 0; i < shpPathList.Count; i++)
                                {
                                    pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
                                    pWorkspace = pWorkspaceFactory.OpenFromFile(Path.GetDirectoryName(shpPathList[i]), 0);
                                    pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
                                    string name = Path.GetFileName(shpPathList[i]);
                                    pSourceFeatureClass = pFeatureWorkspace.OpenFeatureClass(name);
                                    pSourceFCList.Add(pSourceFeatureClass);
                                    fileName += name + ";";
                                }
                                if (pSourceFCList.Count > 0)
                                {
                                    SetShapeTableMapping();
                                }
                            }
                        }
                        else if (!string.IsNullOrWhiteSpace(ImportDataType) && ImportDataType.Equals("Shape") && pSourceFCList.Count != 0)
                        {
                            SetShapeTableMapping();
                        }
                        else if (!string.IsNullOrWhiteSpace(ImportDataType) && ImportDataType.Equals("VCT"))
                        {
                            string TempMDBFolderPath = Path.GetTempPath();
                            string TempMDBPath = Path.Combine(TempMDBFolderPath, string.Format("{0}.mdb", Path.GetFileNameWithoutExtension(selectedPath)));
                            if (File.Exists(TempMDBPath))
                                File.Delete(TempMDBPath);
                            this.ShowLoading("正在解析VCT文件... ...", 0, 0);
                            VCTToMDBHelper3 vcttomdb = new VCTToMDBHelper3();
                            vcttomdb.RootPath = TempMDBFolderPath;
                            vcttomdb.VCTToMDB(selectedPath);
                            this.CloseLoading();
                            if (!File.Exists(TempMDBPath))
                            {
                                MessageHelper.ShowError("VCT文件解析失败");
                                return;
                            }
                            SourceMDBPath = TempMDBPath;
                            SetTableMapping();
                        }
                        else
                        {
                            SetTableMapping();
                        }
                        this.CloseLoading();
                        com.ManageLifetime(pWorkspaceFactory);
                        com.ManageLifetime(pWorkspace);
                        com.ManageLifetime(pFeatureWorkspace);
                    }
                }
                catch (Exception ex)
                {
                    LogAPI.Debug("选择参考数据库失败:" + ex);
                    this.CloseLoading();
                    MessageHelper.Show("选择参考数据库失败:" + ex);
                }
                finally
                {
                    this.CloseLoading();
                }
            }
        }
        private void SetTableMapping()
        {
            IWorkspaceAPI t_WsAPI = null;
            IWorkspaceAPI s_WsAPI = null;
            IFeatureClassAPI s_FCAPI = null;
            try
            {
                dgTableMapping.ItemsSource = null;
                string s_MdbPath = null;
                if (ImportDataType == "VCT")
                {
                    s_MdbPath = SourceMDBPath;
                }
                else
                {
                    if (this.cobDataBase.SelectedItem != null)
                        s_MdbPath = this.cobDataBase.SelectedItem.ToString();
                }
                if ((ImportDataType == "MDB" || ImportDataType == "VCT") && !File.Exists(s_MdbPath))
                {
                    this.CloseLoading();
                    MessageHelper.ShowTips("请确保文件存在,并且为mdb文件!");
                    return;
                }
                else if (ImportDataType == "GDB" && !Directory.Exists(s_MdbPath))
                {
                    this.CloseLoading();
                    MessageHelper.ShowTips("请确保GDB文件夹存在!");
                    return;
                }
                if (ImportDataType == "MDB" || ImportDataType == "VCT")
                {
                    FileInfo s_MdbPathInfo = new FileInfo(s_MdbPath);
                    if (!s_MdbPathInfo.Extension.Equals(".mdb"))
                    {
                        this.CloseLoading();
                        MessageHelper.ShowTips("必须为mdb文件才能进行导入!");
                        return;
                    }
                }
                if (ImportDataType == "MDB" || ImportDataType == "VCT")
                {
                    s_WsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.MDBFile);
                }
                else if (ImportDataType == "GDB" && Directory.Exists(s_MdbPath))
                {
                    s_WsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.GDBFile);
                }
                else if (!Directory.Exists(s_MdbPath) && !File.Exists(s_MdbPath))
                {
                    return;
                }
                List s_TbList = s_WsAPI.GetFeatureClassName(esriDatasetType.esriDTFeatureDataset).Where(x => !x.Value.StartsWith("TDQSQ") && !x.Value.StartsWith("JC_CZCDYD")).Select(x => new KeyAndValue() { S_Key = x.Key, S_Value = x.Value }).ToList();//周旺华 0424 排除TDQSQ导致的导入问题
                Dictionary s_TbList2 = s_WsAPI.GetFeatureClassName(esriDatasetType.esriDTFeatureClass);
                Dictionary s_TbList3 = s_WsAPI.GetFeatureClassName(esriDatasetType.esriDTTable);
                foreach (string item in s_TbList2.Keys)
                {
                    if (!s_TbList.Select(x => x.S_Value).Contains(item))
                        s_TbList.Add(new KeyAndValue() { S_Key = item, S_Value = s_TbList2[item] });
                }
                if (s_TbList != null)
                {
                    List MappingList = new List();
                    foreach (string key in s_TbList.Select(x => x.S_Key))
                    {
                        var s_keyvalue = s_TbList.FirstOrDefault(x => x.S_Key == key).S_Value;
                        TableMapping mapping = new TableMapping();
                        mapping.State = TBState.Waiting;
                        mapping.S_TableName = s_keyvalue;
                        mapping.S_TableAliasName = key;
                        if (s_TbList3.Values.Contains(mapping.S_TableName))
                        {
                            mapping.S_TableType = "Table";
                        }
                        else
                        {
                            s_FCAPI = s_WsAPI.OpenFeatureClass(s_keyvalue);
                            mapping.S_Spatial = (s_FCAPI.FeatureClass as IGeoDataset).SpatialReference.Name;
                            mapping.S_TableType = s_FCAPI.FeatureClass.ShapeType.ToString();
                            s_FCAPI.CloseFeatureClass();
                        }
                        mapping.T_TableName = s_keyvalue;
                        mapping.T_TableAliasName = key;
                        MappingList.Add(mapping);
                    }
                    dgTableMapping.ItemsSource = MappingList;
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
                MessageHelper.ShowTips(ex.Message);
            }
            finally
            {
                s_WsAPI?.CloseWorkspace();
                t_WsAPI?.CloseWorkspace();
                if (s_FCAPI != null)
                {
                    s_FCAPI.CloseFeatureClass();
                    s_FCAPI = null;
                }
            }
        }
        private void SetShapeTableMapping()
        {
            try
            {
                dgTableMapping.ItemsSource = null;
                List MappingList = new List();
                foreach (IFeatureClass pSourceFeatureClass in pSourceFCList)
                {
                    //pSourceFeatureClass.CheckArea();
                    TableMapping mapping = new TableMapping();
                    mapping.State = TBState.Waiting;
                    mapping.S_TableName = (pSourceFeatureClass as FeatureClass).Name;
                    mapping.S_TableAliasName = pSourceFeatureClass.AliasName;
                    mapping.S_Spatial = (pSourceFeatureClass as IGeoDataset).SpatialReference.Name;
                    mapping.S_TableType = pSourceFeatureClass.ShapeType.ToString();
                    mapping.T_TableName = (pSourceFeatureClass as FeatureClass).Name;
                    mapping.T_TableAliasName = pSourceFeatureClass.AliasName;
                    mapping.S_TableType = pSourceFeatureClass.ShapeType.ToString();
                    MappingList.Add(mapping);
                }
                dgTableMapping.ItemsSource = MappingList;
                //JudgeIsTheSameSpatialReference();
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
                MessageHelper.ShowTips(ex.Message);
            }
        }
        /// 
        /// 重置导入
        /// 
        public void ResetImport()
        {
            try
            {
                //将选中的数据源地址清空
                this.cobDataBase.SelectedItem = null;
                //将映射关系置空
                if (dgTableMapping != null)
                {
                    if (dgTableMapping.ItemsSource != null)
                    {
                        dgTableMapping.ItemsSource = null;
                    }
                    dgTableMapping.UnselectAll();
                    dgTableMapping.RefreshData();
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("重置 " + ImportDataType + " 的导入失败,异常原因: " + ex + " ; ");
            }
        }
        /// 
        /// 全选和反选事件
        /// 
        /// 
        /// 
        private void chkSelectedAll_EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
        {
            try
            {
                if (this.dgTableMapping == null || (dgTableMapping.ItemsSource as List) == null)
                {
                    return;
                }
                List listTableMapping = (dgTableMapping.ItemsSource as List);
                bool check = (sender as DevExpress.Xpf.Editors.CheckEdit).IsChecked == null ? false : bool.Parse((sender as DevExpress.Xpf.Editors.CheckEdit).IsChecked.Value.ToString());
                if (check)
                {
                    listTableMapping.ForEach(x => x.State = TBState.Waiting);
                }
                else
                {
                    listTableMapping.ForEach(x => x.State = TBState.Delete);
                }
                dgTableMapping.RefreshData();
            }
            catch (Exception ex)
            {
                MessageHelper.ShowTips("全选发生异常:" + ex.Message);
            }
        }
        private void BtnLoad_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //外部数据拷贝至工作目录参考数据文件夹
                if (this.cbCopyBaseData.IsChecked == true && TempSelection != null)
                {
                    IWorkCatalog workCatalog = BundleRuntime.Instance.GetFirstOrDefaultService();
                    string code = (MapsManager.Instance.CurrProjectInfo as ProjectInfo).CODE;
                    string xzqmc = GetXZQMC(code);
                    string xzqDir = string.Format("{0}({1})", xzqmc, code);
                    if (workCatalog != null && !string.IsNullOrWhiteSpace(code))
                    {
                        projectOtherDataPath = Path.Combine(workCatalog.SaveWorkSapcePath, xzqDir, "参考数据");
                        if (!Directory.Exists(projectOtherDataPath))
                            Directory.CreateDirectory(projectOtherDataPath);
                        if (ImportDataType == "GDB")
                            PluginServiceInterface.CommonHelper.DirectoryCopy(TempFinalLocation, projectOtherDataPath);
                        else
                        {
                            for (int i = 0; i < TempSelection.Count; i++)
                            {
                                string name = Path.GetFileName(TempSelection[i].FullName);
                                string nameWithoutExtension = Path.GetFileNameWithoutExtension(TempSelection[i].FullName);
                                if (ImportDataType == "SHP")
                                {
                                    string shpDir = Path.GetDirectoryName(TempSelection[i].FullName);
                                    string[] fileArr = Directory.GetFiles(shpDir);
                                    for (int j = 0; j < fileArr.Length; j++)
                                    {
                                        string name2 = Path.GetFileName(fileArr[j]);
                                        string name2WithoutExtension = Path.GetFileNameWithoutExtension(fileArr[j]);
                                        if (nameWithoutExtension == name2WithoutExtension)
                                            File.Copy(fileArr[j], projectOtherDataPath + "\\" + name2, true);
                                    }
                                }
                                else
                                {
                                    File.Copy(TempSelection[i].FullName, projectOtherDataPath + "\\" + name, true);
                                }
                            }
                        }
                    }
                }
                if (!string.IsNullOrWhiteSpace(ImportDataType) && ImportDataType.Equals("Shape"))
                {
                    LoadShpData();
                }
                else
                {
                    LoadData();
                }
                //刷新视图
                //Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "RefreshLayer" });
            }
            catch (Exception ex)
            {
                MessageHelper.ShowError(ex.Message);
                LogAPI.Debug(ex);
            }
        }
        private void LoadData()
        {
            this.btnLoad.IsEnabled = false;
            List mapping = dgTableMapping.ItemsSource as List;
            IWorkspaceAPI pSourceWsAPI = null;
            try
            {
                if (this.cobDataBase.SelectedItem == null)
                {
                    MessageHelper.ShowTips("请先选择要导入的参考数据!");
                    return;
                }
                else
                {
                    if (ImportDataType == "GDB")
                    {
                        if ((Directory.Exists(this.cobDataBase.SelectedItem.ToString()) == false) || this.cobDataBase.SelectedItem.ToString().ToLower().EndsWith(".gdb") == false)
                        {
                            MessageHelper.ShowTips("无效的 " + ImportDataType + " 数据源");
                            this.cobDataBase.SelectedItem = null;
                            return;
                        }
                    }
                    else//MDB/VCT/DCSJ
                    {
                        if (File.Exists(this.cobDataBase.SelectedItem.ToString()) == false)
                        {
                            MessageHelper.ShowTips("无效的 " + ImportDataType + " 数据源");
                            this.cobDataBase.SelectedItem = null;
                            return;
                        }
                    }
                }
                string s_MdbPath = null;
                if (ImportDataType == "VCT")
                {
                    s_MdbPath = SourceMDBPath;
                }
                else if (this.cobDataBase.SelectedItem != null)
                {
                    s_MdbPath = this.cobDataBase.SelectedItem.ToString();
                }
                if (string.IsNullOrWhiteSpace(s_MdbPath)) return;
                if (ImportDataType == "MDB" || ImportDataType == "VCT" || ImportDataType == "DCSJ")
                {
                    if (!File.Exists(s_MdbPath)) return;
                    pSourceWsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.MDBFile);
                }
                else
                {
                    if (!Directory.Exists(s_MdbPath)) return;
                    pSourceWsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.GDBFile);
                }
                if (mapping != null)
                {
                    //循环导入要素类
                    string message = string.Empty;
                    string errorMessage = string.Empty;
                    int SuccessImportLayerCount = 0;
                    int DeletedImportLayerCount = 0;
                    int FailImportLayerCount = 0;
                    ILayer layer = MapsManager.Instance.MapService.GetGroupLayer("CKSJ");//获取参考数据图层组
                    LayerCfg GroupLayerInfo = null;
                    if (_DataCatalog != null)
                    {
                        _DataCatalog.GetNodeByLayer(layer);
                        LayerCfg rootLayer = _DataCatalog.CurrentLayers as LayerCfg;
                        List AllLayers = rootLayer.GetAllItem();
                        GroupLayerInfo = AllLayers.FirstOrDefault(f => f.LayerName == layer.Name);
                    }
                    foreach (TableMapping table in mapping)
                    {
                        if (shutDown)
                        {
                            return;
                        }
                        if (table.State == TBState.Delete) continue;
                        if (string.IsNullOrWhiteSpace(table.T_TableName) || table.T_TableName == "null" || string.IsNullOrWhiteSpace(table.T_TableAliasName))
                            continue;
                        dgTableMapping.SelectedItem = table;
                        dgTableMapping.View.ScrollIntoView(dgTableMapping.SelectedItem);
                        System.Windows.Forms.Application.DoEvents();
                        table.State = TBState.BeingImport;
                        if (AddLayerToMap(GroupLayerInfo, table, pSourceWsAPI, ref message, ref errorMessage, ref FailImportLayerCount))
                        {
                            table.State = TBState.EndImport;
                            SuccessImportLayerCount++;
                        }
                        else
                        {
                            table.State = TBState.Delete;
                            DeletedImportLayerCount++;
                        }
                    }
                    if (_DataCatalog != null)
                    {
                        if (GroupLayerInfo.Layers.Count > 0)
                            GroupLayerInfo.Expanded = true;//添加数据时展开
                        _DataCatalog.UpdateTree();
                    }
                    if (!string.IsNullOrWhiteSpace(errorMessage))
                    {
                        int TotalImportLayerCount = SuccessImportLayerCount + DeletedImportLayerCount + FailImportLayerCount;
                        errorMessage = string.Format("共导入{0}个图层,成功{1}个,删除{2}个,失败{3}个。", TotalImportLayerCount, SuccessImportLayerCount,
                            DeletedImportLayerCount, FailImportLayerCount) + errorMessage;
                        MessageHelper.Show(errorMessage, true);
                    }
                    else
                    {
                        int TotalImportLayerCount = SuccessImportLayerCount + DeletedImportLayerCount + FailImportLayerCount;
                        message = string.Format("共导入{0}个图层,成功{1}个,删除{2}个,失败{3}个。", TotalImportLayerCount, SuccessImportLayerCount,
                            DeletedImportLayerCount, FailImportLayerCount) + message;
                        MessageHelper.Show(message, true);
                    }
                    Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "SaveProject" });
                    //这里设置关闭
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("导入 " + ImportDataType + " 数据时失败,异常原因: " + ex + " ; ");
            }
            finally
            {
                this.btnLoad.IsEnabled = true;
                if (pSourceWsAPI != null)
                {
                    pSourceWsAPI.CloseWorkspace();
                }
                if (mapping != null && mapping.Count() > 0)
                {
                    mapping = null;
                }
            }
        }
        private void LoadShpData()
        {
            try
            {
                string str = "1234567890";
                if (dgTableMapping.ItemsSource is List mapping)
                {
                    //循环导入要素类
                    string message = string.Empty;
                    string errorMessage = string.Empty;
                    int SuccessImportLayerCount = 0;
                    int DeletedImportLayerCount = 0;
                    int FailImportLayerCount = 0;
                    ILayer layer = MapsManager.Instance.MapService.GetGroupLayer("CKSJ");//获取参考数据图层组
                    LayerCfg GroupLayerInfo = null;
                    if (_DataCatalog != null)
                    {
                        _DataCatalog.GetNodeByLayer(layer);
                        LayerCfg rootLayer = _DataCatalog.CurrentLayers as LayerCfg;
                        List AllLayers = rootLayer.GetAllItem();
                        GroupLayerInfo = AllLayers.FirstOrDefault(f => f.LayerName == layer.Name);
                    }
                    foreach (TableMapping table in mapping)
                    {
                        //增加控制,以数字开头的图层不能追加到当前工程。对应bug11125
                        if (str.Contains(table.S_TableName.Substring(0, 1)) && table.T_TableName == "Add")
                        {
                            MessageHelper.ShowTips("以数字开头的图层不能追加到当前工程!");
                            return;
                        }
                        if (shutDown)
                        {
                            break;
                        }
                        if (table.State == TBState.Delete)
                            continue;
                        if (string.IsNullOrWhiteSpace(table.T_TableName) || table.T_TableName == "null" || string.IsNullOrWhiteSpace(table.T_TableAliasName))
                            continue;
                        dgTableMapping.SelectedItem = table;
                        dgTableMapping.View.ScrollIntoView(dgTableMapping.SelectedItem);
                        System.Windows.Forms.Application.DoEvents();
                        table.State = TBState.BeingImport;
                        if (AddShpToMap(GroupLayerInfo, table, ref message, ref errorMessage, ref FailImportLayerCount))
                        {
                            table.State = TBState.EndImport;
                            SuccessImportLayerCount++;
                        }
                        else
                        {
                            table.State = TBState.Delete;
                            SuccessImportLayerCount++;
                        }
                    }
                    if (_DataCatalog != null)
                    {
                        if (GroupLayerInfo.Layers.Count > 0)
                            GroupLayerInfo.Expanded = true;
                        _DataCatalog.UpdateTree();
                    }
                    MapsManager.Instance.MapService.getAxMapControl().Refresh();
                    if (!string.IsNullOrWhiteSpace(errorMessage))
                    {
                        int TotalImportLayerCount = SuccessImportLayerCount + DeletedImportLayerCount + FailImportLayerCount;
                        errorMessage = string.Format("共导入{0}个图层,成功{1}个,删除{2}个,失败{3}个。", TotalImportLayerCount, SuccessImportLayerCount,
                            DeletedImportLayerCount, FailImportLayerCount) + errorMessage;
                        MessageHelper.Show(errorMessage, true);
                    }
                    else
                    {
                        int TotalImportLayerCount = SuccessImportLayerCount + DeletedImportLayerCount + FailImportLayerCount;
                        message = string.Format("共导入{0}个图层,成功{1}个,删除{2}个,失败{3}个。", TotalImportLayerCount, SuccessImportLayerCount,
                            DeletedImportLayerCount, FailImportLayerCount) + message;
                        MessageHelper.Show(message, true);
                    }
                    Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "SaveProject" });
                    //这里设置关闭
                    this.Close();
                }
                else
                {
                    if (this.cobDataBase.SelectedItem == null)
                    {
                        MessageHelper.ShowTips("请先选择 Shape 数据源");
                    }
                    else
                    {
                        string s_MdbPath_T2 = this.cobDataBase.SelectedItem.ToString();
                        if (string.IsNullOrWhiteSpace(s_MdbPath_T2) == true)
                        {
                            MessageHelper.ShowTips("请先选择 Shape 数据源");
                        }
                        else
                        {
                            if (Directory.Exists(s_MdbPath_T2) == false)
                            {
                                MessageHelper.ShowTips("选择的 Shape 数据源不存在");
                                (this.cobDataBase.ItemsSource as List).Remove(s_MdbPath_T2);// = null;
                                this.cobDataBase.RefreshData();
                            }
                            else
                            {
                                //判断目录下有没有shape文件
                                string[] strFiles = Directory.GetFiles(s_MdbPath_T2);
                                int iFileDirs = strFiles.Count();
                                List ShapeFileNameList = strFiles.ToList();
                                if (ShapeFileNameList == null || ShapeFileNameList.Count <= 0)
                                {
                                    MessageHelper.ShowTips("Shape 数据源不能为空");
                                    (this.cobDataBase.ItemsSource as List).Remove(s_MdbPath_T2);// = null;
                                    this.cobDataBase.RefreshData();
                                }
                                else
                                {
                                    bool bHaveShp = false;
                                    foreach (string strFile in strFiles)
                                    {
                                        if (strFile.ToLower().EndsWith(".shp") == true)
                                        {
                                            bHaveShp = true;
                                            break;
                                        }
                                    }
                                    if (bHaveShp == false)
                                    {
                                        MessageHelper.ShowTips("Shape 数据源不能为空");
                                        (this.cobDataBase.ItemsSource as List).Remove(s_MdbPath_T2);// = null;
                                        this.cobDataBase.RefreshData();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pSourceFCList != null && pSourceFCList.Count > 0)
                {
                    using (ComReleaser com = new ComReleaser())
                    {
                        foreach (IFeatureClass item in pSourceFCList)
                        {
                            com.ManageLifetime(item);
                        }
                    }
                }
                this.CloseLoading();
            }
        }
        private bool AddLayerToMap(LayerCfg cksjGroupLayer, TableMapping pTbMaping, IWorkspaceAPI pSourceWsAPI, ref string message, ref string errorMessage, ref int FailImportLayerCount)
        {
            if (pSourceWsAPI == null || pSourceWsAPI.CurrentWorkspace == null || cksjGroupLayer == null)
                return false;
            IFeatureClassAPI s_FcAPI = null;
            try
            {
                if (!string.IsNullOrWhiteSpace(pTbMaping.S_TableName) && !string.IsNullOrWhiteSpace(pTbMaping.T_TableName))
                {
                    s_FcAPI = pSourceWsAPI.OpenFeatureClass(pTbMaping.S_TableName);
                    if (s_FcAPI != null && s_FcAPI.FeatureClass != null)
                    {
                        IFeatureLayer pTargetLayer = new FeatureLayer
                        {
                            FeatureClass = s_FcAPI.FeatureClass,
                            Name = pTbMaping.T_TableAliasName
                        };
                        ILegendInfo pLegendInfo = pTargetLayer as ILegendInfo;
                        int legendGroupCount = pLegendInfo.LegendGroupCount;
                        ILegendGroup pLGroup;
                        for (int i = 0; i < legendGroupCount; i++)
                        {
                            pLGroup = pLegendInfo.get_LegendGroup(i);
                            pLGroup.Visible = false;
                        }
                        if (cksjGroupLayer.Data is IGroupLayer groupLayer)
                        {
                            ICompositeLayer pComLayer = groupLayer as ICompositeLayer;
                            for (int i = 0; i < pComLayer.Count; i++)
                            {
                                ILayer layer = pComLayer.Layer[i];
                                if ((layer as IDataset).BrowseName == pTbMaping.S_TableName)
                                {
                                    groupLayer.Delete(layer);
                                }
                            }
                        }
                        if (_DataCatalog != null)
                        {
                            //object parentLayer = _DataCatalog.GetNodeByLayer(ncsjGroupLayer);
                            _DataCatalog.AddLayer(pTargetLayer, cksjGroupLayer);
                        }
                    }
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                FailImportLayerCount++;
                errorMessage += (pTbMaping.S_TableName + "图层数据导入异常!" + ex.Message);
                return false;
            }
            finally
            {
                if (s_FcAPI != null)
                    s_FcAPI.CloseFeatureClass();
            }
        }
        public List GetSubLayer(ICompositeLayer group)
        {
            List result = new List();
            for (int i = 0; i < group.Count; i++)
            {
                var item = group.Layer[i];
                if (item is ICompositeLayer)
                {
                    result.AddRange(GetSubLayer(item as ICompositeLayer));
                }
                else if (item is T)
                {
                    result.Add((T)item);
                }
            }
            return result;
        }
        private bool AddShpToMap(LayerCfg cksjGroupLayer, TableMapping pTbMaping, ref string message, ref string errorMessage, ref int FailImportLayerCount)
        {
            if (pSourceFCList == null || cksjGroupLayer == null)
                return false;
            IFeatureClassAPI t_FcAPI = null;
            IFeatureClass pSourceFeatureClass = null;
            string currentFiled = string.Empty;
            try
            {
                if (!string.IsNullOrWhiteSpace(pTbMaping.S_TableName) && !string.IsNullOrWhiteSpace(pTbMaping.T_TableName))
                {
                    pSourceFeatureClass = pSourceFCList.Where(p => (p as FeatureClass).Name.Equals(pTbMaping.S_TableName) || p.AliasName.Equals(pTbMaping.S_TableName)).Single();
                    if (pSourceFeatureClass == null)
                    {
                        return false;
                    }
                    IFeatureLayer pTargetLayer = new FeatureLayer
                    {
                        FeatureClass = pSourceFeatureClass,
                        Name = pTbMaping.T_TableAliasName
                    };
                    ILegendInfo pLegendInfo = pTargetLayer as ILegendInfo;
                    int legendGroupCount = pLegendInfo.LegendGroupCount;
                    ILegendGroup pLGroup;
                    for (int i = 0; i < legendGroupCount; i++)
                    {
                        pLGroup = pLegendInfo.get_LegendGroup(i);
                        pLGroup.Visible = false;
                    }
                    _DataCatalog.AddLayer(pTargetLayer, cksjGroupLayer);
                }
                return false;
            }
            catch (Exception ex)
            {
                FailImportLayerCount++;
                errorMessage += (pTbMaping.S_TableName + "图层数据导入异常!" + ex.Message);
                return false;
            }
            finally
            {
                t_FcAPI?.CloseFeatureClass();
            }
        }
        /// 
        /// 选择本地的参考数据
        /// 
        /// 
        /// 
        private void BtnSelectedOtherData_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (ComReleaser com = new ComReleaser())
                {
                    List otherDataPathList = new List();
                    pSourceFCList = new List();
                    string FinalLocation = "";
                    PluginServiceInterface.Helper.OpenDataDialogHelper.OpenDataDialog("选择其他参考数据", ref FinalLocation, ref TempSelection, ref otherDataPathList, ref pSourceFCList);
                    ResetImport();
                    TempFinalLocation = FinalLocation;
                    if (string.IsNullOrWhiteSpace(TempFinalLocation)) return;
                    ImportDataType = Path.GetExtension(FinalLocation).ToUpper().Replace('.', ' ').TrimStart();
                    if (ImportDataType == "SHP") ImportDataType = "Shape";
                    this.cobDataBase.ItemsSource = null;
                    if (!string.IsNullOrWhiteSpace(ImportDataType) && ImportDataType.Equals("Shape"))
                    {
                        if (pSourceFCList.Count != 0 && otherDataPathList.Count != 0)
                        {
                            this.cobDataBase.ItemsSource = null;
                            this.cobDataBase.ItemsSource = otherDataPathList;
                            this.cobDataBase.SelectedIndex = 0;
                        }
                    }
                    else if (!string.IsNullOrWhiteSpace(ImportDataType) && ImportDataType.Equals("VCT"))
                    {
                        string TempMDBFolderPath = Path.GetTempPath();
                        string TempMDBPath = Path.Combine(TempMDBFolderPath, string.Format("{0}.mdb", Path.GetFileNameWithoutExtension(FinalLocation)));
                        if (File.Exists(TempMDBPath))
                            File.Delete(TempMDBPath);
                        VCTToMDBHelper3 vcttomdb = new VCTToMDBHelper3
                        {
                            RootPath = TempMDBFolderPath
                        };
                        vcttomdb.VCTToMDB(FinalLocation);
                        this.CloseLoading();
                        if (!File.Exists(TempMDBPath))
                        {
                            MessageHelper.ShowError("VCT文件解析失败");
                            return;
                        }
                        SourceMDBPath = TempMDBPath;
                        otherDataPathList.Add(FinalLocation);
                        this.cobDataBase.ItemsSource = null;
                        this.cobDataBase.ItemsSource = otherDataPathList;
                        this.cobDataBase.SelectedIndex = 0;
                        SetTableMapping();
                    }
                    else
                    {
                        otherDataPathList.Add(FinalLocation);
                        this.cobDataBase.ItemsSource = null;
                        this.cobDataBase.ItemsSource = otherDataPathList;
                        this.cobDataBase.SelectedIndex = 0;
                        SetTableMapping();
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("选择参考数据库失败:" + ex);
                MessageHelper.Show("选择参考数据库失败:" + ex.Message);
            }
        }
        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            TableMapping tbm = dgTableMapping.SelectedItem as TableMapping;
            if (tbm != null)
            {
                switch (tbm.State)
                {
                    case TBState.Waiting:
                        tbm.State = TBState.Delete;
                        break;
                    case TBState.Delete:
                        tbm.State = TBState.Waiting;
                        break;
                    case TBState.BeingImport:
                        break;
                    case TBState.EndImport:
                        break;
                    default:
                        break;
                }
                dgTableMapping.RefreshData();
            }
        }
        /// 
        /// 取消
        /// 
        /// 
        /// 
        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        private void BaseWindow_Closing(object sender, CancelEventArgs e)
        {
            this.shutDown = true;
        }
        #endregion
    }
}