using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using KGIS.Framework.AE.ExtensionMethod;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using Kingo.Plugin.MapView.Views;
using Kingo.PluginServiceInterface;
using System;
using System.Linq;
using System.Collections.Generic;
using KGIS.Framework.Views;
using ESRI.ArcGIS.Geodatabase;
using UIShell.OSGi;
using Kingo.PluginServiceInterface.Model;
using Kingo.Plugin.MapView.Common;
namespace Kingo.Plugin.MapView.Commands
{
    //[PathAttribute("Kingo.Plugin.MapView.Commands.CmdOpenAttrTable")]
    public class CmdTBBG : BaseMapMenuCommand
    {
        IEngineEditor m_pEditor;
        FrmFeatureAttribute frmFeatureAttr = null;
        IFeatureLayer featureLayer = null;
        IAttrTableHelper uCAttribute_Form = null;
        private IProofManager ProofMgr = null;
        private ISystemCfg SystemCfg = null;
        IDockPanel2 _Panel = null;
        /// 
        /// 坐落单位字典
        /// 
        private List ZLDMdataDic = null;
        public override void OnClick()
        {
            //Views.FeatureAttribute.UCAttributeEdit aa = new Views.FeatureAttribute.UCAttributeEdit();
            IDockViewService _DockViewService = null;
            IElementInfo _ProofImg = null;
            //IElementInfo _ProofInfo = null;
            IElementInfo _FeatureInfo = null;
            try
            {
                if (ProofMgr == null)
                    ProofMgr = BundleRuntime.Instance.GetFirstOrDefaultService();
                if (SystemCfg == null)
                    SystemCfg = BundleRuntime.Instance.GetFirstOrDefaultService();
                SystemCfg.Load();
                List lstElement = UIShell.OSGi.BundleRuntime.Instance.GetService();
                _ProofImg = lstElement.FirstOrDefault(f => f.Title == "外业照片");
                //_ProofInfo = lstElement.FirstOrDefault(f => f.Title == "外业信息");
                _FeatureInfo = lstElement.FirstOrDefault(f => f.Title == "要素属性");
                //_FeatureInfo = aa;
                _DockViewService = BundleRuntime.Instance.GetFirstOrDefaultService();
                if (_DockViewService == null)
                    return;
                _DockViewService.IsShowSaveButton = true;
                _DockViewService.Orientation = EnumOrientation.Vertical;
                _Panel = _DockViewService.InitView();
                if (_ProofImg != null)
                    _DockViewService.AddElement(_ProofImg);
                //if (_ProofInfo != null)
                //    _DockViewService.AddElement(_ProofInfo);
                if (_FeatureInfo != null)
                    _DockViewService.AddElement(_FeatureInfo);
                _Panel.Title = "图斑变更";
                _Panel.DefaultArea = DockStyle.DockRight;
                _Panel.DockWidth = 470;
                _Panel.ShowCloseButton = true;
                if (MapsManager.Instance.MapService != null)
                {
                    MapsManager.Instance.MapService.ProjectClosed -= MapService_ProjectClosed;
                    MapsManager.Instance.MapService.ProjectClosed += MapService_ProjectClosed;
                }
                object pLayer = m_hookHelper.GetCustomProperty();//获取对象的创建者的Application对象
                IFeatureLayer pTocFeatureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName("DLTBBG");
                featureLayer = pTocFeatureLayer;
                string PanelName = "图斑变更";
                uCAttribute_Form = BundleRuntime.Instance.GetFirstOrDefaultService();
                _DockViewService.Callback = uCAttribute_Form.SelectRowPrevOrNextRow;
                List attributeViewParameters = new List();
                //创建自定义控件信息
                AttributeViewParameter attributeViewParameter = new AttributeViewParameter()
                {
                    LableInfo = "加载监测图斑:",
                    Type = "RadioCombox",
                    Data = featureLayer,
                    Filterriteria = " AND (SFJCTB = 'Y' OR SFJCTB = '1') "
                };
                attributeViewParameters.Add(attributeViewParameter);
                attributeViewParameter = new AttributeViewParameter()
                {
                    LableInfo = "过滤条件:",
                    Type = "CheckCombox",
                    Data = GetZLDWDMList(),
                    Filterriteria = " AND (SUBSTRING(ZLDWDM,1,9) in ({0}))"
                };
                attributeViewParameters.Add(attributeViewParameter);
                uCAttribute_Form.InitView(PanelName, m_hookHelper, attributeViewParameters);
                if (uCAttribute_Form.CurrentView != null)
                {
                    uCAttribute_Form.CurrentView.LoadData(featureLayer, null);
                    uCAttribute_Form.CurrentView.CustomCallBack += (o) =>
                    {
                        string strwhere = "1=1 ";
                        IFeature pFeature = null;
                        if (o.Type == "gridView1_DoubleClick" || o.Type == "gridView1_RowChangeClick")
                        {
                            if (o.Data != null)
                            {
                                pFeature = featureLayer.FeatureClass.GetFeature(Convert.ToInt32(o.Data));
                            }
                        }
                        else
                        {
                            foreach (var item in attributeViewParameters)
                            {
                                if (item.Value == null) continue;
                                if (string.IsNullOrEmpty(item.Value.ToString())) continue;
                                strwhere += $"{string.Format(item.Filterriteria, item.Value)}";
                            }
                            if (featureLayer != null)
                            {
                                uCAttribute_Form.CurrentView.LoadData(featureLayer, strwhere);
                                IFeatureCursor pFeatureCursor = featureLayer.Search(new QueryFilterClass() { WhereClause = strwhere }, true);
                                pFeature = pFeatureCursor.NextFeature();
                                System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
                            }
                        }
                        if (pFeature != null)
                        {
                            List _ProofList = GetProofData(pFeature);
                            _ProofImg.BindData(null);
                            //_ProofInfo.BindData(null);
                            if (_ProofList != null && _ProofList.Count > 0)
                            {
                                EnvironmentVariables.Instance.cameraPoint.AddCameraPoint(_ProofList[0].ImgList);
                                _ProofImg.BindData(_ProofList[0].ImgList);
                                //_ProofInfo.BindData(_ProofList);
                            }
                            _FeatureInfo.BindData(pFeature);
                        }
                    };
                    if (featureLayer != null)
                    {
                        IFeatureCursor pFeatureCursor = featureLayer.Search(new QueryFilterClass() { WhereClause = "1=1" }, true);
                        IFeature pFeature = pFeatureCursor.NextFeature();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
                        if (pFeature != null)
                        {
                            List _ProofList = GetProofData(pFeature);
                            _ProofImg.BindData(null);
                            //_ProofInfo.BindData(null);
                            if (_ProofList != null && _ProofList.Count > 0)
                            {
                                EnvironmentVariables.Instance.cameraPoint.AddCameraPoint(_ProofList[0].ImgList);
                                _ProofImg.BindData(_ProofList[0].ImgList);
                                //_ProofInfo.BindData(_ProofList);
                            }
                            _FeatureInfo.BindData(pFeature);
                        }
                    }
                    //初始化属性联动配置
                    //_FeatureInfo.BindData(null);
                    Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "ShowDetailView", Content = _Panel });
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("初始化 打开图斑变更属性表 命令时异常,异常信息如下:");
                LogAPI.Debug(ex);
                LogAPI.Debug("初始化 打开图斑变更属性表 命令时异常信息结束");
            }
        }
        private void MapService_ProjectClosed(object sender, EventArgs e)
        {
            if (_Panel != null)
            {
                _Panel.ClosePanel();
                _Panel = null;
            }
        }
        private List GetProofData(IFeature pFeature)
        {
            //List result = new List();
            //if (ProofMgr != null && SystemCfg != null)
            //{
            //    if (SystemCfg.JZCGCfg == null)
            //        SystemCfg.Load();
            //    if (SystemCfg.JZCGCfg != null && SystemCfg.JZCGCfg.LayerInfo != null && SystemCfg.JZCGCfg.LayerInfo.Count != 0)
            //    {
            //        string name = (pFeature.Class as IDataset).Name;
            //        List layerInfoList = SystemCfg.JZCGCfg.LayerInfo.FindAll(x => x.IsCheck == true && x.LayerName == name || x.LayerAliasName == name);
            //        if (layerInfoList != null && layerInfoList.Count != 0)
            //        {
            //            foreach (var wylayer in layerInfoList)
            //            {
            //                if (wylayer.RelevantModel == "属性")
            //                {
            //                    if (!string.IsNullOrWhiteSpace(wylayer.AttributeField))
            //                    {
            //                        int fieldIndex = pFeature.Fields.FindField(wylayer.AttributeField);
            //                        if (fieldIndex < 0)
            //                            continue;
            //                        string jcbh = pFeature.Value[fieldIndex].ToString();
            //                        if (!string.IsNullOrWhiteSpace(jcbh))
            //                        {
            //                            //根据属性字段关联照片
            //                            result = ProofMgr.GetProofInfoList(jcbh);//("528")
            //                            //ucImgXZZP.InitData(ProofInfo, false);
            //                            //EnvironmentVariables.Instance.cameraPoint.AddCameraPoint(ProofInfo);
            //                        }
            //                    }
            //                }
            //                else if (wylayer.RelevantModel == "图形")
            //                {
            //                    ////根据图形范围关联照片
            //                    if (!string.IsNullOrWhiteSpace(wylayer.AreaScale))
            //                    {
            //                        result = ProofMgr.GetProofInfoList(pFeature.ShapeCopy, wylayer.AreaScale);
            //                        //ucImgXZZP.InitData(ProofInfo, false);
            //                        //EnvironmentVariables.Instance.cameraPoint.AddCameraPoint(ProofInfo);
            //                    }
            //                }
            //            }
            //        }
            //        else
            //        {
            //            //ucImgXZZP.InitData(null, false);
            //        }
            //    }
            //}
            //return result;
            List result = new List();
            int fieldIndex = pFeature.Fields.FindField("TBYBH");
            if (fieldIndex > 0)
            {
                result = ProofMgr.GetProofInfoList(pFeature.Value[fieldIndex].ToString());
            }
            return result;
        }
        /// 
        /// 获取行政区代码及名称
        /// 
        /// 
        /// 
        private Dictionary GetZLDWDMList()
        {
            try
            {
                ZLDMdataDic = Platform.Instance.DicHelper.GetNoGroupDic(DicTypeEnum.QSDM);
                Dictionary keyValuePairs = new Dictionary();
                if (ZLDMdataDic != null)
                {
                    foreach (var item in ZLDMdataDic.FindAll(x => x.CODE.Length == 9))
                    {
                        keyValuePairs[item.CODE] = item.CODE + "_" + item.NAME;
                    }
                }
                return keyValuePairs;
            }
            catch (Exception ex)
            {
                LogAPI.Debug("获取坐落代码失败:" + ex.Message);
                return null;
            }
        }
        private void FrmAttr_CloseViewHandler(object sender, EventArgs e)
        {
            frmFeatureAttr.CloseViewHandler -= FrmAttr_CloseViewHandler;
            frmFeatureAttr = null;
        }
        private void UCAttribute_Form_CloseViewHandler(object sender, EventArgs e)
        {
            try
            {
                ViewAttrTable view = sender as ViewAttrTable;
                //if (listPanel.FirstOrDefault(f => f.ID == view.ID) != null)
                //    listPanel.Remove(view);
            }
            catch (Exception ex)
            {
                LogAPI.Debug("关闭属性列表异常,异常信息如下:");
                LogAPI.Debug(ex);
                LogAPI.Debug("关闭属性列表异常信息结束");
            }
        }
        /// 
        /// 对象识别符.Hook
        /// 
        /// 
        public override void OnCreate(object Hook)
        {
            try
            {
                if (m_hookHelper == null)
                {
                    m_hookHelper = new HookHelperClass();
                }
                m_hookHelper.Hook = Hook;
                m_pEditor = new EngineEditorClass();
            }
            catch (Exception ex)
            {
                LogAPI.Debug("初始化 打开属性表 命令时异常,异常信息如下:");
                LogAPI.Debug(ex);
                LogAPI.Debug("初始化 打开属性表 命令时异常信息结束");
            }
        }
        public override bool Enabled => JudgeIsHaveTargetPath();
        private bool JudgeIsHaveTargetPath()
        {
            try
            {
                ProjectInfo prj = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
                if (prj == null)
                {
                    return false;
                }
                return !string.IsNullOrWhiteSpace(prj.BGDatabase) && m_pEditor.EditState == esriEngineEditState.esriEngineStateEditing;
            }
            catch (Exception ex)
            {
                LogAPI.Debug("判定 检测数据加载 按钮是否有效时失败,异常原因: " + ex + " ; ");
                return false;
            }
        }
    }
}