using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geometry;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Helper;
using KGIS.Framework.Utils.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Kingo.Plugin.BGSetting.View.ViewSystemSetting
{
    /// 
    /// ViewAuthorizaManage.xaml 的交互逻辑
    /// 
    public partial class ViewAuthorizaManage : UserControl
    {
        private AxMapControl mapControl = null;
        KGIS.Framework.Core.Services.RunIDService2 SQInfo = null;
        public static IGeometryFactory3 GeometryFactory3 { get; set; }
        public ViewAuthorizaManage()
        {
            InitializeComponent();
            InitData();
        }
        public void InitData()
        {
            SQInfo = KGIS.Framework.Core.Services.RunIDService2.Instance;
            txtXZQ.Text = GetXZQDic(SQInfo.Codes).ToString();
            txtJZSJ.Text = SQInfo.ExpirationTime.ToString();
        }
        private void DispalySQ_Click(object sender, RoutedEventArgs e)
        {
            string SQstring = SQInfo.Area;
            if (!string.IsNullOrWhiteSpace(SQstring))
            {
                string[] rings = SQstring.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                string coord = string.Empty;
                if (rings.Length > 1)
                {
                    coord = "MULTIPOLYGON(";
                    foreach (var ring in rings)
                    {
                        string Temp_Coordinate = string.Empty;
                        string[] points = ring.TrimEnd(';').Split(';');
                        string strRing = "((";
                        foreach (var item in points)
                        {
                            strRing += item.Replace(',', ' ') + ",";
                        }
                        strRing = strRing.TrimEnd(',');
                        strRing += ")),";
                        coord += strRing;
                    }
                    coord = coord.TrimEnd(',');
                    coord += ")";
                }
                else
                {
                    coord = string.Format("POLYGON((");
                    string[] points = SQstring.TrimEnd(';').Split(';');
                    foreach (var item in points)
                    {
                        coord += item.Replace(',', ' ') + ",";
                    }
                    coord = coord.TrimEnd(',');
                    coord += "))";
                }
                IGeometry geo = GetPolygonFromWkt(coord);
                ISpatialReferenceFactory NewSpatialReference = new SpatialReferenceEnvironmentClass();
                geo.SpatialReference = NewSpatialReference.CreateGeographicCoordinateSystem(4490);
                geo.Project(MapsManager.Instance.MapService.getAxMapControl().SpatialReference);
                ITopologicalOperator topo = geo as ITopologicalOperator;
                geo = topo.Buffer(2000);
                DrawPolygonElement(geo, "授权范围");
                AreaEnvOfeat(geo);
            }
            //AreaEnvOfeat(ConvertWKTToIGeometry(SQstring));
        }
        private IGeometry GetPolygonFromWkt(string pointsStr)
        {
            try
            {
                //OSGeo.OGR.Ogr.RegisterAll();
                IGeometry geometry = new PolygonClass();
                OSGeo.OGR.Geometry rstGeometry = OSGeo.OGR.Geometry.CreateFromWkt(pointsStr);
                byte[] geometryBytes = new byte[rstGeometry.WkbSize()];
                rstGeometry.ExportToWkb(geometryBytes);
                IGeometryFactory3 factory = new GeometryEnvironment() as IGeometryFactory3;
                int bytesLen = geometryBytes.Length;
                factory.CreateGeometryFromWkbVariant(geometryBytes, out geometry, out bytesLen);
                IPolygon polygon = geometry as IPolygon;
                polygon.Close();
                ITopologicalOperator pBoundaryTop = polygon as ITopologicalOperator;
                pBoundaryTop.Simplify();
                return geometry;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public string GetXZQDic(List Codes)
        {
            IRDBHelper rdbHelper = null;
            string SQXZQs = string.Empty;
            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 strPrWhere = "1=2";
                    string strWhere = string.Empty;
                    if (Codes != null)
                    {
                        foreach (var item in Codes)
                        {
                            strWhere += string.Format(" or XZQ = '{0}'", item.Replace("00", ""));
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(strWhere))
                        strWhere = strPrWhere + strWhere;
                    else
                        strWhere = "1=1";
                    string strSQL = "select OBJECTID AS ID, XZQ AS CODE,XZQMC AS NAME from XZQ Where " + strWhere + "";
                    DataTable dt = rdbHelper.ExecuteDatatable("Dic", strSQL, true);
                    if (dt != null)
                    {
                        foreach (var item in TBToList.ToList(dt))
                        {
                            SQXZQs += string.Format("{0}({1}),", item.NAME, item.CODE);
                        }
                        SQXZQs.Trim(',');
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
            }
            finally
            {
                if (rdbHelper != null)
                    rdbHelper.DisConnect();
            }
            return SQXZQs.Trim(',');
        }
        public void AreaEnvOfeat(IGeometry geometry)
        {
            try
            {
                mapControl = MapsManager.Instance.MapService.getAxMapControl() as AxMapControl;
                EnvelopeClass pEnvelope = new EnvelopeClass();
                IEnvelope pEnvOfFeat = geometry.Envelope;
                //投影到当前地图坐标系定位缩放到当前要素
                pEnvOfFeat.Project(mapControl.SpatialReference);
                IUnitConverter pUnitConverter = new UnitConverterClass();
                double dScale = pUnitConverter.ConvertUnits(50, esriUnits.esriMeters, mapControl.MapUnits);
                pEnvelope.PutCoords(pEnvOfFeat.XMin - dScale, pEnvOfFeat.YMin - dScale, pEnvOfFeat.XMax + dScale, pEnvOfFeat.YMax + dScale);
                mapControl.ActiveView.Extent = pEnvelope;
                mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, mapControl.ActiveView.Extent);
            }
            catch (Exception ex)
            {
                MessageHelper.ShowError("操作异常!异常信息:" + ex.Message);
                LogAPI.Debug(ex);
            }
        }
        private void DrawPolygonElement(IGeometry pGeo, string pName)
        {
            ISimpleFillSymbol pSimpleFillSymbol = new SimpleFillSymbolClass();
            pSimpleFillSymbol.Style = esriSimpleFillStyle.esriSFSDiagonalCross;
            //设置线宽和线的颜色
            ISimpleLineSymbol pLineSymbol = new SimpleLineSymbolClass
            {
                Color = Symbol.GetRGBColor(255, 0, 0),
                Width = 2
            };
            pSimpleFillSymbol.Outline = pLineSymbol;
            PolygonElementClass element = new PolygonElementClass
            {
                Name = pName,
                Symbol = pSimpleFillSymbol,
                Geometry = pGeo
            };
            IGraphicsLayer grapLayer = AddSubGraphicsLayer("TempSQFWGrapLayer");
            (grapLayer as IGraphicsContainer).AddElement(element, 0);
            MapsManager.Instance.MapService.getAxMapControl().ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, MapsManager.Instance.MapService.getAxMapControl().ActiveView.Extent);
        }
        public IGraphicsLayer AddSubGraphicsLayer(string subgraphicsLayername)
        {
            ICompositeGraphicsLayer pCompositeGLayer = MapsManager.Instance.MapService.getAxMapControl().Map.BasicGraphicsLayer as ICompositeGraphicsLayer;
            IGraphicsLayer pGLayer = null;
            try
            {
                //查找是否已存在,如果不存在,跳转到catch内容.
                //如果查到不到,说明集合中并没有指定名称的graphicslayer
                pGLayer = pCompositeGLayer.FindLayer(subgraphicsLayername);
            }
            catch
            {
                //若不存在,则添加一个指定名称的GraphicsLayer
                pGLayer = pCompositeGLayer.AddLayer(subgraphicsLayername, null);
            }
            return pGLayer;
        }
    }
    public enum EnumSymbolType
    {
        SimpleMarkerSymbol,
        SimpleLineSymbol,
        SimpleFillSymbol,
        FormattedTextSymbol
    }
    public class Symbol
    {
        public static ISymbol CreateDefaultSymbol(EnumSymbolType pSymbolType)
        {
            ISymbol symbol = null;
            IRgbColor color = new RgbColorClass();
            color = GetRGBColor(0xff, 0, 0);
            switch (pSymbolType)
            {
                case EnumSymbolType.SimpleMarkerSymbol:
                    return symbol;
                case EnumSymbolType.SimpleLineSymbol:
                    {
                        ISimpleLineSymbol symbol2 = new SimpleLineSymbolClass();
                        symbol2.Color = color;
                        symbol2.Width = 1.5;
                        return (ISymbol)symbol2;
                    }
                case EnumSymbolType.SimpleFillSymbol:
                    {
                        ISimpleFillSymbol symbol3 = new SimpleFillSymbolClass();
                        symbol3.Outline.Color = color;
                        symbol3.Color = color;
                        symbol3.Style = esriSimpleFillStyle.esriSFSDiagonalCross;
                        return (ISymbol)symbol3;
                    }
            }
            return symbol;
        }
        public static IRgbColor GetRGBColor(int pRed, int pGreen, int pBlue)
        {
            try
            {
                IRgbColor color = new RgbColorClass();
                color.Red = pRed;
                color.Green = pGreen;
                color.Blue = pBlue;
                return color;
            }
            catch
            {
                return null;
            }
        }
    }
}