using DevExpress.Xpf.Grid;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.ExtensionMethod;
using KGIS.Framework.Utils.Utility;
using KGIS.Framework.Views;
using Kingo.Plugin.MapView.Model;
using Kingo.PluginServiceInterface;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
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;
using System.Xml;
using UIShell.OSGi;
namespace Kingo.Plugin.MapView
{
    /// 
    /// UCWorkspace.xaml 的交互逻辑
    /// 
    public partial class UCWorkspace : UserControl, IDockPanel3, IWorkCatalog
    {
        private List WorkspaceSource { get; set; }
        private string Setworkapacepath { get; set; }
        public UCWorkspace()
        {
            DevExpress.Xpf.Core.ThemeManager.SetTheme(this, DevExpress.Xpf.Core.Theme.Office2016White);
            InitializeComponent();
            Title = "工作目录";
            DockWidth = 300;
            DockHeight = 300;
            DefaultArea = DockStyle.DockLeft;
            DockAreas = DockStyle.DockLeft | DockStyle.DockRight;
            ShowCloseButton = false;
            ShowAutoHideButton = true;
            IsDockToPanel = true;
            DockToPanelStyle = DockStyle.DockBottom;
            WorkspaceSource = new List();
        }
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            var watcher = source as FileSystemWatcher;
            if (watcher != null)
            {
                if (e.FullPath.EndsWith(".lock") || e.FullPath.EndsWith("wal") || e.FullPath.EndsWith("shm") || e.FullPath.Contains(".gdb") || e.FullPath.Contains(".ldb"))
                    return;
                this.Dispatcher.Invoke(new Action(delegate
                {
                    LoadWorkspace(watcher.Path);
                }));
            }
        }
        public Guid ID { get; set; }
        public DockStyle DockAreas { get; set; }
        public System.Drawing.Size FloatSize { get; set; }
        public int DockWidth { get; set; }
        public int DockHeight { get; set; }
        public DockStyle DefaultArea { get; set; }
        public bool ShowCloseButton { get; set; }
        public bool ShowAutoHideButton { get; set; }
        public string Title { get; set; }
        public bool IsDockToPanel { get; set; }
        public DockStyle DockToPanelStyle { get; set; }
        public bool IsShowInMap { get; set; }
        public bool IsOpenView { get; set; }
        /// 
        /// 存放工作目录路径
        /// 
        public string SaveWorkSapcePath { get => Setworkapacepath; }
        /// 
        /// 标记当前是否加载工程
        /// 
        public bool IsLoadProject { get; set; }
        public event EventHandler CloseViewHandler;
        public void ClosePanel()
        {
            Platform.Instance.CloseView(this);
        }
        public void ClosePanelInvoke()
        {
            CloseViewHandler?.Invoke(this, null);
        }
        public void ShowPanel()
        {
            Platform.Instance.OpenView(this, false);
        }
        public void LoadWorkspace(string wsPath = null)
        {
            Setworkapacepath = wsPath;
            try
            {
                string MainId = Guid.NewGuid().ToString();
                DirectoryInfo dicInfo = null;
                if (string.IsNullOrWhiteSpace(wsPath))
                {
                    //if (!string.IsNullOrWhiteSpace(WorkspacePath))
                    //{
                    //    if (Directory.Exists(WorkspacePath))
                    //    {
                    //        DirectorySecurity dirSec = new DirectorySecurity(WorkspacePath, AccessControlSections.Access);
                    //        if (!dirSec.AreAuditRulesProtected)
                    //            dicInfo = new DirectoryInfo(WorkspacePath);
                    //        else
                    //            return;
                    //    }
                    //    else
                    //    {
                    //        return;
                    //    }
                    //}
                    //else
                    //{
                    //    return;
                    //}
                }
                else
                {
                    if (Directory.Exists(wsPath))
                    {
                        DirectorySecurity dirSec = new DirectorySecurity(wsPath, AccessControlSections.Access);
                        if (!dirSec.AreAuditRulesProtected)
                            dicInfo = new DirectoryInfo(wsPath);
                        else
                            return;
                    }
                    else
                    {
                        return;
                    }
                }
                WorkspaceSource.Clear();
                if (dicInfo == null) return;
                WorkspaceSource.Add(new WorkspaceInfo()
                {
                    ItemName = dicInfo.Name,
                    ObjectType = "文件夹",
                    SelfPath = dicInfo.FullName,
                    ID = MainId,
                    ParentID = "00"
                });
                List listSub = dicInfo.GetDirectories().ToList().FindAll(q => !q.FullName.EndsWith(".gdb") && !q.FullName.EndsWith("System Volume Information"));
                string verifyDirectory = VerifyXZQDic();
                foreach (DirectoryInfo dir in listSub)
                {
                    if (Directory.Exists(dir.FullName))
                    {
                        if (!string.IsNullOrWhiteSpace(verifyDirectory) && !verifyDirectory.Contains(dir.Name)) continue;
                        DirectorySecurity dirSec = new DirectorySecurity(dir.FullName, AccessControlSections.Access);
                        if (dirSec.AreAuditRulesProtected)
                            continue;
                        string SubId = Guid.NewGuid().ToString();
                        WorkspaceInfo infoSub = new WorkspaceInfo()
                        {
                            ItemName = dir.Name,
                            ObjectType = "文件夹",
                            SelfPath = dir.FullName,
                            ID = SubId,
                            ParentID = MainId
                        };
                        WorkspaceSource.Add(infoSub);
                        GetSubDirs(dir, null, SubId);
                        if (Directory.Exists(dir.FullName))
                        {
                            List listSTFileSub = dir.GetFiles("*.KBG").ToList();//调整为模板仅限 mxt格式
                            foreach (FileInfo fileInfo in listSTFileSub)
                            {
                                WorkspaceInfo fileInfoSub = new WorkspaceInfo()
                                {
                                    ItemName = System.IO.Path.GetFileNameWithoutExtension(fileInfo.FullName),
                                    ObjectType = "文件",
                                    SelfPath = fileInfo.FullName,
                                    ID = Guid.NewGuid().ToString(),
                                    ParentID = SubId
                                };
                                WorkspaceSource.Add(fileInfoSub);
                            }
                        }
                    }
                }
                if (Directory.Exists(dicInfo.FullName))
                {
                    List listSTFileSub = dicInfo.GetFiles("*.KBG").ToList();
                    foreach (FileInfo fileInfo in listSTFileSub)
                    {
                        WorkspaceInfo fileInfoSub = new WorkspaceInfo()
                        {
                            ItemName = System.IO.Path.GetFileNameWithoutExtension(fileInfo.FullName),
                            ObjectType = "文件",
                            SelfPath = fileInfo.FullName,
                            ID = Guid.NewGuid().ToString(),
                            ParentID = MainId
                        };
                        WorkspaceSource.Add(fileInfoSub);
                    }
                }
                gcWorkspace.ItemsSource = null;
                gcWorkspace.ItemsSource = WorkspaceSource;
                SetGridControl();
            }
            catch (Exception ex)
            {
                //LogAPI.Debug(ex);
                //Common.Helper.MessageHelper.ShowError(ex.Message);
            }
        }
        /// 
        /// 验证工作文件夹子级目录是否符合工作目录
        /// 
        /// 
        public string VerifyXZQDic()
        {
            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 strSQL = "select OBJECTID AS ID, XZQ AS CODE,XZQMC AS NAME from XZQ";
                    DataTable dt = rdbHelper.ExecuteDatatable("Dic", strSQL, true);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (var item in TBToList.ToList(dt))
                        {
                            SQXZQs += string.Format("{0}({1}),", item.NAME, item.CODE);
                        }
                        SQXZQs.Trim(',');
                    }
                }
                return SQXZQs;
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
                return "";
            }
            finally
            {
                if (rdbHelper != null)
                    rdbHelper.DisConnect();
            }
        }
        private void GetSubDirs(DirectoryInfo dir, StreamWriter sw, string PID)
        {
            DirectorySecurity dirSec = new DirectorySecurity(dir.FullName, AccessControlSections.Access);
            if (!dirSec.AreAuditRulesProtected)
            {
                List listDirSub = dir.GetDirectories().ToList().FindAll(q => !q.FullName.EndsWith(".gdb") && !q.FullName.EndsWith("System Volume Information")); ;
                foreach (DirectoryInfo dirSub in listDirSub)
                {
                    if (Directory.Exists(dirSub.FullName))
                    {
                        DirectorySecurity dirSec2 = new DirectorySecurity(dirSub.FullName, AccessControlSections.Access);
                        if (dirSec2.AreAuditRulesProtected)
                            continue;
                        if (dirSub.FullName.Contains(","))
                            continue;
                        string SubId = Guid.NewGuid().ToString();
                        WorkspaceInfo infoSub = new WorkspaceInfo()
                        {
                            ItemName = dirSub.Name,
                            ObjectType = "文件夹",
                            SelfPath = dirSub.FullName,
                            ID = SubId,
                            ParentID = PID
                        };
                        WorkspaceSource.Add(infoSub);
                        if (Directory.Exists(dirSub.FullName) && dirSub.GetFiles("*.KBG").ToList().Count <= 0)
                            GetSubDirs(dirSub, sw, SubId);//与*.KBG同级目录的文件夹不在进行展示
                        if (Directory.Exists(dirSub.FullName))
                        {
                            List listFileSub = dirSub.GetFiles("*.KBG").ToList();
                            if (listFileSub != null && listFileSub.Count > 0)
                            {
                                infoSub.ObjectType = "文件";
                            }
                            //foreach (FileInfo fileInfo in listFileSub)
                            //{
                            //    if (fileInfo.FullName.Contains(","))
                            //        continue;
                            //    WorkspaceInfo fileInfoSub = new WorkspaceInfo()
                            //    {
                            //        ItemName = System.IO.Path.GetFileNameWithoutExtension(fileInfo.FullName),
                            //        ObjectType = "文件",
                            //        SelfPath = fileInfo.FullName,
                            //        ID = Guid.NewGuid().ToString(),
                            //        ParentID = SubId
                            //    };
                            //    WorkspaceSource.Add(fileInfoSub);
                            //}
                        }
                    }
                }
            }
        }
        private void SetGridControl()
        {
            try
            {
                if (gcWorkspace != null)
                {
                    gcWorkspace.Dispatcher.Invoke(new Action(() =>
                    {
                        gcWorkspace.Columns[0].Header = "";
                        gcWorkspace.Columns[1].Header = "文件夹/文件";
                        gcWorkspace.Columns[2].Header = "路径";
                        gcWorkspace.Columns[1].Visible = false;
                        gcWorkspace.Columns[2].Visible = false;
                        gcWorkspace.Columns[0].ReadOnly = true;
                        gcWorkspace.Columns[0].AllowEditing = DevExpress.Utils.DefaultBoolean.False;
                        gcWorkspace.Columns[0].Width = 1600;
                        //gcWorkspace.RefreshData();
                        if ((gcWorkspace.View as TreeListView).Nodes.Count > 0)
                        {
                            (gcWorkspace.View as TreeListView).Nodes[0].IsExpanded = true;
                        }
                    }));
                    ////tlvTemplate.Nodes[1].IsExpanded = true;用户自定义
                    //tlvWorkspace.Dispatcher.Invoke(new Action(() =>
                    //{
                    //    if (tlvWorkspace.Nodes.Count > 0)
                    //        tlvWorkspace.Nodes[0].IsExpanded = true;//系统
                    //    tlvWorkspace.ExpandAllNodes();
                    //    //SetNodeImage();
                    //}));
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
            }
        }
        private void gcWorkspace_AutoGeneratedColumns(object sender, RoutedEventArgs e)
        {
            SetGridControl();
        }
        /// 
        /// 双击打开工程
        /// 
        /// 
        /// 
        private void tlvWorkspace_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            foreach (var item in (sender as TreeListView).SelectedRows)
            {
                if (string.IsNullOrWhiteSpace((item as WorkspaceInfo).SelfPath)) return;
                string TempPath = System.IO.Path.GetFileName((item as WorkspaceInfo).SelfPath) + ".KBG";
                string str = System.IO.Path.Combine((item as WorkspaceInfo).SelfPath, TempPath);
                if (File.Exists(str))
                {
                    #region 判断当前要打开的工程与系统类型是否匹配
                    var projectInfo = ProjectInfo.OpenProject(str);
                    if (!projectInfo.ProjType.ToTrim().StartsWith($"{Platform.Instance.SystemType.ToTrim().Substring(0, 4)}"))
                    {
                        KGIS.Framework.Utils.Helper.MessageHelper.ShowError("当前工程类型与当前软件类型不匹配,将会导致一些功能不可正常使用,请重新正确打开工程类型!");
                        return;
                    }
                    #endregion
                    MapsManager.Instance.MapService.LoadProject(str);
                    ProjectInfo ProInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
                    if (ProInfo != null)
                    {
                        if (ProInfo.ProjType == EnumProjType.BHTBTQ && Platform.Instance.SystemType != SystemTypeEnum.BGFWCG
                            || ProInfo.ProjType != EnumProjType.BHTBTQ && Platform.Instance.SystemType == SystemTypeEnum.BGFWCG)
                        {
                            ClearData();
                            LogAPI.Debug("工程类型与当前软件类型不匹配,将会导致功能不可用,请正确打开工程类型!");
                            KGIS.Framework.Utils.Helper.MessageHelper.ShowError("当前工程类型与当前软件类型不匹配,将会导致一些功能不可正常使用,请重新正确打开工程类型!");
                            return;
                        }
                        if (ProInfo.ProjType == EnumProjType.BHTBTQ && Platform.Instance.SystemType == SystemTypeEnum.BGFWCG)
                        {
                            //添加作业区标注
                            PluginServiceInterface.Helper.MarkLabelLayerForZYQ.MarkLayer();
                            IUcZYQMagrHelper ucZYQMagrHelper = BundleRuntime.Instance.GetFirstOrDefaultService();
                            if (ucZYQMagrHelper != null)
                            {
                                ucZYQMagrHelper.UpdataData();
                            }
                            IUcMulitMapControlHelper ucMulitMapControlHelper = BundleRuntime.Instance.GetFirstOrDefaultService();
                            if (ucMulitMapControlHelper != null)
                            {
                                ucMulitMapControlHelper.ClearData();
                                ucMulitMapControlHelper.SetLayer();
                                ucMulitMapControlHelper.MarkLabelLayer();
                            }
                        }
                    }
                }
            }
        }
        private void ClearData()
        {
            MapsManager.Instance.MapService.getAxMapControl().ClearLayers();
            if (Platform.Instance.SystemType == SystemTypeEnum.BGFWCG)
            {
                IUcZYQMagrHelper ucZYQMagrHelper = BundleRuntime.Instance.GetFirstOrDefaultService();
                if (ucZYQMagrHelper != null)
                {
                    ucZYQMagrHelper.ClearData();
                }
                IUcMulitMapControlHelper ucMulitMapControlHelper = BundleRuntime.Instance.GetFirstOrDefaultService();
                if (ucMulitMapControlHelper != null)
                {
                    ucMulitMapControlHelper.ClearData();
                }
            }
        }
        public void Open()
        {
            this.ShowPanel();
            IsOpenView = true;
            IsLoadProject = true;
        }
        FileSystemWatcher watcher = null;
        public void SetWorksapce(string pDirectoryPath)
        {
            try
            {
                LoadWorkspace(pDirectoryPath);
                #region 记录最近打开的工作目录
                SysConfigsOprator configOp = new SysConfigsOprator();
                #region 验证:依据配置记录中的地址遍历去验证发现如果工作目录不在的就把记录删掉
                string strRecentOpenProjectRecordXmlPath = SysAppPath.GetRecentOpenProjectRecordConfigPath();
                if (File.Exists(strRecentOpenProjectRecordXmlPath) == true)
                {
                    List iInvalidPathXMLList = configOp.GetExcludeInvalidRecentOpenProjectRecordXmlMsg(strRecentOpenProjectRecordXmlPath);
                    if (iInvalidPathXMLList != null && iInvalidPathXMLList.Count() > 0)
                    {
                        bool bDelTemp = false;
                        for (int ut = 0; ut < iInvalidPathXMLList.Count(); ut++)
                        {
                            if (Directory.Exists(iInvalidPathXMLList[ut])) continue;
                            bDelTemp = configOp.DeleteProjectFileOpenTime(strRecentOpenProjectRecordXmlPath, iInvalidPathXMLList[ut]);
                            if (bDelTemp == false)
                                LogAPI.Debug("依据配置记录中的地址遍历去验证发现如果KBG文件不在的就把记录删掉 时失败,请排查 ; ");
                        }
                    }
                }
                #endregion
                XmlDocument doc = new XmlDocument();
                if (File.Exists(strRecentOpenProjectRecordXmlPath) == false)
                {
                    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                    doc.AppendChild(dec);
                    XmlElement projectmessage = doc.CreateElement("projectmessage");
                    doc.AppendChild(projectmessage);
                    doc.Save(strRecentOpenProjectRecordXmlPath);
                }
                //工作目录记录不存在,可以加
                if (!configOp.JudgeRecentOpenProjectRecordXmlMsgIsExist(strRecentOpenProjectRecordXmlPath, pDirectoryPath))
                {
                    doc.Load(strRecentOpenProjectRecordXmlPath);
                    XmlElement projectrecord = doc.DocumentElement;
                    XmlElement project = doc.CreateElement("project");
                    project.SetAttribute("ProjectPath", pDirectoryPath);
                    projectrecord.AppendChild(project);
                    project.SetAttribute("LastOpenTime", DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + " " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second);
                    projectrecord.AppendChild(project);
                    //加上工作目录唯一标识码---2020-6-12
                    string sProjectUniqueID_Now = System.Guid.NewGuid().ToString("N");
                    sProjectUniqueID_Now += DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
                    project.SetAttribute("ProjectUniqueID", sProjectUniqueID_Now);
                    projectrecord.AppendChild(project);
                    //ProjType
                    project.SetAttribute("ProjType", Platform.Instance.SystemType.ToTrim());
                    projectrecord.AppendChild(project);
                    doc.Save(strRecentOpenProjectRecordXmlPath);
                }
                else
                {
                    //更新打开记录的时间
                    configOp.UpdateProjectFileOpenTime(strRecentOpenProjectRecordXmlPath, pDirectoryPath);
                }
                #endregion
                #region 获取当前工作目录中上次打开的工程
                string workCatalogPathTemp = pDirectoryPath + "\\RecentWorkCatalogRecord.xml";
                if (!string.IsNullOrEmpty(workCatalogPathTemp) && File.Exists(workCatalogPathTemp))
                {
                    string projPath = GetProjPath(workCatalogPathTemp);
                    if (File.Exists(projPath) && IsLoadProject)
                        MapsManager.Instance.MapService.LoadProject(projPath);
                }
                #endregion
                #region 监测工作目录下的文件
                if (watcher == null)
                {
                    watcher = new FileSystemWatcher();
                    watcher.Path = pDirectoryPath;
                    watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                    watcher.IncludeSubdirectories = true;
                    watcher.Deleted += new FileSystemEventHandler(OnChanged);
                    watcher.Created += new FileSystemEventHandler(OnChanged);
                    watcher.EnableRaisingEvents = true;
                }
                #endregion
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
            }
        }
        private string GetProjPath(string sXmlPath)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement orderElement = null;
            XmlNodeList orderChildr = null;
            string PathProject = string.Empty;
            try
            {
                if (File.Exists(sXmlPath) == false) return PathProject;
                doc.Load(sXmlPath);
                orderElement = doc.DocumentElement;// 获取根节点
                if (orderElement == null) return PathProject;
                if (orderElement.ChildNodes == null || orderElement.ChildNodes.Count <= 0) return PathProject;
                orderChildr = orderElement.ChildNodes;
                if (orderChildr == null || orderChildr.Count <= 0) return PathProject;
                Dictionary workPaths = new Dictionary();
                foreach (XmlNode item in orderChildr)
                {
                    if (!workPaths.ContainsKey(item.Attributes["ProjectPath"].Value))
                    {
                        if (item.Attributes["ProjType"].Value == Platform.Instance.SystemType.ToTrim())
                            workPaths.Add(item.Attributes["ProjectPath"].Value, Convert.ToDateTime(item.Attributes["LastOpenTime"].Value));
                    }
                }
                Dictionary dicTemp = workPaths.OrderByDescending(o => o.Value).ToDictionary(o => o.Key, p => p.Value);
                return dicTemp.FirstOrDefault().Key;
            }
            catch (Exception ex)
            {
                LogAPI.Debug("GetProjPath异常:" + ex.Message);
                LogAPI.Debug("GetProjPath异常:" + ex.StackTrace);
                return PathProject;
            }
            finally
            {
                if (doc != null) doc = null;
                if (orderElement != null) orderElement = null;
                if (orderChildr != null && orderChildr.Count > 0) orderChildr = null;
                if (string.IsNullOrWhiteSpace(sXmlPath) == false) sXmlPath = "";
            }
        }
    }
    public class ObjectTypeImageSelector : TreeListNodeImageSelector
    {
        public override ImageSource Select(DevExpress.Xpf.Grid.TreeList.TreeListRowData rowData)
        {
            BitmapImage image = null;
            if (rowData != null)
            {
                if (rowData.Node != null)
                {
                    WorkspaceInfo info = rowData.Node.Content as WorkspaceInfo;
                    if (info != null)
                    {
                        if (info.ObjectType == "文件夹")
                        {
                            image = FilePathToBitmapImage(System.IO.Path.Combine(SysAppPath.GetCurrentAppPath(), "Images", "menu", "Windows文件夹.png"));
                        }
                        else
                        {
                            image = FilePathToBitmapImage(System.IO.Path.Combine(SysAppPath.GetCurrentAppPath(), "Images", "menu", "MxdFile.png"));
                        }
                    }
                }
            }
            return image;
        }
        private BitmapImage FilePathToBitmapImage(string filePath)
        {
            BitmapImage bmp = null;
            try
            {
                byte[] data = File.ReadAllBytes(filePath);
                bmp = new BitmapImage();
                using (MemoryStream ms = new MemoryStream(data.ToArray()))
                {
                    bmp.BeginInit();
                    bmp.CreateOptions = BitmapCreateOptions.None;
                    bmp.CacheOption = BitmapCacheOption.OnLoad;
                    bmp.UriSource = null;
                    bmp.StreamSource = ms;
                    bmp.EndInit();
                }
                return bmp;
            }
            catch
            {
                return null;
            }
        }
    }
}