using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using KGIS.Framework.AE;
using KGIS.Framework.Commands;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.ExtensionMethod;
using KGIS.Framework.Utils.Helper;
using Kingo.Framework.LayerStyleConvert.Common;
using Kingo.Framework.LayerStyleConvert.XSDClass;
using Kingo.PluginServiceInterface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UIShell.OSGi;
namespace Kingo.Plugin.BGSetting.Commands
{
    /// 
    /// 系统设置-功能点
    /// 
    public class CmdCreateBGDB : BaseMenuCommand
    {
        /// 
        /// 编辑器
        /// 
        private EngineEditorClass pEditor = null;
        private IHookHelper hookHelper = null;
        private IDataCatalogService _DataCatalog = null;
        private SystemConfig2 SystemCfg = null;
        public override void OnClick()
        {
            IWorkspaceAPI wsAPI = null;
            IWorkspaceAPI wsAPI_YCL = null;
            try
            {
                if (_DataCatalog == null)
                    _DataCatalog = BundleRuntime.Instance.GetFirstOrDefaultService();
                if (_DataCatalog == null)
                    return;
                if (!(MapsManager.Instance.MapService.GetProjectInfo() is ProjectInfo ProInfo))
                    return;
                if (!string.IsNullOrWhiteSpace(ProInfo.BGDatabase))
                    return;
                if (pEditor == null)
                    pEditor = new EngineEditorClass();
                if (pEditor.EditState != esriEngineEditState.esriEngineStateNotEditing)
                {
                    MessageHelper.ShowTips("请先关闭编辑!");
                    return;
                }
                if (hookHelper == null)
                    hookHelper = new HookHelperClass { Hook = MapsManager.Instance.MapService.Hook };
                PluginServiceInterface.CommonHelper.DirectoryCopy(SysAppPath.GetCurrentAppPath() + string.Format("工作空间\\模板\\新建变更工程\\{0}\\BGDB.gdb", (int)Math.Floor(Math.Round(10 / ProInfo.XYResolution))), ProInfo.ProjDir);
                ProInfo.BGDatabase = Path.Combine(ProInfo.ProjDir, "BGDB.gdb");
                ProInfo.Save();
                wsAPI = new WorkspaceAPI(ProInfo.BGDatabase, KGIS.Framework.AE.Enum.WorkspaceTypeEnum.GDBFile, true);
                GeoDBAPI.SetGeoDatasetSpatialReference(wsAPI.CurrentWorkspace, hookHelper.FocusMap.SpatialReference, ProInfo.XYResolution);
                object GroupLayerInfo = null;
                ILayer groupLayer = MapsManager.Instance.MapService.GetGroupLayer("XZQTZ");
                if (groupLayer == null)
                {
                    groupLayer = new GroupLayer() { Name = "行政区调整" };
                    ILayerGeneralProperties layerGeneralProperties = groupLayer as ILayerGeneralProperties;
                    layerGeneralProperties.LayerDescription = "XZQTZ";
                    GroupLayerInfo = _DataCatalog.AddLayer(groupLayer);
                }
                if (GroupLayerInfo == null)
                    GroupLayerInfo = _DataCatalog.GetNodeByLayer(groupLayer);
                if (wsAPI.ExistFeatureClass("YSDLTB"))//新增原始地类图斑
                {
                    IFeatureClassAPI YSDLTBFcAPI = wsAPI.OpenFeatureClass("YSDLTB");
                    IFeatureLayer YSDLTBLayer = new FeatureLayer() { Name = "原始地类图斑", FeatureClass = YSDLTBFcAPI.FeatureClass };
                    _DataCatalog.AddLayer(YSDLTBLayer, GroupLayerInfo);
                }
                if (wsAPI.ExistFeatureClass("XJJXTQTB"))//新增图斑
                {
                    IFeatureClassAPI XZQHRQJCTBFcAPI = wsAPI.OpenFeatureClass("XJJXTQTB");
                    IFeatureLayer XZQHRQJCTBLayer = new FeatureLayer() { Name = "县级界线提取图斑", FeatureClass = XZQHRQJCTBFcAPI.FeatureClass };
                    _DataCatalog.AddLayer(XZQHRQJCTBLayer, GroupLayerInfo);
                }
                IFeatureClassAPI DLTBHRGCSJFcAPI = wsAPI.OpenFeatureClass("DLTBHRGC");
                IFeatureLayer DLTBHRGCSJLayer = new FeatureLayer() { Name = "地类图斑划入过程", FeatureClass = DLTBHRGCSJFcAPI.FeatureClass };
                _DataCatalog.AddLayer(DLTBHRGCSJLayer, GroupLayerInfo);
                GroupLayerInfo = null;
                groupLayer = MapsManager.Instance.MapService.GetGroupLayer("BGSJ");
                if (groupLayer == null)
                {
                    groupLayer = new GroupLayer() { Name = "变更数据" };
                    ILayerGeneralProperties layerGeneralProperties = groupLayer as ILayerGeneralProperties;
                    layerGeneralProperties.LayerDescription = "BGSJ";
                    GroupLayerInfo = _DataCatalog.AddLayer(groupLayer);
                }
                if (GroupLayerInfo == null)
                    GroupLayerInfo = _DataCatalog.GetNodeByLayer(groupLayer);
                ISystemCfg cfg2 = BundleRuntime.Instance.GetFirstOrDefaultService();
                SystemCfg = cfg2.Load();
                if (SystemCfg.BGLayerLoadCfg == null)
                    SystemCfg.BGLayerLoadCfg = new List();
                IFeatureClassAPI XJKZJXFcAPI = wsAPI.OpenFeatureClass("XJKZJX");
                IFeatureLayer tempLayer = new FeatureLayer() { Name = "县级控制界线", FeatureClass = XJKZJXFcAPI.FeatureClass };
                SetILayerSymbol(tempLayer, "XJKZJX");
                _DataCatalog.AddLayer(tempLayer, GroupLayerInfo);
                IFeatureClassAPI ZLTBGXFcAPI = wsAPI.OpenFeatureClass2("ZLTBGX");
                if (ZLTBGXFcAPI != null && ZLTBGXFcAPI.FeatureClass != null)
                {
                    tempLayer = new FeatureLayer() { Name = "增量图斑更新", FeatureClass = ZLTBGXFcAPI.FeatureClass };
                    SetILayerSymbol(tempLayer, "ZLTBGX");
                    _DataCatalog.AddLayer(tempLayer, GroupLayerInfo);
                }
                IFeatureClassAPI bgtbFcAPI = wsAPI.OpenFeatureClass("DLTBBG");
                AddFieldSXWHForDBLayer.JudgeTypeAddField(ProInfo, bgtbFcAPI.FeatureClass);
                tempLayer = new FeatureLayer() { Name = "变更范围", FeatureClass = bgtbFcAPI.FeatureClass };
                SetILayerSymbol(tempLayer, "DLTBBG");
                LayerCfg layCfg = _DataCatalog.AddLayer(tempLayer, GroupLayerInfo) as LayerCfg;
                LayerCfg layerCfg = SystemCfg.BGLayerLoadCfg.FirstOrDefault(x => x.FcName == "DLTBBG");
                layCfg.FieldEditCfg = layerCfg?.FieldEditCfg.ToTrim();
                GroupLayerInfo = null;
                groupLayer = MapsManager.Instance.MapService.GetGroupLayer("JCTBSJ");
                if (groupLayer == null)
                {
                    groupLayer = new GroupLayer() { Name = "监测数据" };
                    ILayerGeneralProperties layerGeneralProperties = groupLayer as ILayerGeneralProperties;
                    layerGeneralProperties.LayerDescription = "JCTBSJ";
                    GroupLayerInfo = _DataCatalog.AddLayer(groupLayer);
                }
                if (GroupLayerInfo == null)
                    GroupLayerInfo = _DataCatalog.GetNodeByLayer(groupLayer);
                IFeatureClassAPI jctbFcAPI = wsAPI.OpenFeatureClass("JCTB");
                IFeatureLayer JcTBLayer = new FeatureLayer() { Name = "国家监测图斑", FeatureClass = jctbFcAPI.FeatureClass };
                IFeatureLayerDefinition pFLDefinition = JcTBLayer as IFeatureLayerDefinition;
                if (pFLDefinition != null)
                {
                    pFLDefinition.DefinitionExpression = "SJLY='GJJC'";
                }
                _DataCatalog.AddLayer(JcTBLayer, GroupLayerInfo);
                IFeatureLayer ZZBGTBLayer = new FeatureLayer() { Name = "自主变更图斑", FeatureClass = jctbFcAPI.FeatureClass };
                pFLDefinition = ZZBGTBLayer as IFeatureLayerDefinition;
                if (pFLDefinition != null)
                {
                    pFLDefinition.DefinitionExpression = "SJLY='ZZBG'";
                }
                _DataCatalog.AddLayer(ZZBGTBLayer, GroupLayerInfo);
                _DataCatalog.UpdateTree();
                Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "SaveProject" });
            }
            catch (Exception ex)
            {
                MessageHelper.ShowTips("系统设置初始化页面失败:" + ex.Message);
                LogAPI.Debug(ex);
            }
            finally
            {
                if (wsAPI != null)
                {
                    wsAPI.CloseWorkspace();
                    wsAPI = null;
                }
                if (wsAPI_YCL != null)
                {
                    wsAPI_YCL.CloseWorkspace();
                    wsAPI_YCL = null;
                }
            }
        }
        private void SetILayerSymbol(IFeatureLayer tempLayer, string LayerAliseName)
        {
            IFeatureRenderer result = null;
            LayerCfg layerCfg = SystemCfg.BGLayerLoadCfg.FirstOrDefault(x => x.FcName == LayerAliseName);//默认配置默认不为NULL
            if (layerCfg != null && !string.IsNullOrWhiteSpace(layerCfg.Symbol))
            {
                AdvancedDrawingInfo ad = AdvancedDrawingInfo.FromJson(layerCfg.Symbol);
                if (ad != null)
                {
                    if (ad.DrawingInfo.Renderer is Framework.LayerStyleConvert.XSDClass.SimpleRenderer)
                    {
                        Symbol symbol1 = (ad.DrawingInfo.Renderer as Framework.LayerStyleConvert.XSDClass.SimpleRenderer).Symbol;
                        ISimpleRenderer simpleRander2 = SymbolConvert.Instance().GetSimpleRenderer(symbol1, SymbolTypeEnum.Fill);
                        result = simpleRander2 as IFeatureRenderer;
                    }
                    else if (ad.DrawingInfo.Renderer is Framework.LayerStyleConvert.XSDClass.UniqueValueRenderer)
                    {
                        Renderer rander = ad.DrawingInfo.Renderer;
                        IUniqueValueRenderer uniqueValueRander = SymbolConvert.Instance().GetUniqueValueRenderer(rander, SymbolTypeEnum.Fill);
                        result = uniqueValueRander as IFeatureRenderer;
                    }
                }
                #region 样式
                if (result != null)
                    (tempLayer as IGeoFeatureLayer).Renderer = result;
                #endregion
                #region 显示比例设置
                tempLayer.MinimumScale = layerCfg.MinScale;
                tempLayer.MaximumScale = layerCfg.MaxScale;
                #endregion
                #region 图层透明度
                if (tempLayer is ILayerEffects mLayerEffects)//透明度
                    mLayerEffects.Transparency = (short)layerCfg.Transparency;
                #endregion
                #region 是否显示
                tempLayer.Visible = layerCfg.Visible;//是否显示
                #endregion
                #region 是否可选择
                tempLayer.Selectable = layerCfg.Selectable;
                #endregion
                #region 过滤条件
                IFeatureLayerDefinition pFLDefinition = tempLayer as IFeatureLayerDefinition;
                if (pFLDefinition != null)
                {
                    pFLDefinition.DefinitionExpression = layerCfg.DefinitionExpression;
                }
                #endregion
            }
        }
        private IFeatureRenderer GetSymbol(string pStrSymbol)
        {
            IFeatureRenderer result = null;
            if (!string.IsNullOrWhiteSpace(pStrSymbol))
            {
                AdvancedDrawingInfo ad = AdvancedDrawingInfo.FromJson(pStrSymbol);
                if (ad != null)
                {
                    if (ad.DrawingInfo.Renderer is Framework.LayerStyleConvert.XSDClass.SimpleRenderer)
                    {
                        Symbol symbol1 = (ad.DrawingInfo.Renderer as Framework.LayerStyleConvert.XSDClass.SimpleRenderer).Symbol;
                        ISimpleRenderer simpleRander2 = SymbolConvert.Instance().GetSimpleRenderer(symbol1, SymbolTypeEnum.Fill);
                        result = simpleRander2 as IFeatureRenderer;
                    }
                    else if (ad.DrawingInfo.Renderer is Framework.LayerStyleConvert.XSDClass.UniqueValueRenderer)
                    {
                        Renderer rander = ad.DrawingInfo.Renderer;
                        IUniqueValueRenderer uniqueValueRander = SymbolConvert.Instance().GetUniqueValueRenderer(rander, SymbolTypeEnum.Fill);
                        result = uniqueValueRander as IFeatureRenderer;
                    }
                }
            }
            return result;
        }
        public override void OnCreate(object Hook)
        {
            if (hookHelper == null)
                hookHelper = new HookHelperClass();
            hookHelper.Hook = Hook;
        }
        public override bool Enabled
        {
            get
            {
                //验证是否打开工程
                if (!(MapsManager.Instance.MapService.GetProjectInfo() is ProjectInfo ProInfo))
                    return false;
                else
                    return string.IsNullOrWhiteSpace(ProInfo.BGDatabase);
            }
        }
    }
}