using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geometry;
using KGIS.Framework.Core.Services;
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 Kingo.PluginServiceInterface.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using UserControl = System.Windows.Controls.UserControl;
namespace Kingo.Plugin.SystemSetting.View.ViewSystemSetting
{
    /// 
    /// ViewAuthoriza.xaml 的交互逻辑
    /// 
    public partial class ViewAuthoriza : UserControl
    {
        private AxMapControl mapControl = null;
        KGIS.Framework.Core.Services.RunIDService2 SQInfo = null;
        public static IGeometryFactory3 GeometryFactory3 { get; set; }
        public ViewAuthoriza()
        {
            InitializeComponent();
            InitData();
        }
        public void InitData()
        {
            SQInfo = RunIDService2.Instance;
            txtXZQ.Text = GetXZQDic(SQInfo.Codes).ToString();
            txtJZSJ.Text = SQInfo.ExpirationTime.ToString();
            Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "UpdatedTime" });
        }
        private void DispalySQ_Click(object sender, RoutedEventArgs e)
        {
            IGeometry geo = null;
            try
            {
                geo = AuthorizationVerification.DrawAuthorizationRange(MapsManager.Instance.MapService.getAxMapControl().SpatialReference);
                if (geo != null && !geo.IsEmpty)
                {
                    if (mapControl == null || mapControl.ActiveView == null || mapControl.ActiveView.GraphicsContainer == null)
                        mapControl = MapsManager.Instance.MapService.getAxMapControl() as AxMapControl;
                    mapControl.ActiveView.GraphicsContainer.DeleteAllElements();
                    mapControl.Refresh();
                    //DrawPolygonElement(geo, "授权范围");
                    DrawBaseGraph(geo, 150, 150, 150);
                    AreaEnvOfeat(geo);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(mapControl.ActiveView.GraphicsContainer);
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("执行显示授权异常:" + ex.Message);
                LogAPI.Debug("执行显示授权异常:" + ex.StackTrace);
            }
        }
        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)
                        {
                            if (item.IndexOf("00") == 4)
                                strWhere += string.Format(" or XZQ Like '{0}%'", item.Replace("00", ""));
                            else if (item.IndexOf("0000") == 2)
                                strWhere += string.Format(" or XZQ Like '{0}%'", item.Replace("0000", ""));
                            else
                                strWhere += string.Format(" or XZQ Like '{0}%'", item);
                        }
                    }
                    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();
            }
            if (!string.IsNullOrWhiteSpace(SQXZQs) && SQXZQs.Split(',').Length >= 2800)
                return "全国";
            else
                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
            {
                Style = esriSimpleFillStyle.esriSFSNull
            };
            //设置线宽和线的颜色
            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;
        }
        private void DispalyGH_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                KGIS.PlatformPlugin.Views.License.LicenseView lic = new KGIS.PlatformPlugin.Views.License.LicenseView(null, "KGIS_SJJK", "400", "4x");
                DialogResult dialog = lic.ShowDialog();
                if (dialog == DialogResult.Yes || dialog == DialogResult.OK)
                {
                    InitData();
                    IGeometry geo = null;
                    geo = AuthorizationVerification.DrawAuthorizationRange(MapsManager.Instance.MapService.getAxMapControl().SpatialReference);
                    if (geo != null && !geo.IsEmpty)
                    {
                        if (mapControl == null || mapControl.ActiveView == null || mapControl.ActiveView.GraphicsContainer == null)
                            mapControl = MapsManager.Instance.MapService.getAxMapControl() as AxMapControl;
                        mapControl.ActiveView.GraphicsContainer.DeleteAllElements();
                        mapControl.Refresh();
                        //DrawPolygonElement(geo, "授权范围");
                        DrawBaseGraph(geo, 150, 150, 150);
                        AreaEnvOfeat(geo);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(mapControl.ActiveView.GraphicsContainer);
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("执行更换授权异常:" + ex.Message);
                LogAPI.Debug("执行更换授权异常:" + ex.StackTrace);
            }
        }
        public IElement DrawBaseGraph(IGeometry geoDraw, int R = 255, int G = 0, int B = 0)
        {
            try
            {
                IElement result = null;
                IGraphicsContainer iGraphicsContainer = null;
                IElement CameraPointElm = null;
                IGraphicsContainer graphicsContainer = mapControl.ActiveView.GraphicsContainer;
                graphicsContainer.Reset(); 
                while ((CameraPointElm = graphicsContainer.Next()) != null)
                {
                    if ((CameraPointElm as IElementProperties).Name == "BaseElement")
                        break;
                }
                if (CameraPointElm == null)
                {
                    CameraPointElm = new GroupElementClass();
                    (CameraPointElm as IElementProperties).Name = "BaseElement";
                    mapControl.ActiveView.GraphicsContainer.AddElement(CameraPointElm, 2);
                }
                    (CameraPointElm as IGroupElement).ClearElements();
                if (geoDraw == null) return null;
                //替换Env改动---无用
                //IMapControl2 axMapDraw = Env.Instance.KMap.HookHelper.Hook as IMapControl2;
                // 获取IRGBColor接口
                IRgbColor color = new RgbColor();
                // 设置颜色属性
                color.Red = R;
                color.Green = G;
                color.Blue = B;
                switch (geoDraw.GeometryType)
                {
                    case ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint:
                        result = new MarkerElementClass();
                        IMarkerSymbol symbol = new SimpleMarkerSymbolClass();
                        symbol.Color = color;
                        symbol.Size = 10;
                        (result as IMarkerElement).Symbol = symbol;
                        result.Geometry = geoDraw;
                        break;
                    case ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon:
                        result = new KGIS.Framework.Maps.PolygonElement() { Opacity = 100 };
                        // 获取ILine符号接口
                        ILineSymbol lineSymbol = new SimpleLineSymbol();
                        // 设置线符号属
                        lineSymbol.Width = 2;
                        ISimpleFillSymbol simpleFillSymbol = new SimpleFillSymbolClass();
                        simpleFillSymbol.Color = color;
                        IRgbColor colorLine = new RgbColor();
                        colorLine.Red = 0;
                        colorLine.Green = 0;
                        colorLine.Blue = 0;
                        lineSymbol.Color = colorLine;
                        // 设置填充符号属性
                        simpleFillSymbol.Outline = lineSymbol;
                        simpleFillSymbol.Style = ESRI.ArcGIS.Display.esriSimpleFillStyle.esriSFSSolid;//esriSimpleFillStyle.esriSFSSolid;
                        (result as IFillShapeElement).Symbol = simpleFillSymbol;
                        result.Geometry = geoDraw;
                        break;
                    case ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline:
                        result = new LineElementClass();
                        // 获取ILine符号接口
                        ILineSymbol outline = new SimpleLineSymbol();
                        // 设置线符号属
                        outline.Width = 3;
                        outline.Color = color;
                        (outline as SimpleLineSymbol).Style = ESRI.ArcGIS.Display.esriSimpleLineStyle.esriSLSSolid;
                        (result as ILineElement).Symbol = outline;
                        result.Geometry = geoDraw;
                        break;
                    default:
                        break;
                }
                (CameraPointElm as IGroupElement).AddElement(result);
                iGraphicsContainer?.AddElement(result, 0);
                mapControl.ActiveView.Refresh();
                return result;
            }
            catch (Exception ex)
            {
                LogAPI.Debug("执行DrawGraph方法时异常:" + ex);
                return null;
            }
        }
    }
    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;
            }
        }
    }
}