using CodeLibrary;
using ConfigHelper;
using DeviceLibrary;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoScanAndLabel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.FormClosing += Form1_FormClosing;
            this.Text = Config.Get(Setting_Init.App_Title);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
            }
        }

        LogControl lc = new LogControl();
        IOControl ioc = new IOControl();
        AxisControl ac = new AxisControl();
        SettingControl sc = new SettingControl();
        private void Form1_Load(object sender, EventArgs e)
        {
            List<CodeInfo> codeInfos = new List<CodeInfo>();
            //codeInfos.Add(new CodeInfo("", 528, 406));
            codeInfos.Add(new CodeInfo("", 925, 520));
            //codeInfos.Add(new CodeInfo("", 564, 684));

            btn_run.Enabled = false;
            btn_stop.Enabled = false;
            #region 报警信息listview初始化
            listView1.View = View.Details;
            ColumnHeader emptycol = new ColumnHeader();
            emptycol.Text = "";
            emptycol.Width = 0;
            ColumnHeader msgcol = new ColumnHeader();
            msgcol.Text = "信息";
            msgcol.Width = 600;
            ColumnHeader timecol = new ColumnHeader();
            timecol.Text = "时间";
            timecol.Width = 150;
            listView1.Columns.Add(emptycol);
            listView1.Columns.Add(timecol);
            listView1.Columns.Add(msgcol);
            listView1.ColumnWidthChanging += listView_ColumnWidthChanging;
            #endregion

            #region 状态信息listview初始化
            stateView.View = View.Details;
            ColumnHeader c1 = new ColumnHeader();
            c1.Text = "";
            c1.Width = 0;
            ColumnHeader c2 = new ColumnHeader();
            c2.Text = "模块";
            c2.Width = 100;
            ColumnHeader c3 = new ColumnHeader();
            c3.Text = "步骤";
            c3.Width = 100;
            ColumnHeader c4 = new ColumnHeader();
            c4.Text = "信息";
            c4.Width = 400;

            stateView.Columns.Add(c1);
            stateView.Columns.Add(c2);
            stateView.Columns.Add(c3);
            stateView.Columns.Add(c4);
            stateView.ColumnWidthChanging += listView_ColumnWidthChanging;
            #endregion

            LogUtil.info("开始初始化");

            RobotManage.LoadFinishEvent += RobotManage_LoadFinishEvent;
            
            RobotManage.Init();
        }
        private void listView_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
        {
            e.NewWidth = (sender as ListView).Columns[e.ColumnIndex].Width;
            e.Cancel = true;
        }
        void addTablePage() {
            AddForm("IO调试", ioc);
            AddForm("伺服调试", ac);
            AddForm("相关设置", sc);
            AddForm("日志", lc);
        }
        public delegate void setstatedelegate(List<MoveInfo> moveinfoList);
        private void MainMachine_ProcessMoveinfoEvent(List<MoveInfo> moveinfoList)
        {
            var d = new setstatedelegate(SetState);
            this.Invoke(d, moveinfoList);
        }
        void SetState(List<MoveInfo> moveInfoList)
        {
            this.SuspendLayout();
            stateView.Items.Clear();
            foreach (MoveInfo moveInfo in moveInfoList)
            {
                ListViewItem lvi = new ListViewItem(new string[] { "", moveInfo.Name, moveInfo.MoveStep.ToString(),moveInfo.GetStateStr() });
                stateView.Items.Add(lvi);
            }
            ListViewItem lvi1 = new ListViewItem(new string[] { "", "Printer", RobotManage.mainMachine.LastPrintStatus.ToString(), ConfigHelper.Config.Get(Setting_Init.PrinterName) });
            stateView.Items.Add(lvi1);
            this.ResumeLayout(true);

        }
        private void AddForm(string text, UserControl form)
        {
            //text = text.PadLeft(10, ' ');
            TabPage lineTabPage = new TabPage(text);
            // lineTabPage.AutoScroll = true;
            //lineTabPage.Tag = robot;
            Panel linePan = new Panel();
            linePan.Dock = DockStyle.Fill;
            linePan.AutoScroll = true;
            lineTabPage.Controls.Add(linePan);
            //form.FormBorderStyle = FormBorderStyle.None;
            //form.TopLevel = false;
            linePan.Controls.Add(form);
            form.Dock = DockStyle.Fill;
            linePan.Anchor = ((AnchorStyles)((AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left)));
            form.Anchor = ((AnchorStyles)((AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left)));
            form.Show();
            //tabPageList.Add(lineTabPage);
            tabControl1.Controls.Add(lineTabPage);
        }

        private void 启用调试模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RobotManage.IsDebug = RobotManage.IsDebug ? false : true;

            (sender as ToolStripMenuItem).Text = !RobotManage.IsDebug ? "启用调试模式" : "停用调试模式";

            //RobotManage.Init();

            if (RobotManage.IsDebug)
            {
                addTablePage();
                RobotManage.LoadDebug();
            }
            else {
                for (int i = tabControl1.TabPages.Count-1; i > 0; i--)
                {
                    tabControl1.TabPages[i].Parent = null;
                }
            }
        }

        public delegate void setmsgdelegate(List<Msg> msgs);
        private void MainMachine_ProcessMsgEvent(List<Msg> msgs)
        {
            var d = new setmsgdelegate(SetMsg);
            this.Invoke(d, msgs);
        }

        private void RobotManage_LoadFinishEvent(bool state, string msg)
        {
            if (state)
            {
                btn_run.Enabled = true;
                btn_stop.Enabled = true;
                RobotManage.mainMachine.ProcessMsgEvent += MainMachine_ProcessMsgEvent;
                RobotManage.mainMachine.ProcessMoveinfoEvent += MainMachine_ProcessMoveinfoEvent;
            }
            var lm = new List<Msg>();
            foreach (string ms in msg.Split(new char[] { '\n' },StringSplitOptions.RemoveEmptyEntries))
            {
                var m = new Msg();
                m.datetime = DateTime.Now;
                m.msgtxt = ms;
                m.msgLevel = state ? MsgLevel.info : MsgLevel.warning;
                lm.Add(m);
            }
            SetMsg(lm);
        }
        void SetMsg(List<Msg> msgs)
        {
            this.SuspendLayout();
            listView1.Items.Clear();
            foreach (Msg msg in msgs)
            {
                ListViewItem lvi = new ListViewItem(new string[] {"", msg.datetime.ToString(), msg.msgtxt });
                if (msg.msgLevel==MsgLevel.info)
                    lvi.ForeColor = Color.DarkGreen;
                else
                    lvi.ForeColor = Color.Red;
                listView1.Items.Add(lvi);
            }
            this.ResumeLayout(true);
        }
        bool userpause = false;


        private void btn_run_Click(object sender, EventArgs e)
        {
            if (!RobotManage.isRunning)
            {
                RobotManage.Start();
                userpause = false;
                if (RobotManage.isRunning)
                    (sender as Button).Text = "暂停运行";
            }
            else if (!userpause)
            {
                userpause = true;
                RobotManage.UserPause(userpause);
                (sender as Button).Text = "恢复运行";
            }
            else if (userpause)
            {
                userpause = false;
                RobotManage.UserPause(userpause);
                (sender as Button).Text = "暂停运行";
            }
        }

        private void btn_stop_Click(object sender, EventArgs e)
        {
            btn_run.Text = "启动";
            RobotManage.Stop();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (RobotManage.isRunning) {
                MessageBox.Show("机器尚在运行,不能退出,请先停止运行.");
            } else {
                Application.Exit();
            }
        }

        private void cb_IgnoreSafecheck_CheckedChanged(object sender, EventArgs e)
        {
            RobotManage.IgnoreSafecheck((sender as CheckBox).Checked);
        }

        private void cb_IgnoreGratingSignal_CheckedChanged(object sender, EventArgs e)
        {
            RobotManage.IgnoreGratingSignal((sender as CheckBox).Checked);
        }
    }
}