using com.superscene.util;
using parkMonitor.bll;
using parkMonitor.entity;
using parkMonitor.model;
using parkMonitor.server;
using parkMonitor.server.monitorServer;
using parkMonitor.server.uiLogServer;
using parkMonitor.view.okBoxWin;
using parkMonitor.view.util;
using parkMonitor.view.writePLCWin;
using parkMonitor.viewModel;
using parkMonitor.viewModel.detail;
using parkMonitor.viewModel.devInfoPanel;
using parkMonitor.viewModel.objectTree;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
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;

namespace parkMonitor
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        List<ObjectTreeRootVM> lstObjectTree = new List<ObjectTreeRootVM>();

        public MainWinVM winVM = new MainWinVM();

        MainBll bll = new MainBll();
		
        ObjectItemVM selectedTreeVM = null;
        ObservableCollection<DevDetailItemVM> selectedDetailItemVM = null;
        //XmlCtl xmlConfig = new XmlCtl();
        //private bool isScrollLogBox = true;

        public MainWindow()
        {
            InitializeComponent();

            //winform 样式
            System.Windows.Forms.Application.EnableVisualStyles();
            System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);

            MainModel.ins.mainWin = this;

            DataContext = winVM;
            clearLogText();

            //initTestData();

            bll.init();

			//debug
			if(System.IO.File.Exists("uidebug")) {
				win.WindowState = WindowState.Normal;
				win.WindowStyle = WindowStyle.SingleBorderWindow;
			}
		}

        /// <summary>测试数据</summary>
        private void initTestData()
        {
            DataContext = winVM = new DesignMainWinVM();
        }

        //树形菜单-选中item事件
        private void treeObjectInfo_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            try
            {
                ObjectItemVM data = e.NewValue as ObjectItemVM;
                //非叶子节点
                if (data == null)
                {
                    return;
                }

                selectedTreeVM = null;
                btnReset.Visibility = Visibility.Collapsed;
				
                MonitorServer monitor = EquipmentSimpleFactory.ins.FindEquipment(EquipmentName.Monitor) as MonitorServer;
                var detailVM = monitor.getSelectedDetailViewModel(data);
                if (detailVM == null)
                {
                    winVM.DevInfoDetail = null;
                    selectedTreeVM = null;
                    selectedDetailItemVM = null;
                    return;
                }
                else
                {
                    winVM.DevInfoDetail = detailVM;

                    selectedTreeVM = data;
                    selectedDetailItemVM = detailVM;
                }
            }
            catch (Exception)
            {

            }
        }

        private void txtLog_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = true;
        }

        public void clearLogText()
        {
            rtxtLog.Document.Blocks.Clear();
            rtxtLog.Document.LineHeight = 2;
            removeFirstLog();
        }

        public void removeFirstLog()
        {
            Block block = rtxtLog.Document.Blocks.FirstOrDefault();
            if (block != null)
            {
                rtxtLog.Document.Blocks.Remove(block);
            }
        }

        //int logTextLen = 0;
        private void addLogText(string text, Brush color)
        {
            rtxtLog.Document.Blocks.Add(new Paragraph(new Run(text) { Foreground = color }) { LineHeight = 1 });
        }

        public void addLogText(UILogModel data)
        {
            bool isScrollLogBox = IsScrolledToEnd(rtxtLog);
            addLogText(data.info, data.color);
            if (isScrollLogBox)
            {
                scrollLogToEnd();
            }
        }

        public void setLogText(List<UILogModel> data)
        {
            bool isScrollLogBox = IsScrolledToEnd(rtxtLog);

            clearLogText();
            for (int i = 0; i < data.Count; ++i)
            {
                addLogText(data[i].info, data[i].color);
            }

            if (isScrollLogBox)
            {
                scrollLogToEnd();
            }
        }

        private bool IsScrolledToEnd(RichTextBox textBox)
        {
            return textBox.VerticalOffset + textBox.ViewportHeight >= textBox.ExtentHeight;
        }

        /// <summary>滚动日志框到底部</summary>
        private void scrollLogToEnd()
        {
            rtxtLog.ScrollToEnd();
        }

        //点击关闭按钮事件
        private void btnClose_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            OkBoxWin win = new OkBoxWin();
            language.Language lng = language.Language.ins;

            win.show(this, lng.exit, lng.sureExit);

            if (win.isOk)
            {
                Close();
                System.Environment.Exit(0);
            }
        }

        private void grdDevTreeType_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            winVM.IsDevTreeShowList = !winVM.IsDevTreeShowList;
        }

        private void win_Closed(object sender, EventArgs e)
        {
            CmdServer.ins.send(CmdType.MainWinClosed);

            //xmlConfig.save();
        }

        /// <summary>点击复位按钮</summary>
        private void btnReset_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (selectedTreeVM == null)
            {
                return;
            }
        }

        /// <summary>点击写入按钮</summary>
        private void lstDetailInfo_ClickWrite(object sender, RoutedEventArgs e)
        {
            try
            {
                int idx = lstDetailInfo.SelectedIndex;
                if (selectedDetailItemVM == null)
                {
                    return;
                }
                if (idx < 0 || idx >= selectedDetailItemVM.Count)
                {
                    return;
                }

                DevDetailItemVM itemVM = selectedDetailItemVM[idx];

                WritePLCWin win = new WritePLCWin();
                win.show(this, selectedTreeVM.Name, itemVM);
                if (!win.isOk)
                {
                    return;
                }

                string val = win.value;
                MonitorServer monitor = EquipmentSimpleFactory.ins.FindEquipment(EquipmentName.Monitor) as MonitorServer;
                monitor.writeData(selectedTreeVM, idx, val);
            }
            catch (Exception)
            {

            }
        }

        /// <summary>点击复位按钮</summary>
        private void lstDetailInfo_ClickReset(object sender, RoutedEventArgs e)
        {
            try
            {
                int idx = lstDetailInfo.SelectedIndex;
                if (selectedDetailItemVM == null)
                {
                    return;
                }
                if (idx < 0 || idx >= selectedDetailItemVM.Count)
                {
                    return;
                }

                DevDetailItemVM itemVM = selectedDetailItemVM[idx];

                OkBoxWin win = new OkBoxWin();
                win.show(this, "确定复位?", "复位<" + itemVM.Name + ">?");
                if (!win.isOk)
                {
                    return;
                }

                //PLCMonitorServer.ins.writeData(selectedTreeVM, idx, "0");
                MonitorServer monitor = EquipmentSimpleFactory.ins.FindEquipment(EquipmentName.Monitor) as MonitorServer;
                monitor.restData(selectedTreeVM, idx);
            }
            catch (Exception)
            {

            }
        }
    }
}
