using ESRI.ArcGIS.Controls;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.ExtensionMethod;
using KGIS.Framework.Utils.Helper;
using KGIS.Framework.Views;
using Kingo.PluginServiceInterface;
using KUI.Windows;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Xml;
using UIShell.OSGi;
namespace Kingo.Plugin.MapView.Views
{
    /// 
    /// 最近工程记录的交互逻辑
    /// 
    public partial class RecentOpenProject : UserControl
    {
        private double dGridWidthNow;
        private bool IsFirstOpen = false;
        private double dGridWidthInitial = 0;
        private double dReduceScale = 0;
        public event EventHandler Close;
        private IViewManager m_ViewManager;
        public List ProjectInfoList { get; set; }
        /// 
        /// 自定义i的工程信息
        /// 
        public class ProjectInfo
        {
            public string Name { get; set; }
            public string Path { get; set; }
            public string RecentOpenDate { get; set; }
            public BitmapImage FileImage { get; set; }
        }
        public DataTable dtShow = new DataTable("最近打开工程信息");
        public RecentOpenProject()
        {
            IsFirstOpen = true;
            dReduceScale = 1;
            InitializeComponent();
            InitData();
        }
        private void RefreshGridData(bool isRegainDTShowInfo = false)
        {
            try
            {
                if (isRegainDTShowInfo == true)
                {
                    GetDTShowInfo();
                }
                ProjectInfoList = new List();
                ProjectInfo PI = new ProjectInfo();
                if (dtShow != null && dtShow.Rows.Count > 0)
                {
                    for (int i = 0; i < dtShow.Rows.Count; i++)
                    {
                        PI = new ProjectInfo();
                        PI.Name = GetFileShowMsg(dtShow.Rows[i]["projname"].ToString(), dtShow.Rows[i]["projpath"].ToString());
                        PI.Path = dtShow.Rows[i]["projpath"].ToString();
                        PI.RecentOpenDate = dtShow.Rows[i]["projrecentopendate"].ToString();
                        PI.FileImage = GetFileBitmapImage(2);
                        ProjectInfoList.Add(PI);
                    }
                }
                string prjType = ".KBG";
                switch (Platform.Instance.SystemType)
                {
                    case SystemTypeEnum.NDBGJK:
                        prjType = ".KBG";
                        break;
                    case SystemTypeEnum.TBBG:
                        prjType = ".KAP";
                        break;
                    default:
                        break;
                }
                List ProInfoList = ProjectInfoList.Where(x => x.Path.Contains(prjType)).ToList();
                dgRecentOpenProject.ItemsSource = ProInfoList;
            }
            catch (Exception ex)
            {
                LogAPI.Debug("获取Grid数据时失败,异常原因: " + ex + " ; ");
                return;
            }
        }
        /// 
        /// 获取显示的图片类型(0未知 1文件夹 2文件)
        /// 
        /// 获取显示的图片类型(0未知 1文件夹 2文件)
        /// 
        private BitmapImage GetFileBitmapImage(int iImgType)
        {
            try
            {
                string sAppPathNowTemp = SysAppPath.GetCurrentAppPath() + "Plugins\\KGIS.Plugin.MapView\\Resources\\Tool";
                if (string.IsNullOrWhiteSpace(sAppPathNowTemp) == true)
                {
                    return null;
                }
                else
                {
                    string sFolderImagePath = sAppPathNowTemp + "\\folderimg.png";
                    string sFileImagePath = sAppPathNowTemp + "\\fileimg.png";
                    if (File.Exists(sFolderImagePath) == false || File.Exists(sFileImagePath) == false)
                    {
                        return null;
                    }
                    else
                    {
                        if (iImgType == 1)
                        {
                            BitmapImage bitmap = new BitmapImage(new Uri(sFolderImagePath));
                            return bitmap;
                        }
                        else
                        {
                            BitmapImage bitmap = new BitmapImage(new Uri(sFileImagePath));
                            return bitmap;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("获取显示的图片类型(iImgType= " + iImgType + ")时失败,异常原因: " + ex + " ; ");
                return null;
            }
        }
        private string GetFileShowMsg(string sFileName, string sPath)
        {
            string sMark = "";
            string _Path = "";
            try
            {
                if (string.IsNullOrWhiteSpace(sPath) == true)
                {
                    if (string.IsNullOrWhiteSpace(sFileName) == true)
                    {
                        return "";
                    }
                    else
                    {
                        sMark = GetRealShowMessageByReduceScale(sFileName);
                        return sMark;
                    }
                }
                else
                {
                    //_Path = GetFileDirectoryName(sPath);//因为考虑涉及到有删除的情况,所以这里就不验证
                    _Path = sPath;
                    if (string.IsNullOrWhiteSpace(sFileName) == true)
                    {
                        sMark = GetRealShowMessageByReduceScale(_Path);
                        return sMark;
                    }
                    else
                    {
                        sMark = GetRealShowMessageByReduceScale(sFileName);
                        sMark += "\r";
                        sMark += GetRealShowMessageByReduceScale(_Path);
                        return sMark;
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("获取文件展示用内容时失败,异常原因: " + ex + " ; ");
                return "";
            }
            finally
            {
                if (string.IsNullOrWhiteSpace(sMark) == false)
                {
                    sMark = "";
                }
                if (string.IsNullOrWhiteSpace(_Path) == false)
                {
                    _Path = "";
                }
            }
        }
        private string GetRealShowMessageByReduceScale(string sOriginalContent)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(sOriginalContent) == true)
                {
                    return "";
                }
                if (dReduceScale <= 0)
                {
                    return "";
                }
                if (dReduceScale > 1)
                {
                    dReduceScale = 1;
                }
                int iLength = sOriginalContent.Length;
                double dTemp = iLength * dReduceScale;
                int iNeedLength = GetNeedLength(dTemp * 1.5);
                if (iNeedLength <= 0)
                {
                    iNeedLength = iLength;
                }
                if (iNeedLength >= iLength)
                {
                    return sOriginalContent;
                }
                else
                {
                    string sMark = sOriginalContent.Substring(0, iNeedLength) + "...";
                    return sMark;
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("按照比例获取显示内容时失败,异常原因: " + ex + " ; ");
                return "";
            }
        }
        private int GetNeedLength(double dTemp)
        {
            try
            {
                return (int)dTemp;//取整数部分
            }
            catch (Exception ex)
            {
                LogAPI.Debug("转化Double数(" + dTemp + ") 时失败,异常原因:" + ex + " ; ");
                return 0;
            }
        }
        private void InitData()
        {
            dtShow.Columns.Add("projname", typeof(string));
            dtShow.Columns.Add("projpath", typeof(string));
            dtShow.Columns.Add("projrecentopendate", typeof(string));
            RefreshGridData(true);
        }
        private void GetDTShowInfo()
        {
            if (dtShow != null && dtShow.Rows.Count > 0)
            {
                dtShow.Rows.Clear();
            }
            try
            {
                #region 获取最近打开信息
                string sSysSetShowCount = "";
                string[,] RecentOpenProjectRecord_List = null;
                SysConfigsOprator configOp = new SysConfigsOprator();
                RecentOpenProjectRecord_List = configOp.GetRecentOpenProjectRecordList();
                if (RecentOpenProjectRecord_List != null && RecentOpenProjectRecord_List.Length > 0)
                {
                    int iSysSetShowCount = 0;
                    int iCountTemp = RecentOpenProjectRecord_List.Length / 3;
                    sSysSetShowCount = SysConfigsOprator.GetAppsetingValueByKey("RecentOpenProjectRecordShowCount");
                    int iSysSetShowCount_Temp = ExtendMethd.GetIntByObject(sSysSetShowCount) == 0 ? iCountTemp : Convert.ToInt32(sSysSetShowCount);
                    if (iCountTemp <= iSysSetShowCount_Temp)
                    {
                        iSysSetShowCount = iCountTemp;
                    }
                    else
                    {
                        iSysSetShowCount = iSysSetShowCount_Temp;
                    }
                    for (int y = 0; y < iSysSetShowCount; y++)
                    {
                        dtShow.Rows.Add(new object[] { RecentOpenProjectRecord_List[y, 0], RecentOpenProjectRecord_List[y, 1], RecentOpenProjectRecord_List[y, 2] });
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                LogAPI.Debug("获取最近打开的展示用信息时失败,异常原因: " + ex + " ; ");
                return;
            }
        }
        void Row_MouseEnter(object sender, MouseEventArgs e)
        {
            //DataGridRow row = (DataGridRow)sender;
            //row.ToolTip = GetPathByIndex(row.GetIndex());配置较差电脑会导致黑块 暂时移除提示
        }
        private void DgRecentOpenProject_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.MouseEnter += Row_MouseEnter;
        }
        /// 
        /// 打开工程操作
        /// 
        /// 
        /// 
        private void DgRecentOpenProject_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            string sProjectPath = "";
            string strRecentOpenProjectRecordXmlPath = "";
            SysConfigsOprator configOp = new SysConfigsOprator();
            try
            {
                EngineEditorClass engineEditorClass = new EngineEditorClass();
                if (engineEditorClass.EditState != esriEngineEditState.esriEngineStateNotEditing)
                {
                    MessageHelper.ShowTips("当前工程正处于编辑状态,打开工程之前请先结束编辑!");
                    this.Close?.Invoke(null, null);
                    return;
                }
                ProjectInfo prjSelectedNow = dgRecentOpenProject.SelectedItem as ProjectInfo;
                if (prjSelectedNow == null)
                {
                    return;
                }
                sProjectPath = prjSelectedNow.Path;
                if (File.Exists(sProjectPath) == false)
                {
                    if (MessageHelper.ShowYesNoAndTips(string.Format("未能找到此文件,是否确定要删除此记录?记录删除后不可恢复,请谨慎操作!")) == System.Windows.Forms.DialogResult.Yes)
                    {
                        //删除xml记录
                        strRecentOpenProjectRecordXmlPath = KGIS.Framework.Utils.SysAppPath.GetRecentOpenProjectRecordConfigPath();
                        if (File.Exists(strRecentOpenProjectRecordXmlPath) == false)
                        {
                            MessageHelper.ShowError("未能找到 最近打开工程记录信息");
                            return;
                        }
                        else
                        {
                            bool bProjectOpenRecordDelResult = configOp.DeleteProjectFileOpenTime(strRecentOpenProjectRecordXmlPath, sProjectPath);
                            RefreshGridData(true);
                            return;
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    this.ShowLoading("正在打开工程……", 0, 0);
                    strRecentOpenProjectRecordXmlPath = SysAppPath.GetRecentOpenProjectRecordConfigPath();
                    Platform.Instance.Progress.SetWorkPath(Path.GetDirectoryName(sProjectPath));
                    //切换前关闭所有的未关闭的窗体
                    m_ViewManager = Platform.Instance.ViewManager;
                    m_ViewManager.CloseAllDocument();
                    m_ViewManager.CloseAllPanel();
                    KGIS.Framework.Maps.MapsManager.Instance.MapService.LoadProject(sProjectPath);//打开工程
                    //加载工作目录
                    LoadWorkCatalog(sProjectPath, strRecentOpenProjectRecordXmlPath);
                    RefreshGridData(true);
                    this.Close?.Invoke(null, null);
                    this.CloseLoading();
                    return;
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("在 点击打开最近工程 时失败,原因:" + ex + " ; ");
                this.CloseLoading();
                MessageHelper.ShowError("工程打开 失败");
                return;
            }
        }
        /// 
        /// 加载工作目录
        /// 
        /// 
        /// 
        private void LoadWorkCatalog(string sProjectPath, string XMLPath)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement orderElement = null;
            XmlNodeList orderChildr = null;
            IWorkCatalog _workCatalog = null;
            try
            {
                #region 判断是否存在此工程打开记录
                if (string.IsNullOrWhiteSpace(sProjectPath) == true || string.IsNullOrWhiteSpace(XMLPath) == true) return;
                if (File.Exists(XMLPath) == false) return;
                doc.Load(XMLPath);
                orderElement = doc.DocumentElement;
                if (orderElement == null) return;
                if (orderElement.ChildNodes == null || orderElement.ChildNodes.Count <= 0) return;
                orderChildr = orderElement.ChildNodes;
                if (orderChildr == null || orderChildr.Count <= 0) return;
                foreach (XmlNode item in orderChildr)
                {
                    if (item.Attributes["ProjectPath"].Value == sProjectPath)
                    {
                        if (item.Attributes["WorkCatalogPath"] != null && !string.IsNullOrWhiteSpace(item.Attributes["WorkCatalogPath"].Value))
                        {
                            _workCatalog = BundleRuntime.Instance.GetFirstOrDefaultService();
                            _workCatalog.SetWorksapce(item.Attributes["WorkCatalogPath"].Value);
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                LogAPI.Debug("更新最近打开的工程记录时间时异常:" + ex);
                return;
            }
            finally
            {
                if (doc != null) doc = null;
                if (orderElement != null) orderElement = null;
                if (orderChildr != null && orderChildr.Count > 0) orderChildr = null;
            }
        }
        /// 
        /// 代码注释原因:窗口最大化之后,在还原,工程名称界面变形
        /// 
        /// 
        /// 
        private void DgRecentOpenProject_SizeChanged(object sender, SizeChangedEventArgs e)
        {
        }
    }
}