using AR;
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 Project.Dialog
{
	public partial class Motion_MoveToGroup : Form
	{
		int axisX, axisY, axisZ;

		DataSet1 ds;
		int pidx = -1;/// = string.Empty;
		public Motion_MoveToGroup(DataSet1 dt_, int targetidx)
		{
			InitializeComponent();
			//	this.Size = new Size(800, 500);
			this.WindowState = FormWindowState.Maximized;
			btXNeg.Tag = "X-";
			btXPos.Tag = "X+";
			btYNeg.Tag = "Y-";
			btYPos.Tag = "Y+";
			this.ds = dt_;
			pidx = targetidx;
			//this.lvF.FullRowSelect = true;
			//this.lvF.GridLines = true;
			//arDatagridView1.DataSource = dt_.MCModel;

			var dr = dt_.MCModel.Where(t => t.idx == targetidx).FirstOrDefault();
			if (dr == null) this.Text = "Position-Based Movement";
			else this.Text = $"Position-Based Movement (Model: {dr.Title})";

		}

		private void Motion_MoveToGroup_Load(object sender, EventArgs e)
		{
			refreshData();
			tmDisplay.Start();
		}
		void refreshData()
		{
			//목록을 추출한다
			//this.lvF.Items.Clear();
			//this.listView1.Columns[0].Width = 120;
			//this.listView1.Columns[1].Width = 300;
			//this.lvF.Font = new Font("맑은 고딕", 15);

			var ctgrp = this.ds.MCModel.Where(t => t.pidx == this.pidx && string.IsNullOrEmpty(t.Category) == false).GroupBy(t => t.Category);
			var rawGrplist = ctgrp.Select(t => t.Key).ToList();
			Dictionary<string, List<int>> grpList = new Dictionary<string, List<int>>();


			foreach (var dr in ctgrp.OrderBy(t => t.Key))
			{
				var rawgrplist = dr.Key.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (var grpname in rawgrplist)
				{
					var keybuf = grpname.Split('|');    //그룹과 위치명은 | 로구분되어있다
					if (keybuf.Length == 1)
					{
						Array.Resize(ref keybuf, 2);
						keybuf[1] = keybuf[0];
						keybuf[0] = "Normal";
					}

					var newgrpname = string.Join("|", keybuf);
					var motlist = dr.GroupBy(t => t.idx).Select(t => t.Key).ToList();

					if (grpList.ContainsKey(newgrpname) == false)
					{
						grpList.Add(newgrpname, motlist);
					}
					else
					{
						//동일그룹이 등록되어있다
						var oldlist = grpList[newgrpname];
						foreach (var drindex in motlist)
							if (oldlist.Contains(drindex) == false) oldlist.Add(drindex);
						grpList[newgrpname] = oldlist;
					}
				}
			}

			tvFront.Nodes.Clear();
			tvFront.Font = new Font("맑은 고딕", 10, FontStyle.Bold);

			tvRear.Nodes.Clear();
			tvRear.Font = new Font("맑은 고딕", 10, FontStyle.Bold);

			tvOther.Nodes.Clear();
			tvOther.Font = new Font("맑은 고딕", 10, FontStyle.Bold);

			tvOther2.Nodes.Clear();
			tvOther2.Font = new Font("맑은 고딕", 10, FontStyle.Bold);

			//목록을 취합햇으니 표시한다
			foreach (var item in grpList)
			{
				var motlist = new List<int>();
				foreach (var drindex in item.Value)
				{
					var dr = this.ds.MCModel.Where(t => t.idx == drindex).First();
					motlist.Add(dr.MotIndex);
				}

				if (motlist.Count < 1) continue;

				var buf = item.Key.Split('|');

				var cate = buf[0];
				var itemname = buf[1];

				if (cate.Contains("_MANAGE"))
				{
					if (tvOther2.Nodes.ContainsKey(cate) == false)
					{
						var nd = tvOther2.Nodes.Add(cate, cate);
						var snd = nd.Nodes.Add(itemname, itemname + " ▶ (" + string.Join(",", motlist.OrderBy(t => t).Select(t => (eAxis)t)) + ")");
						snd.Tag = item.Value;

						if (itemname.Contains("PICKOFF")) snd.ForeColor = Color.Blue;
						else if (itemname.Contains("PICKON")) snd.ForeColor = Color.DarkGreen;
						else if (itemname.StartsWith("T")) snd.ForeColor = Color.Magenta;
						else snd.ForeColor = Color.Black;
					}
					else
					{
						var nd = tvOther2.Nodes[cate];
						var snd = nd.Nodes.Add(itemname, itemname + " ▶ (" + string.Join(",", motlist.OrderBy(t => t).Select(t => (eAxis)t)) + ")");
						snd.Tag = item.Value;

						if (itemname.Contains("PICKOFF")) snd.ForeColor = Color.Blue;
						else if (itemname.Contains("PICKON")) snd.ForeColor = Color.DarkGreen;
						else if (itemname.StartsWith("T")) snd.ForeColor = Color.Magenta;
						else snd.ForeColor = Color.Black;
					}
				}

				else if (itemname.StartsWith("R") || (itemname.StartsWith("F") == false && itemname.ToUpper().Contains("REAR")))
				{
					itemname = itemname.Replace("RSHUTTLE", "R");
					if (tvRear.Nodes.ContainsKey(cate) == false)
					{
						var nd = tvRear.Nodes.Add(cate, cate);
						var snd = nd.Nodes.Add(itemname, itemname + " ▶ (" + string.Join(",", motlist.OrderBy(t => t).Select(t => (eAxis)t)) + ")");
						snd.Tag = item.Value;

						if (itemname.Contains("PICKOFF")) snd.ForeColor = Color.Blue;
						else if (itemname.Contains("PICKON")) snd.ForeColor = Color.DarkGreen;
						else if (itemname.StartsWith("T")) snd.ForeColor = Color.Magenta;
						else snd.ForeColor = Color.Black;
					}
					else
					{
						var nd = tvRear.Nodes[cate];
						var snd = nd.Nodes.Add(itemname, itemname + " ▶ (" + string.Join(",", motlist.OrderBy(t => t).Select(t => (eAxis)t)) + ")");
						snd.Tag = item.Value;

						if (itemname.Contains("PICKOFF")) snd.ForeColor = Color.Blue;
						else if (itemname.Contains("PICKON")) snd.ForeColor = Color.DarkGreen;
						else if (itemname.StartsWith("T")) snd.ForeColor = Color.Magenta;
						else snd.ForeColor = Color.Black;

					}
				}
				else if (itemname.StartsWith("F") || (itemname.StartsWith("R") == false && itemname.ToUpper().Contains("FRONT")))

				{
					itemname = itemname.Replace("FSHUTTLE", "F");
					if (tvFront.Nodes.ContainsKey(cate) == false)
					{
						var nd = tvFront.Nodes.Add(cate, cate);
						var snd = nd.Nodes.Add(itemname, itemname + " ▶ (" + string.Join(",", motlist.OrderBy(t => t).Select(t => (eAxis)t)) + ")");
						snd.Tag = item.Value;

						if (itemname.Contains("PICKOFF")) snd.ForeColor = Color.Blue;
						else if (itemname.Contains("PICKON")) snd.ForeColor = Color.DarkGreen;
						else if (itemname.StartsWith("T")) snd.ForeColor = Color.Magenta;
						else snd.ForeColor = Color.Black;
					}
					else
					{
						var nd = tvFront.Nodes[cate];
						var snd = nd.Nodes.Add(itemname, itemname + " ▶ (" + string.Join(",", motlist.OrderBy(t => t).Select(t => (eAxis)t)) + ")");
						snd.Tag = item.Value;

						if (itemname.Contains("PICKOFF")) snd.ForeColor = Color.Blue;
						else if (itemname.Contains("PICKON")) snd.ForeColor = Color.DarkGreen;
						else if (itemname.StartsWith("T")) snd.ForeColor = Color.Magenta;
						else snd.ForeColor = Color.Black;
					}
				}

				else
				{
					if (tvOther.Nodes.ContainsKey(cate) == false)
					{
						var nd = tvOther.Nodes.Add(cate, cate);
						var snd = nd.Nodes.Add(itemname, itemname + " ▶ (" + string.Join(",", motlist.OrderBy(t => t).Select(t => (eAxis)t)) + ")");
						snd.Tag = item.Value;

						if (itemname.Contains("PICKOFF")) snd.ForeColor = Color.Blue;
						else if (itemname.Contains("PICKON")) snd.ForeColor = Color.DarkGreen;
						else if (itemname.StartsWith("T")) snd.ForeColor = Color.Magenta;
						else snd.ForeColor = Color.Black;
					}
					else
					{
						var nd = tvOther.Nodes[cate];
						var snd = nd.Nodes.Add(itemname, itemname + " ▶ (" + string.Join(",", motlist.OrderBy(t => t).Select(t => (eAxis)t)) + ")");
						snd.Tag = item.Value;

						if (itemname.Contains("PICKOFF")) snd.ForeColor = Color.Blue;
						else if (itemname.Contains("PICKON")) snd.ForeColor = Color.DarkGreen;
						else if (itemname.StartsWith("T")) snd.ForeColor = Color.Magenta;
						else snd.ForeColor = Color.Black;
					}
				}



				//var lv = this.lvF.Items.Add(buf[0]);
				//lv.SubItems.Add(buf[1]);
				//lv.SubItems.Add(string.Join(",", motlist.OrderBy(t => t)));

				//if (buf[1].StartsWith("R"))
				//	lv.ForeColor = Color.Blue;
				//else if (buf[1].StartsWith("T"))
				//	lv.ForeColor = Color.Magenta;

				//lv.Tag = item.Value; //datarowindex 를 가진다

			}

			tvFront.ExpandAll();
			tvRear.ExpandAll();
			tvOther.ExpandAll();
			tvOther2.ExpandAll();
		}

		private void toolStripButton1_Click(object sender, EventArgs e)
		{
			refreshData();
		}

		Task MoveMotion = null;


		List<int> GetCurrentList()
		{
			if (seltv == null)
			{
				UTIL.MsgE("Please select a position to move to first");
				return null;
			}
			var tn = seltv.SelectedNode;
			if (tn == null) return null;
			if (tn.Level < 1) return null;
			return (List<int>)tn.Tag;
		}

		private void toolStripButton2_Click(object sender, EventArgs e)
		{
			//지정된 축중에 Z축을 가진 대상이 있다면 그것을 우선 0으로 이동시킨다.
			List<int> idxlist = GetCurrentList();
			if (idxlist == null) return;

			List<eAxis> zlist = new List<eAxis>();
			List<eAxis> nlist = new List<eAxis>();

			List<DataSet1.MCModelRow> zplist = new List<DataSet1.MCModelRow>();
			List<DataSet1.MCModelRow> nplist = new List<DataSet1.MCModelRow>();

			System.Text.StringBuilder sb = new StringBuilder();
			foreach (var dridx in idxlist)
			{
				var dr = this.ds.MCModel.Where(t => t.idx == dridx).First();
				var ax = (eAxis)dr.MotIndex;
				var cate = ax.CategoryAttr();
				if (cate.StartsWith("Z"))
				{
					zlist.Add(ax);
					zplist.Add(dr);
				}
				else
				{
					//나머지축에 인터락이 있으면 처리하지 않는다.
					if (PUB.iLock[dr.MotIndex].IsEmpty() == false)
					{
						if (sb.Length < 1) sb.AppendLine("Motion interlock is set\n");
						var locklist = MOT.GetActiveLockList(ax, PUB.iLock[dr.MotIndex]);
						sb.AppendLine($"Axis : {ax}({dr.MotIndex}) Target:{string.Join(",", locklist)}");

					}
					nlist.Add(ax);
					nplist.Add(dr);
				}
			}

			if (sb.Length > 0)
			{
				UTIL.MsgE(sb.ToString(), true);
				return;
			}

			Queue<Tuple<eAxis, sPositionData, bool>> poslist = new Queue<Tuple<eAxis, sPositionData, bool>>();
			sb.AppendLine("Do you want to start axis movement?\nZ-axis will move to 0 first for safety before movement");

			int idx = 0;
			for (int i = 0; i < zlist.Count; i++)
			{
				var ax = zlist[i];
				var dr = zplist[i];
				sb.AppendLine($"[{++idx:000}] Move to origin (0) : " + ax.ToString());
				var p = new Tuple<eAxis, sPositionData, bool>(ax, new sPositionData
				{
					Axis = (short)ax,
					Position = 0,
					Speed = Math.Max(100, dr.Speed),
					Acc = dr.SpeedAcc,
					Dcc = dr.SpeedDcc,
				}, true);
				poslist.Enqueue(p);
			}

			for (int i = 0; i < nlist.Count; i++)
			{
				var ax = nlist[i];
				var dr = nplist[i];
				sb.AppendLine($"[{++idx:000}] {ax} Position move : {dr.Position}mm({dr.Speed}ms)");
				var p = new Tuple<eAxis, sPositionData, bool>(ax, new sPositionData
				{
					Axis = (short)ax,
					Position = dr.Position,
					Speed = Math.Max(100, dr.Speed),
					Acc = dr.SpeedAcc,
					Dcc = dr.SpeedDcc,
				}, false);
				poslist.Enqueue(p);
			}

			//x,y완료될떄까지 기다림
			for (int i = 0; i < nlist.Count; i++)
			{
				var ax = nlist[i];
				var dr = nplist[i];
				sb.AppendLine($"[{++idx:000}] {ax} Position move : {dr.Position}mm({dr.Speed}ms)");
				var p = new Tuple<eAxis, sPositionData, bool>(ax, new sPositionData
				{
					Axis = (short)ax,
					Position = dr.Position,
					Speed = Math.Max(100, dr.Speed),
					Acc = dr.SpeedAcc,
					Dcc = dr.SpeedDcc,
				}, true);
				poslist.Enqueue(p);
			}


			for (int i = 0; i < zlist.Count; i++)
			{
				var ax = zlist[i];
				var dr = zplist[i];
				sb.AppendLine($"[{++idx:000}] {ax} Position move : {dr.Position}mm({dr.Speed}ms)");
				var p = new Tuple<eAxis, sPositionData, bool>(ax, new sPositionData
				{
					Axis = (short)ax,
					Position = Math.Max(dr.Position - 50, 0),
					Speed = Math.Max(100, dr.Speed),
					Acc = dr.SpeedAcc,
					Dcc = dr.SpeedDcc,
				}, false);
				poslist.Enqueue(p);
			}

			var dlg = UTIL.MsgQ(sb.ToString());
			if (dlg != DialogResult.Yes) return;

			if (PUB.mot.HasHomeSetOff)
			{
				UTIL.MsgE("There are motions that have not completed homing");
				return;
			}



			MoveMotion = new Task(new Action(() =>
			{
				DateTime starttime = DateTime.Now;
				Tuple<eAxis, sPositionData, bool> p = null;
				while (poslist.Any() || p != null)  //자료가있거나 현재 걸려있는게 있는 경우
				{
					if (p == null)
					{
						p = poslist.Dequeue();
						starttime = DateTime.Now;
					}

					var seqtime = DateTime.Now - starttime;
					if (p.Item3)    //대기
					{

						if (MOT.CheckMotionPos(seqtime, p.Item2, "USER", false) == false)
						{
							var msg = PUB.mot.ErrorMessage;
							//{
							//Util.MsgE("모션 이동 실패\n" + Pub.mot.ErrorMessage);
							//break;
							//}
							if (seqtime.TotalSeconds > 60)
							{
								PUB.log.AddE("Position movement failed, exceeded 60 seconds");
								break;
							}
							System.Threading.Thread.Sleep(100);
							continue;
						}
					}
					else MOT.Move(p.Item1, p.Item2.Position, p.Item2.Speed, p.Item2.Acc, false, false, false); //위치이동을한다
					p = null; //다음으로 진행할 수 있게 한다
				}
			}));
			MoveMotion.RunSynchronously();
		}

		private void btSet_Click(object sender, EventArgs e)
		{
			//담당 축중에 ready 를 제외한 축을 추출하고
			//해당 축의 해당 위치에 command 좌표를 할당 합니다.


			if (PUB.mot.HasHomeSetOff)
			{
				UTIL.MsgE("There are motions that have not completed homing\nCannot save");
				return;
			}

			//지정된 축중에 Z축을 가진 대상이 있다면 그것을 우선 0으로 이동시킨다.
			//지정된 축중에 Z축을 가진 대상이 있다면 그것을 우선 0으로 이동시킨다.
			List<int> idxlist = GetCurrentList();
			if (idxlist == null) return;


			List<eAxis> nlist = new List<eAxis>();
			List<DataSet1.MCModelRow> nplist = new List<DataSet1.MCModelRow>();

			foreach (var dridx in idxlist)
			{
				var dr = this.ds.MCModel.Where(t => t.idx == dridx).First();
				if (dr.PosTitle.StartsWith("READY")) continue;

				var ax = (eAxis)dr.MotIndex;
				var cate = ax.CategoryAttr();
				nlist.Add(ax);
				nplist.Add(dr);
			}
			Queue<Tuple<DataSet1.MCModelRow, eAxis, string, double, double>> poslist = new Queue<Tuple<DataSet1.MCModelRow, eAxis, string, double, double>>();
			var sb = new System.Text.StringBuilder();
			sb.AppendLine("Do you want to save the positions of the following coordinates?");
			sb.AppendLine();

			for (int i = 0; i < nlist.Count; i++)
			{
				var ax = nlist[i];
				var dr = nplist[i];
				var curpos = PUB.mot.GetCmdPos((short)ax);
				sb.AppendLine($"[{dr.idx}] Axis:{ax} - {dr.PosTitle}\n\tChange position {dr.Position} -> {curpos}");
				var param = new Tuple<DataSet1.MCModelRow, eAxis, string, double, double>(dr, ax, dr.PosTitle, dr.Position, curpos);
				poslist.Enqueue(param);
			}


			using (var f = new Dialog.fSavePosition(poslist))
			{
				if (f.ShowDialog() != DialogResult.OK)
				{
					UTIL.MsgE("Coordinate saving was cancelled");
				}
			}



			//var dlg = Util.MsgQ(sb.ToString());
			//if (dlg != DialogResult.Yes) return;



			//var cnt = 0;
			//foreach (var p in poslist)
			//{
			//	p.Item1.Position = p.Item2;
			//	p.Item1.EndEdit();
			//	cnt += 1;
			//}
			//Util.MsgI($"{cnt}건의 위치를 변경 했습니다");
		}

		private void btJogUp_MouseDown(object sender, MouseEventArgs e)
		{
			var but = sender as Button;
			var tag = but.Tag.ToString();
			var vel = (float)nudJogVel.Value;
			if (tag == "X+")
			{
				if (axisX >= 0) PUB.mot.JOG((short)axisX, arDev.MOT.MOTION_DIRECTION.Positive, vel, 500, false, false);
			}
			else if (tag == "X-")
			{
				if (axisX >= 0) PUB.mot.JOG((short)axisX, arDev.MOT.MOTION_DIRECTION.Negative, vel, 500, false, false);
			}
			else if (tag == "Y+")
			{
				if (axisY >= 0) PUB.mot.JOG((short)axisY, arDev.MOT.MOTION_DIRECTION.Positive, vel, 500, false, false);
			}
			else if (tag == "Y-")
			{
				if (axisY >= 0) PUB.mot.JOG((short)axisY, arDev.MOT.MOTION_DIRECTION.Negative, vel, 500, false, false);
			}
			else if (tag == "Z+")
			{
				if (axisZ >= 0) PUB.mot.JOG((short)axisZ, arDev.MOT.MOTION_DIRECTION.Positive, vel, 500, false, false);
			}
			else if (tag == "Z-")
			{
				if (axisZ >= 0) PUB.mot.JOG((short)axisZ, arDev.MOT.MOTION_DIRECTION.Negative, vel, 500, false, false);
			}
		}

		private void btAClear_MouseUp(object sender, MouseEventArgs e)
		{
			var but = sender as Button;
			var tag = but.Tag.ToString();
			var vel = (float)nudJogVel.Value;
			if (tag == "X+")
			{
				if (axisX >= 0) PUB.mot.MoveStop("MOVETOGRP", (short)axisX, true);
			}
			else if (tag == "X-")
			{
				if (axisX >= 0) PUB.mot.MoveStop("MOVETOGRP", (short)axisX, true);
			}
			else if (tag == "Y+")
			{
				if (axisY >= 0) PUB.mot.MoveStop("MOVETOGRP", (short)axisY, true);
			}
			else if (tag == "Y-")
			{
				if (axisY >= 0) PUB.mot.MoveStop("MOVETOGRP", (short)axisY, true);
			}
			else if (tag == "Z+")
			{
				if (axisZ >= 0) PUB.mot.MoveStop("MOVETOGRP", (short)axisZ, true);
			}
			else if (tag == "Z-")
			{
				if (axisZ >= 0) PUB.mot.MoveStop("MOVETOGRP", (short)axisZ, true);
			}
		}


		private void tmDisplay_Tick(object sender, EventArgs e)
		{
			var motpos = string.Empty;
			if (axisX >= 0)
			{
				motpos += $"X:{PUB.mot.GetActPos((short)axisX):N3}/{PUB.mot.GetCmdPos((short)axisX):N3}";
				button6.BackColor = PUB.iLock[axisX].IsEmpty() ? Color.FromArgb(224, 224, 224) : Color.Orange;
			}
			else
			{
				motpos += "X:(none)";
				button6.BackColor = Color.FromArgb(224, 224, 224);
			}
			if (axisY >= 0)
			{
				motpos += $" / Y:{PUB.mot.GetActPos((short)axisY):N3}/{PUB.mot.GetCmdPos((short)axisY):N3}";
				button5.BackColor = PUB.iLock[axisY].IsEmpty() ? Color.FromArgb(224, 224, 224) : Color.Orange;
			}
			else
			{
				motpos += " Y:(none)";
				button5.BackColor = Color.FromArgb(224, 224, 224);
			}
			if (axisZ >= 0)
			{
				motpos += $" / Z:{PUB.mot.GetActPos((short)axisZ):N3},{PUB.mot.GetCmdPos((short)axisZ):N3}";
				button4.BackColor = PUB.iLock[axisZ].IsEmpty() ? Color.FromArgb(224, 224, 224) : Color.Orange;
			}
			else
			{
				motpos += " Z:(none)";
				button4.BackColor = Color.FromArgb(224, 224, 224);
			}

			this.lbMotPos.Text = motpos;

		}

		private void Motion_MoveToGroup_FormClosed(object sender, FormClosedEventArgs e)
		{
			tmDisplay.Stop();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			var but = sender as Button;
			if (but.Text.EndsWith("-ZERO"))
			{

				if (but.Text.StartsWith("X") && axisX >= 0)
				{
					if (UTIL.MsgQ("Do you want to move X position to 0?") != DialogResult.Yes) return;
					MOT.Move((eAxis)axisX, 0, 100, 1000, false, false, false);
				}
				else if (but.Text.StartsWith("Y") && axisY >= 0)
				{
					if (UTIL.MsgQ("Do you want to move Y position to 0?") != DialogResult.Yes) return;
					MOT.Move((eAxis)axisY, 0, 100, 1000, false, false, false);
				}
				else if (but.Text.StartsWith("Z") && axisZ >= 0)
				{
					if (UTIL.MsgQ("Do you want to move Z position to 0?") != DialogResult.Yes) return;
					MOT.Move((eAxis)axisZ, 0, 100, 1000, false, false, false);
				}
			}
			else if (but.Text.EndsWith("-MOVE"))
			{

				//지정된 축중에 Z축을 가진 대상이 있다면 그것을 우선 0으로 이동시킨다.
				List<int> idxlist = GetCurrentList();
				if (idxlist == null) return;

				foreach (var dridx in idxlist)
				{
					var dr = this.ds.MCModel.Where(t => t.idx == dridx).First();
					var ax = (eAxis)dr.MotIndex;
					var cate = ax.CategoryAttr();


					//나머지축에 인터락이 있으면 처리하지 않는다.
					var sb = new System.Text.StringBuilder();
					if (PUB.iLock[dr.MotIndex].IsEmpty() == false)
					{
						if (sb.Length < 1) sb.AppendLine("Motion interlock is set\n");
						var locklist = MOT.GetActiveLockList(ax, PUB.iLock[dr.MotIndex]);
						sb.AppendLine($"Axis : {ax}({dr.MotIndex}) Target:{string.Join(",", locklist)}");
						sb.AppendLine();
						sb.AppendLine("Do you want to continue?");
						if (UTIL.MsgQ(sb.ToString()) != DialogResult.Yes) return;
					}





					if (but.Text.StartsWith("X") && cate.StartsWith("X") && axisX >= 0)
					{
						if (UTIL.MsgQ($"Do you want to move X position to ({dr.Position})?") != DialogResult.Yes) return;
						MOT.Move(ax, dr.Position, dr.Speed, 1000, false, false, false);
					}
					else if (but.Text.StartsWith("Y") && cate.StartsWith("Y") && axisY >= 0)
					{
						if (UTIL.MsgQ($"Do you want to move Y position to ({dr.Position})?") != DialogResult.Yes) return;
						MOT.Move(ax, dr.Position, dr.Speed, 1000, false, false, false);
					}
					else if (but.Text.StartsWith("Z") && cate.StartsWith("Z") && axisZ >= 0)
					{
						if (UTIL.MsgQ($"Do you want to move Z position to ({dr.Position})?") != DialogResult.Yes) return;
						MOT.Move(ax, dr.Position, Math.Min(50, dr.Speed), 1000, false, false, false);
					}
				}
			}
		}

		private void button13_Click(object sender, EventArgs e)
		{
			var but = sender as Button;
			var txt = but.Text.Trim();
			var aname = txt.Substring(0, 1);
			var value = txt.Split(':')[1].Replace("mm", "").Replace("+", "").Trim();
			var v = float.Parse(value);
			if (aname == "X" && axisX >= 0)
			{
				//이동을 해준다
				MOT.Move((eAxis)axisX, v, 100, 1000, true, false, false);
			}
			else if (aname == "Y" && axisY >= 0)
			{
				//이동을 해준다
				MOT.Move((eAxis)axisY, v, 100, 1000, true, false, false);
			}
			else if (aname == "Z" && axisZ >= 0)
			{
				//이동을 해준다
				MOT.Move((eAxis)axisZ, v, 100, 1000, true, false, false);
			}
		}

		TreeNode prevnode = null;
		TreeView seltv = null;
		private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
		{
			//선택되면 대상축에서 x,y,z를 찾아서 설정하고 enable 을 설정한다.
			if (seltv != null)
			{
				seltv.BackColor = Color.White;
			}
			seltv = sender as TreeView;
			seltv.BackColor = Color.LightGoldenrodYellow;

			if (prevnode != null)
			{
				prevnode.BackColor = Color.White;
			}



			//지정된 축중에 Z축을 가진 대상이 있다면 그것을 우선 0으로 이동시킨다.
			List<int> idxlist = GetCurrentList();
			if (idxlist == null) return;
			var tn = this.seltv.SelectedNode;
			this.Text = $"{tn.Parent.Text} - {tn.Text}";

			this.prevnode = tn;
			this.prevnode.BackColor = Color.Lime;

			List<eAxis> xlist = new List<eAxis>();
			List<eAxis> ylist = new List<eAxis>();
			List<eAxis> zlist = new List<eAxis>();

			List<DataSet1.MCModelRow> xplist = new List<DataSet1.MCModelRow>();
			List<DataSet1.MCModelRow> yplist = new List<DataSet1.MCModelRow>();
			List<DataSet1.MCModelRow> zplist = new List<DataSet1.MCModelRow>();

			foreach (var dridx in idxlist)
			{
				var dr = this.ds.MCModel.Where(t => t.idx == dridx).First();
				var ax = (eAxis)dr.MotIndex;
				var cate = ax.CategoryAttr();
				if (cate.StartsWith("Z"))
				{
					zlist.Add(ax);
					zplist.Add(dr);
				}
				else if (cate.StartsWith("X"))
				{
					xlist.Add(ax);
					xplist.Add(dr);
				}
				else if (cate.StartsWith("Y"))
				{
					ylist.Add(ax);
					yplist.Add(dr);
				}
			}

			if (xlist.Count == 1)
			{
				axisX = (int)xlist.First();
				btXNeg.Enabled = true;
				btXPos.Enabled = true;
				btXNeg.BackColor = Color.LightSkyBlue;
				btXPos.BackColor = Color.LightSkyBlue;
			}
			else
			{
				axisX = -1;
				btXNeg.Enabled = false;
				btXPos.Enabled = false;
				btXNeg.BackColor = Color.LightGray;
				btXPos.BackColor = Color.LightGray;
			}

			if (ylist.Count == 1)
			{
				axisY = (int)ylist.First();
				btYNeg.Enabled = true;
				btYPos.Enabled = true;
				btYNeg.BackColor = Color.LightSkyBlue;
				btYPos.BackColor = Color.LightSkyBlue;
			}
			else
			{
				axisY = -1;
				btYNeg.Enabled = false;
				btYPos.Enabled = false;
				btYNeg.BackColor = Color.LightGray;
				btYPos.BackColor = Color.LightGray;
			}

			if (zlist.Count == 1)
			{
				axisZ = (int)zlist.First();
				btZNeg.Enabled = true;
				btZPos.Enabled = true;
				btZNeg.BackColor = Color.LightSkyBlue;
				btZPos.BackColor = Color.LightSkyBlue;
			}
			else
			{
				axisZ = -1;
				btZNeg.Enabled = false;
				btZPos.Enabled = false;
				btZNeg.BackColor = Color.LightGray;
				btZPos.BackColor = Color.LightGray;
			}

			eAxis axx = (eAxis)axisX;
			eAxis axy = (eAxis)axisY;
			eAxis axz = (eAxis)axisZ;

			lbX.Text = $"({axisX}){axx}";
			if (axisX >= 0) lbX.Text += $"({xplist.First().PosIndex}mm)";
			lbY.Text = $"({axisY}){axy}";
			if (axisY >= 0) lbY.Text += $"({yplist.First().PosIndex}mm)";
			lbZ.Text = $"({axisZ}){axz}";
			if (axisZ >= 0) lbZ.Text += $"({zplist.First().PosIndex}mm)";
		}

		private void button25_Click(object sender, EventArgs e)
		{
			var but = sender as Button;
			var val = int.Parse(but.Text);
			nudJogVel.Value = (decimal)val;
		}

		private void toolStripButton2_Click_1(object sender, EventArgs e)
		{
			using (var f = new Model_Motion())
				f.ShowDialog();
		}

		private void toolStripButton3_Click(object sender, EventArgs e)
		{
			using (var f = new Dialog.fIOMonitor())
				f.ShowDialog();
		}


		private void button28_Click(object sender, EventArgs e)
		{
			//var cur = DIO.GetIOOutput(eDOName.F셔틀_회전180);
			//string msg;
			//if (cur) msg = "셔틀(F)이 현재 뒤집혀 있습니다.\n원위치로 복귀 할까요?";
			//else msg = "셔틀(F) 을 뒤집을까요?";

			//var dlg = Util.MsgQ(msg);
			//if (dlg != DialogResult.Yes) return;
		}

		private void button29_Click(object sender, EventArgs e)
		{

		}

		private void toolStripButton4_Click(object sender, EventArgs e)
		{
			using (var f = new Dialog.Quick_Control())
				f.ShowDialog();
		}

		private void button30_Click(object sender, EventArgs e)
		{

		}

		private void btAllZSafe_Click(object sender, EventArgs e)
		{
			//Z1,2,3 안전위치로 이동한다 220421
			var dlg = UTIL.MsgQ("Do you want to move all Z axes to safe position?\n" +
				"For Z1 and Z4, if they are holding sockets, damage may occur during safe position movement.\n" +
				"Check the socket status of each gripper before proceeding\n" +
				"If Z axes are moved arbitrarily, work may not continue properly\n " +
				"It is recommended to cancel the work and start again");

			if (dlg != DialogResult.Yes) return;

			var PosZ1 = MOT.GetPZPos(ePZLoc.READY);
			var PosZ2 = MOT.GetLZPos(eLZLoc.READY);
			var PosZ3 = MOT.GetRZPos(eRZLoc.READY);

			PosZ1.Position = 0;
			PosZ2.Position = 0;
			PosZ3.Position = 0;

			MOT.Move(PosZ1);
			MOT.Move(PosZ2);
			MOT.Move(PosZ3);
		}



		private void button31_Click(object sender, EventArgs e)
		{

		}

		private void btJogStop_Click(object sender, EventArgs e)
		{
			if (axisX >= 0) MOT.Stop((eAxis)axisX, "MOVETOGRP", true);
			if (axisY >= 0) MOT.Stop((eAxis)axisY, "MOVETOGRP", true);
			if (axisZ >= 0) MOT.Stop((eAxis)axisZ, "MOVETOGRP", true);
		}


		private void motCommandButton1_Click(object sender, EventArgs e)
		{
			if (axisX >= 0) MOT.Stop((eAxis)axisX, "MOVETOGRP", true);
			if (axisY >= 0) MOT.Stop((eAxis)axisY, "MOVETOGRP", true);
			if (axisZ >= 0) MOT.Stop((eAxis)axisZ, "MOVETOGRP", true);
		}
	}
}
