using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using KGIS.Framework.AE;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Helper;
using Kingo.PluginServiceInterface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Xml;
namespace Kingo.Plugin.DataDictionary.Helper
{
    public class DicHelper
    {
        /// 
        /// 获取行政区字典数据
        /// 
        /// 行政级别(1:县、2:镇、3:村、4:海岛)
        public static BasicDataModel[] GetXZQDic(int pLevel)
        {
            List result = new List();
            if (pLevel == 1)
            {
                IRDBHelper helper = null;
                DataTable dtData = null;
                try
                {
                    string strConn = SysConfigsOprator.GetDBConnectionByName("MDBOledbConnection");
                    strConn = string.Format(strConn, SysAppPath.GetDataBaseRoot() + "System.mdb");
                    if (string.IsNullOrWhiteSpace(strConn))
                    {
                        result = null;
                    }
                    helper = RDBFactory.CreateDbHelper(strConn, DatabaseType.MSAccess);
                    string strSQL = string.Format("SELECT * FROM {0} where XZQ ='{1}'", "XZQ", ((MapsManager.Instance.CurrProjectInfo as ProjectInfo) as ProjectInfo).CODE);
                    dtData = helper.ExecuteDatatable("dtData", strSQL, true);
                    if (dtData != null)
                    {
                        foreach (DataRow row in dtData.Rows)
                        {
                            BasicDataModel node = new BasicDataModel();
                            node.Name = row["XZQMC"] is DBNull ? "" : row["XZQMC"].ToString();
                            node.Code = row["XZQ"].ToString();
                            node.DisplayName = string.Format("({0}){1}", node.Code, node.Name);
                            node.Attribures = new Dictionary();
                            foreach (DataColumn col in dtData.Columns)
                            {
                                node.Attribures.Add(col.ColumnName, row[col]);
                            }
                            result.Add(node);
                        }
                    }
                    return result.ToArray();
                }
                catch (Exception ex)
                {
                    LogAPI.Debug(ex);
                }
                finally
                {
                    if (dtData != null)
                    {
                        dtData.Clear();
                        dtData.Dispose();
                    }
                    if (helper != null)
                    {
                        helper.DisConnect();
                    }
                }
            }
            else if (pLevel == 2)
            {
                ICursor pCur = null;
                try
                {
                    IFeatureLayer fcLayer = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("行政区");
                    if (fcLayer == null)
                    {
                        MessageHelper.Show("未获取到行政区图层数据!");
                        return result.ToArray();
                    }
                    //获取基础mdb中的tbmj之和
                    IQueryDef pQDef = ((fcLayer.FeatureClass as FeatureClass).Workspace as IFeatureWorkspace).CreateQueryDef();
                    pQDef.Tables = (fcLayer.FeatureClass as FeatureClass).Name;
                    pQDef.SubFields = "*";
                    pCur = pQDef.Evaluate();
                    IRow pRow = null;
                    while ((pRow = pCur.NextRow()) != null)
                    {
                        BasicDataModel node = new BasicDataModel();
                        node.Name = pRow.get_Value(pRow.Fields.FindField("XZQMC")) is DBNull ? "" : pRow.get_Value(pRow.Fields.FindField("XZQMC")).ToString();
                        node.Code = pRow.get_Value(pRow.Fields.FindField("XZQDM")).ToString();
                        node.DisplayName = string.Format("({0}){1}", node.Code, node.Name);
                        node.Attribures = new Dictionary();
                        for (int i = 0; i < pRow.Fields.FieldCount; i++)
                        {
                            IField field = pRow.Fields.get_Field(i);
                            if (field.Name.ToUpper() != "SHAPE")
                            {
                                node.Attribures.Add(field.Name, pRow.get_Value(pRow.Fields.FindField(field.Name)));
                            }
                        }
                        result.Add(node);
                    }
                    return result.ToArray();
                }
                catch (Exception ex)
                {
                    LogAPI.Debug(ex);
                }
                finally
                {
                    if (pCur != null)
                    {
                        Marshal.ReleaseComObject(pCur);
                    }
                }
            }
            else if (pLevel == 3)
            {
                ICursor pCur = null;
                try
                {
                    IFeatureLayer fcLayer = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("村级调查区");
                    //获取基础mdb中的tbmj之和
                    IQueryDef pQDef = ((fcLayer.FeatureClass as FeatureClass).Workspace as IFeatureWorkspace).CreateQueryDef();
                    pQDef.Tables = (fcLayer.FeatureClass as FeatureClass).Name;
                    pQDef.SubFields = "distinct ZLDWDM,ZLDWMC";
                    pCur = pQDef.Evaluate();
                    IRow pRow = null;
                    while ((pRow = pCur.NextRow()) != null)
                    {
                        BasicDataModel node = new BasicDataModel();
                        node.Name = pRow.get_Value(pRow.Fields.FindField("ZLDWMC")) is DBNull ? "" : pRow.get_Value(pRow.Fields.FindField("ZLDWMC")).ToString();
                        node.Code = pRow.get_Value(pRow.Fields.FindField("ZLDWDM")).ToString().Substring(0, 12);
                        node.DisplayName = string.Format("({0}){1}", node.Code, node.Name);
                        node.Attribures = new Dictionary();
                        result.Add(node);
                    }
                    return result.ToArray();
                }
                catch (Exception ex)
                {
                    LogAPI.Debug(ex);
                }
                finally
                {
                    if (pCur != null)
                    {
                        Marshal.ReleaseComObject(pCur);
                    }
                }
            }
            else if (pLevel == 4)
            {
                ICursor pCur = null;
                try
                {
                    IFeatureLayer fcLayer = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("村级调查区");
                    //获取基础mdb中的tbmj之和
                    IQueryDef pQDef = ((fcLayer.FeatureClass as FeatureClass).Workspace as IFeatureWorkspace).CreateQueryDef();
                    pQDef.Tables = (fcLayer.FeatureClass as FeatureClass).Name;
                    pQDef.SubFields = "distinct ZLDWDM,HDMC";
                    pCur = pQDef.Evaluate();
                    IRow pRow = null;
                    while ((pRow = pCur.NextRow()) != null)
                    {
                        BasicDataModel node = new BasicDataModel();
                        node.Name = pRow.get_Value(pRow.Fields.FindField("HDMC")) is DBNull ? "" : pRow.get_Value(pRow.Fields.FindField("HDMC")).ToString();
                        node.Code = pRow.get_Value(pRow.Fields.FindField("ZLDWDM")).ToString().Substring(0, 12);
                        node.DisplayName = string.Format("({0}){1}", node.Code, node.Name);
                        node.Attribures = new Dictionary();
                        result.Add(node);
                    }
                    return result.ToArray();
                }
                catch (Exception ex)
                {
                    LogAPI.Debug(ex);
                }
                finally
                {
                    if (pCur != null)
                    {
                        Marshal.ReleaseComObject(pCur);
                    }
                }
            }
            return null;
        }
        /// 
        /// 获取工程下的字典
        /// 
        /// 
        public static List GetAllDic()
        {
            DataTable dt = null;
            List result = new List();
            IRDBHelper rdbHelper = null;
            try
            {
                string dbPath = (MapsManager.Instance.CurrProjectInfo as ProjectInfo).GetDicDataPath();
                if (!string.IsNullOrWhiteSpace(dbPath))
                {
                    rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
                    string strSQL = "select * from Sys_DicDetail";
                    dt = rdbHelper.ExecuteDatatable("Dic", strSQL, true);
                    if (dt != null)
                    {
                        //Bug-12137 霍岩 2018-11-14 使用CODE字段按顺序排序
                        result = KGIS.Framework.Utils.Utility.TBToList.ToList(dt).OrderBy(x => x.CODE).ToList();
                        result.ForEach(x => x.DisplayName = x.CODE + "-" + x.NAME);
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
            }
            finally
            {
                if (rdbHelper != null)
                {
                    rdbHelper.DisConnect();
                }
                if (dt != null)
                {
                    dt.Clear();
                    dt.Dispose();
                }
            }
            return result;
        }
    }
}