using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geoprocessor;
using KGIS.Framework.AE;
using KGIS.Framework.AE.GPHelper;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Dialog;
using KGIS.Framework.Utils.Helper;
using Kingo.PluginServiceInterface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
namespace Kingo.Plugin.DataLoad.View
{
    /// 
    /// FrmLoadDB.xaml 的交互逻辑
    /// 
    public partial class FrmLoadDB : BaseWindow
    {
        public FrmLoadDB()
        {
            InitializeComponent();
        }
        private void btnBrowse_Click_1(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.DefaultExt = "db";
            dialog.Filter = "举证成果包(*.db)|*.db";
            if (dialog.ShowDialog())
            {
                this.txtPath.Text = dialog.FileName;
            }
        }
        private void btnImport_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtPath.Text))
                {
                    MessageHelper.Show("未获取到文件路径:" + txtPath.Text);
                    return;
                }
                string path = txtPath.Text;
                if (!File.Exists(path))
                {
                    MessageHelper.Show("文件不存在,请重新选择!");
                    return;
                }
                if (!path.EndsWith(".db"))
                {
                    MessageHelper.ShowTips("文件格式不正确,请重新选择!");
                    return;
                }
                ProjectInfo info = (MapsManager.Instance.CurrProjectInfo as ProjectInfo);
                info.DBPath = path;
                //info.Save();
                Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "SaveProject" });
                LoadDBFile(path, info);
                MessageHelper.ShowTips("加载完成!");
                this.Close();
            }
            catch (Exception ex)
            {
                MessageHelper.ShowError("导入数据字典异常:" + ex.Message);
            }
        }
        public string LoadDBFile(string dbPath, ProjectInfo info)
        {
            try
            {
                string sjztcName = string.Empty;
                string targetSourcePath = string.Empty;
                string targetResultPath = string.Empty;
                sjztcName = "BGDC2020";
                //string fields = "F_ID,TBYBH,FJMC,TCBM,Longitude,Latitude,FJLX,PSJD,XZB,YZB";
                //string msg = "";
                Dictionary dic = new Dictionary();
                dic.Add("JCBH", "JCBH");
                dic.Add("BGDL", "BGDL");
                dic.Add("BGFW", "BGFW");
                dic.Add("WBGLX", "WBGLX");
                dic.Add("QSX", "QSX");
                dic.Add("HSX", "HSX");
                dic.Add("TBLX", "TBLX");
                dic.Add("XZQDM", "XZQDM");
                dic.Add("XMC", "XMC");
                dic.Add("JCMJ", "JCMJ");
                dic.Add("XZB", "XZB");
                dic.Add("YZB", "YZB");
                dic.Add("TZ", "TZ");
                dic.Add("BZ", "BZ");
                dic.Add("JZRY", "JZRY");
                dic.Add("SJLY", "SJLY");
                SQLiteDataReader rowTYSDJZ = SQLiteDBOperate.Instance.ExecuteDataReader(dbPath, "select * from " + sjztcName, null);
                IFeatureClass featureClass = MapsManager.Instance.MapService.GetFeatureClassByName("JZCG");
                InsertPolygonToTYSDJZ(rowTYSDJZ, "JZCG", "TBFW", dic, featureClass);
                rowTYSDJZ.Close();
                Geoprocessor mGP = new Geoprocessor() { OverwriteOutput = true };
                // GeoprocessorHelper.RepairGeo(featureClass, true);
                if (null != featureClass)
                    Marshal.FinalReleaseComObject(featureClass);
                return null;
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
                return "举证包数据导入失败:" + ex.Message;
            }
            finally
            {
                GC.Collect();
            }
        }
        /// 
        /// 从外业举证包中导入统一时点举证地类图斑
        /// 
        /// 
        /// 
        /// 
        /// 
        public void InsertPolygonToTYSDJZ(SQLiteDataReader row, string featureName, string shapCol, Dictionary dicMap, IFeatureClass featureClass)
        {
            //IFeatureClass featureClass = featurespace.OpenFeatureClass(featureName);
            //先清空
            ITable pTable = featureClass as ITable;
            pTable.DeleteSearchedRows(null);
            IFeatureCursor feaCursor = featureClass.Insert(true);
            IFeatureBuffer feaBuffer = featureClass.CreateFeatureBuffer();
            try
            {
                while (row.Read())
                {
                    try
                    {
                        feaBuffer.Shape = Kingo.PluginServiceInterface.Helper.AECommonHelper.GetPolygonFromWkt(row[shapCol].ToString());
                        foreach (var item in dicMap)
                        {
                            if (feaBuffer.Fields.FindField(item.Value) == -1) continue;
                            feaBuffer.set_Value(feaBuffer.Fields.FindField(item.Value), row[item.Key] is DBNull ? "" : row[item.Key]);
                        }
                        object obj = feaCursor.InsertFeature(feaBuffer);
                    }
                    catch (Exception ex)
                    {
                        LogAPI.Debug(ex);
                        continue;
                    }
                }
                feaCursor.Flush();
                row.Close();
            }
            catch (Exception)
            {
                //throw;
            }
            finally
            {
                if (feaCursor != null)
                    Marshal.ReleaseComObject(feaCursor);
                if (feaBuffer != null)
                    Marshal.ReleaseComObject(feaBuffer);
            }
        }
        public IFeatureClass CreateXYEventSource(ITable table, ISpatialReference spatialReference)
        {
            IXYEvent2FieldsProperties xyEvent2FieldsProperties = new XYEvent2FieldsPropertiesClass();
            xyEvent2FieldsProperties.XFieldName = "Longitude";
            xyEvent2FieldsProperties.YFieldName = "Latitude";
            IDataset sourceDataset = (IDataset)table;
            IName sourceName = sourceDataset.FullName;
            IXYEventSourceName xyEventSourceName = new XYEventSourceNameClass();
            xyEventSourceName.EventProperties = xyEvent2FieldsProperties; xyEventSourceName.EventTableName = sourceName; xyEventSourceName.SpatialReference = spatialReference;
            IName name = (IName)xyEventSourceName;
            IXYEventSource xyEventSource = (IXYEventSource)name.Open();
            IFeatureClass featureClass = (IFeatureClass)xyEventSource;
            return featureClass;
        }
    }
}