#pragma warning disable IDE1006 // 명명 스타일

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.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace Project.Dialog
{
	public partial class Model_Motion_Desc : Form
	{
		public string Value = string.Empty;
		short axisIndex = 0;
		eAxis axis = eAxis.Z_THETA;//
		Color sbBackColor = Color.FromArgb(200, 200, 200);
		DataSet1 ds;

		public Model_Motion_Desc(DataSet1 ds_)
		{
			InitializeComponent();

			this.ds = ds_;
			//this.bs.Filter = string.Empty;
			//this.bsPos.Filter = string.Empty;


			this.bs.DataSource = ds_;
			this.bsPos.DataSource = ds_;

			//this.bs.DataMember = string.Empty;
			//this.bsPos.DataMember = string.Empty;

			if (System.Diagnostics.Debugger.IsAttached == false)
			{
				// fb = new Dialog.fBlurPanel();
				//fb.Show();
			}

			this.KeyPreview = true;
			this.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Escape) this.Close(); };
			this.StartPosition = FormStartPosition.CenterScreen;
			this.FormClosed += __Closed;

			var axlist = Enum.GetNames(typeof(eAxis));
			var axvalues = Enum.GetValues(typeof(eAxis));

			var preValueList = new List<ushort>();

			//모터설정값을 보고 해당 모터의 목록을 표시한다.
			//사용하지 않는 축은 표시하지 않는다
			for (int i = 0; i < SETTING.System.MotaxisCount; i++)
			{
				var axis = (eAxis)i;
				var axisname = (eAxisName)i;
				var axTitle = axisname.ToString();// axis.ToString();

				if (PUB.system_mot.UseAxis(i) == false) continue;// axTitle = "Disable";
				if (axTitle.Equals(i.ToString())) axTitle = "(No Name)";
				this.dvMot.Rows.Add(
					new string[] {
						i.ToString(), axTitle, string.Empty, string.Empty, string.Empty,
						string.Empty, string.Empty, string.Empty, string.Empty, string.Empty,
						string.Empty
					});
			}


		}


		private void __Load(object sender, EventArgs e)
		{
			this.Show();
			////'Application.DoEvents();

			//this.ds1.Clear();
			//this.ds1.MCModel.Merge(Pub.mdm.dataSet.MCModel);
			//this.ds1.MCModel.AcceptChanges();
			//this.ds1.MCModel.TableNewRow += Model_TableNewRow;

			this.bs.Filter = "isnull(title,'') <> ''";
			this.bsPos.Filter = "isnull(title,'') = '' and isnull(motindex,-1) = -1";
			this.tmDisplay.Start();

			//button7.Enabled = !Pub.mot.HasHomeSetOff;
			//dispal current
			if (PUB.Result.isSetmModel)
			{
				arLabel18.Text = PUB.Result.mModel.Title;
				//find data
				var datas = this.ds1.MCModel.Select("", this.bs.Sort);
				for (int i = 0; i < datas.Length; i++)
				{
					if (datas[i]["Title"].ToString() == PUB.Result.mModel.Title)
					{
						this.bs.Position = i;
						break;
					}
				}
			}
			else arLabel18.Text = "--";

			if (this.ds1.MCModel.Rows.Count < 1)
			{
				var newdr = this.ds1.MCModel.NewMCModelRow();
				newdr.Title = "Default";
				newdr.pidx = -1;
				newdr.PosIndex = -1;
				newdr.idx = ds1.MCModel.Rows.Count + 1;
				this.ds1.MCModel.AddMCModelRow(newdr);
			}

			PUB.log.RaiseMsg += log_RaiseMsg;
			refreshtreen();
		}



		private void __Closed(object sender, FormClosedEventArgs e)
		{
			//if (fb != null) fb.Dispose();
			this.tmDisplay.Enabled = false;
		}

		void log_RaiseMsg(DateTime LogTime, string TypeStr, string Message)
		{

		}


		private void tmDisplay_Tick(object sender, EventArgs e)
		{
				this.Text = "MODEL(MOTION) SETTING";

			if (PUB.mot.IsInit == false)
			{
				//if (groupBox3.Enabled == true) groupBox3.Enabled = false;
			}
			else
			{
				//if (groupBox3.Enabled == false) groupBox3.Enabled = true;

				//각축별 기본 상태를 표시해준다.
				dvMot.SuspendLayout();
				for (int r = 0; r < dvMot.RowCount; r++) // 오류수정 2111221
				{
					var row = this.dvMot.Rows[r];
					var axis = short.Parse(row.Cells[0].Value.ToString());
					row.Cells[0].Style.BackColor = PUB.mot.IsServOn(axis) ? Color.Lime : Color.Tomato;
					row.Cells[2].Value = $"{PUB.mot.GetCmdPos(axis)}";
					row.Cells[3].Value = $"{PUB.mot.GetActPos(axis)}";
					row.Cells[4].Style.BackColor = PUB.mot.IsOrg(axis) ? Color.SkyBlue : Color.Gray;
					row.Cells[5].Style.BackColor = PUB.mot.IsLimitN(axis) ? Color.Red : Color.Gray;
					row.Cells[6].Style.BackColor = PUB.mot.IsLimitP(axis) ? Color.Red : Color.Gray;
					row.Cells[7].Style.BackColor = PUB.mot.IsInp(axis) ? Color.SkyBlue : Color.Gray;
					row.Cells[8].Style.BackColor = PUB.mot.IsServAlarm(axis) ? Color.Red : Color.Gray;
					row.Cells[9].Style.BackColor = PUB.mot.IsHomeSet(axis) ? Color.Green : Color.Gray;
				}
				dvMot.ResumeLayout();
			}
			// this.tblFG.Invalidate();
		}

		private void dv_DataError(object sender, DataGridViewDataErrorEventArgs e)
		{

		}


		/// <summary>
		/// 상단목록에서 모션을 선택한 경우
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void MotAxisSelect(int axisindex)
		{


			RefreshMotorPosition();
		}

		private void bs_CurrentChanged_1(object sender, EventArgs e)
		{

			//BindingData();
		}
		void RefreshMotorPosition()
		{
			var drv = this.bs.Current as DataRowView;
			if (drv == null) return;
			if (dvMot.SelectedCells.Count < 1) return;
			var dr = drv.Row as DataSet1.MCModelRow;

			//var rowindex = dvMot.SelectedCells[0].RowIndex;
			//var row = dvMot.Rows[rowindex];
			//var axisIndex = short.Parse(row.Cells[0].Value.ToString());
			//var axis = (eAxis)this.axisIndex;
			//var axisTitle = row.Cells[1].Value.ToString();
			{


				//위치정보 표시
				bsPos.Filter = string.Format("pidx={0} and motindex = {1}", dr.idx, this.axisIndex);

				////(위치정보) 데이터수량이 맞지 않으면 재 생성한다
				//string[] list = null;
				//Array val = null;
				//Type axType = null;
				//var axis = (eAxis)axisIndex;

				//if (axis == eAxis.X2_FRT || axis == eAxis.X3_RER) axType = typeof(eX2SHTLoc);
				//else if (axis == eAxis.X1_TOP) axType = typeof(eX1TOPLoc);
				//else if (axis == eAxis.Y1_PIK) axType = typeof(eY1PIKLoc);
				//else if (axis == eAxis.Y2_PRECLEAN) axType = typeof(eY2BRSLoc);
				//else if (axis == eAxis.Y3_LASER) axType = typeof(eY3LSRLoc);
				//else if (axis == eAxis.Y4_VIS) axType = typeof(eY4VISLoc);  //전용으로바꿔야함

				//else if (axis == eAxis.Z1_PIK) axType = typeof(eZ1PIKLoc);
				//else if (axis == eAxis.Z2_PRECLEAN) axType = typeof(eZ2BRSLoc);
				//else if (axis == eAxis.Z3_LASER) axType = typeof(eZ3LSRLoc);
				//else if (axis == eAxis.Z4_VISION) axType = typeof(eZ4VISLoc);//전용으로바꿔야함


				//else if (axis == eAxis.L_REAR || axis == eAxis.L_FRNT) axType = typeof(eLDLoc);
				//else if (axis == eAxis.UR_NG || axis == eAxis.UR_OK || axis == eAxis.UF_NG || axis == eAxis.UF_OK) axType = typeof(eUDLoc);

				//if (axType == null)
				//{
				//	Util.MsgE("지정한 축에 대한 위치정보가 지정되지 않았습니다");
				//	return;
				//}


				//list = Enum.GetNames(axType);
				//val = Enum.GetValues(axType);

				//var sb = new System.Text.StringBuilder();
				//var cntI = 0;
				//var cntE = 0;
				//var cntD = 0;

				////posidx == -1인 데이터는 모두 소거한다
				//var dellist = ds1.MCModel.Where(t => t.pidx == dr.idx && t.MotIndex == this.axisIndex && t.PosIndex == -1).ToList();    //메인목록은 남겨둔다
				//cntD += dellist.Count();
				//foreach (var item in dellist)
				//	item.Delete();
				//ds1.MCModel.AcceptChanges();

				////모든데이터의 체크상태를 off한다.
				//var alllist = this.ds1.MCModel.Where(t => t.pidx == dr.idx && t.MotIndex == this.axisIndex);
				//foreach (var item in alllist)
				//	item.Check = false;
				//ds1.MCModel.AcceptChanges();

				//for (int i = 0; i < list.Length; i++)
				//{
				//	var arrTitle = list[i];
				//	var vv = val.GetValue(i);
				//	var arrIndex = (byte)vv;// ((eAxis)(val.GetValue(i)));
				//	if (arrIndex < 50) continue;     //여기는 예약된 위치값이므로 사용하지 않는다
				//	var targetem = Enum.Parse(axType, vv.ToString());

				//	//이 값이 데이터가 없다면 추가하고, 있다면 이름을 검사해서 결과를 안내한다
				//	var pDr = this.ds1.MCModel.Where(t => t.pidx == dr.idx && t.PosIndex == arrIndex && t.MotIndex == axisIndex).FirstOrDefault();
				//	if (pDr == null)
				//	{
				//		//cntI += 1;
				//		//var newdr = this.ds1.MCModel.NewMCModelRow();

				//		//if (ds1.MCModel.Rows.Count == 0) newdr.idx = 1;
				//		//else newdr.idx = ds1.MCModel.Max(t => t.idx) + 1;

				//		//newdr.pidx = dr.idx;
				//		//newdr.MotIndex = this.axisIndex;
				//		//newdr.PosIndex = (short)arrIndex;
				//		//newdr.PosTitle = arrTitle;
				//		//newdr.Position = 0.0;
				//		//newdr.Speed = 50;
				//		//newdr.SpeedAcc = 100;
				//		//newdr.Check = true;
				//		//newdr.Description = targetem.DescriptionAttr();
				//		//newdr.Category = targetem.CategoryAttr();

				//		//this.ds1.MCModel.AddMCModelRow(newdr);
				//		//newdr.EndEdit();
				//		//sb.AppendLine("항목 추가 : " + arrTitle);
				//	}
				//	else
				//	{
				//		//이름이 다르다면 추가해준다.
				//		//if (pDr.PosTitle != arrTitle)
				//		//{
				//		//	sb.AppendLine("(위치)항목 변경 : " + pDr.PosTitle + " => " + arrTitle);
				//		//	cntE += 1;
				//		//	pDr.PosTitle = arrTitle;
				//		//}
				//		////pDr.Description = targetem.DescriptionAttr();
				//		////pDr.Category = targetem.CategoryAttr();
				//		//pDr.EndEdit();

				//		pDr.Check = true;
				//	}
				//}

				////미사용개체 삭제한다

				////var NotUseList = this.ds1.MCModel.Where(t => t.pidx == dr.idx && t.MotIndex == this.axisIndex && t.Check == false).ToList();
				////cntD += NotUseList.Count();
				////foreach (var item in NotUseList)
				////	item.Delete();
				//ds1.MCModel.AcceptChanges();

				//if (cntI > 0) sb.AppendLine("추가수량 : " + cntI.ToString());
				//if (cntE > 0) sb.AppendLine("변경수량 : " + cntE.ToString());
				//if (cntD > 0) sb.AppendLine("삭제수량 : " + cntD.ToString());

				////최종 확정
				//this.ds1.MCModel.AcceptChanges();

				//if (sb.Length > 0)
				//{
				//	Util.MsgI(sb.ToString());
				//}
			}
		}

		private void chkJogMoveForce_Click(object sender, EventArgs e)
		{

		}

		private void btAdd_Click(object sender, EventArgs e)
		{
			var newdr = this.ds1.MCModel.NewMCModelRow();// this.bs.AddNew() as DataRowView;
			newdr["Title"] = DateTime.Now.ToShortDateString();
			newdr["pidx"] = -1;
			newdr.PosIndex = -1;
			newdr["idx"] = this.ds1.MCModel.Rows.Count + 1;
			this.ds1.MCModel.AddMCModelRow(newdr);
			this.bs.Position = this.bs.Count - 1;

			//모터축을 자동 선택해줌
			//radClick_MotAxisSelect(this.flowLayoutPanel1.Controls[0], null);
		}

		private void btDel_Click(object sender, EventArgs e)
		{
			var drv = this.bs.Current as DataRowView;
			if (drv == null) return;
			var dlg = UTIL.MsgQ("Do you want to delete the currently selected data?");
			if (dlg != System.Windows.Forms.DialogResult.Yes) return;
			bs.RemoveCurrent();
			this.ds1.MCModel.AcceptChanges();
		}

		private void btSave_Click(object sender, EventArgs e)
		{
			//button - save
			this.dv.Focus();
			this.Validate();
			this.bs.EndEdit();
			this.bsPos.EndEdit();
			this.Validate();

			this.DialogResult = DialogResult.OK;

		}

		private void button2_Click(object sender, EventArgs e)
		{
			//select
			this.Invalidate();
			this.bs.EndEdit();
			var drv = this.bs.Current as DataRowView;
			if (drv == null) return;
			var dr = drv.Row as DataSet1.MCModelRow;
			if (dr.Title == "") return;
			this.Value = dr.Title;
			DialogResult = System.Windows.Forms.DialogResult.OK;
		}

		private void button6_Click(object sender, EventArgs e)
		{
			//적용

			this.bs.EndEdit();
			this.bsPos.EndEdit();
			this.Validate();

			var drv = this.bs.Current as DataRowView;
			if (drv == null) return;
			var dr = drv.Row as DataSet1.MCModelRow;

			this.Value = dr.Title;

			PUB.Result.mModel.ReadValue(dr.Title, this.ds1.MCModel);
			if (PUB.Result.mModel.isSet)
			{
				PUB.log.AddAT("Motion model selection completed: " + PUB.Result.mModel.Title);
			}
			else UTIL.MsgE("Apply failed\n\nTarget model name not found");
		}

		private void button4_Click(object sender, EventArgs e)
		{
			var drv = this.bs.Current as DataRowView;
			if (drv == null) return;
			var dr = drv.Row as DataSet1.MCModelRow;
			var dlg = UTIL.MsgQ(string.Format("Do you want to copy the following model information?\n\nModel name: {0}", dr.Title));
			if (dlg != System.Windows.Forms.DialogResult.Yes) return;

			var newdr = this.ds1.MCModel.NewMCModelRow();
			UTIL.CopyData(dr, newdr);
			newdr.Title += "-copy-";
			newdr.idx = this.ds1.MCModel.OrderByDescending(t => t.idx).FirstOrDefault().idx + 1;
			newdr.EndEdit();
			this.ds1.MCModel.AddMCModelRow(newdr);
			if (this.bs.Count > 0) this.bs.Position = this.bs.Count - 1;
		}

		private void arDatagridView2_CellClick(object sender, DataGridViewCellEventArgs e)
		{
			//position click
			var dv = sender as DataGridView;
			var col = this.dvPosition.Columns[e.ColumnIndex];
			var colName = col.Name.ToLower();
			if (colName == "btgo")
			{
				if (PUB.mot.HasHomeSetOff)
				{
					UTIL.MsgE("Motion homing not completed\nPlease run 'Device Initialization' from the main screen");
					return;
				}
				//현재값으로 모터를 이동
				//현재위치값으로 설정
				var cell = dv.Rows[e.RowIndex].Cells["btpos"];
				var value = (double)cell.Value;
				var drv = this.bsPos.Current as DataRowView;
				var drParent = drv.Row as DataSet1.MCModelRow;

				//일반 속도값을 찾는다
				//var speedDr = drParent.Speed;//  this.ds1.MCModel.Where(t => t.pidx == drParent.idx && t.MotIndex == axisIndex && t.PosIndex == -1 && t.SpdIndex == (int)eAxisSpeed.Normal).FirstOrDefault();
				var speed = drParent.Speed;// speedDr.Speed;// (double)this.nudJogVel.Value;
				var acc = drParent.SpeedAcc;// speedDr.SpeedAcc;// ;  (double)nudAcc.Value;


				var relative = false;
				//if (ctl.motCommand == arFrame.Control.MotCommandButton.eCommand.RelativeMove)
				//    relative = true;

				var msg = string.Format("모션의 위치를 변경 하시겠습니까\n" +
					"축 : {0}\n" +
					"현재위치 : {1}\n" +
					"대상위치 : {2}\n" +
					"이동속도 : {3}(가속도:{4})\n" +
					"이동 시 충돌 가능성이 있는지 반드시 확인 하세요", axis, PUB.mot.GetActPos(axisIndex), value, speed, acc);

				if (UTIL.MsgQ(msg) != System.Windows.Forms.DialogResult.Yes) return;

				var chkJogMoveForce = true;
				if (!MOT.Move(axis, value, speed, acc, relative, !chkJogMoveForce, !chkJogMoveForce))
					PUB.log.AddE("MOT:MOVE_:" + axis.ToString() + ",Msg=" + PUB.mot.ErrorMessage);



			}
			else if (colName == "btset")
			{
				if (PUB.mot.HasHomeSetOff)
				{
					UTIL.MsgE("Motion homing not completed\nPlease run 'Device Initialization' from the main screen");
					return;
				}

				//현재위치값으로 설정
				var cell = dv.Rows[e.RowIndex].Cells["btpos"];
				var value = (double)cell.Value;
				var nValue = Math.Round(PUB.mot.GetCmdPos(this.axisIndex), 4); //소수점4자리에서 반올림처리한다 210414

				var msg1 = string.Format("모션의 설정값을 변경 하시겠습니까\n" +
					   "축 : {0}\n" +
					   "변경전 : {1}\n" +
					   "변경후 : {2}\n" +
					   "변경 후 '저장'을 눌러야 영구 기록 됩니다", this.axis, value, nValue);

				if (UTIL.MsgQ(msg1) != System.Windows.Forms.DialogResult.Yes) return;
				cell.Value = nValue;
			}
			else if (colName == "btpos")
			{
				//현재값 변경 팝업
				var cell = dv.Rows[e.RowIndex].Cells[e.ColumnIndex];
				var value = (double)cell.Value;
				value = PUB.ChangeValuePopup(value, "위치 입력");
				cell.Value = value;
			}
			else if (colName == "btspeed")
			{
				//현재값 변경 팝업
				var cell = dv.Rows[e.RowIndex].Cells[e.ColumnIndex];
				var value = (double)cell.Value;
				value = PUB.ChangeValuePopup(value, "속도 입력");
				cell.Value = value;
			}
			else if (colName == "btacc")
			{
				//현재값 변경 팝업
				var cell = dv.Rows[e.RowIndex].Cells[e.ColumnIndex];
				var value = (double)cell.Value;
				value = PUB.ChangeValuePopup(value, "가속도 입력");
				cell.Value = value;
			}
			else if (colName == "btdcc")
			{
				//현재값 변경 팝업
				var cell = dv.Rows[e.RowIndex].Cells[e.ColumnIndex];
				if (cell.Value.ToString().isEmpty()) cell.Value = "0";
				var value = (double)cell.Value;
				value = PUB.ChangeValuePopup(value, "감속도 입력");
				cell.Value = value;
			}

		}


		private void toolStripButton1_Click(object sender, EventArgs e)
		{
			var dlg = UTIL.MsgQ("Do you want to batch change the speed of all movement coordinates?");
			if (dlg != System.Windows.Forms.DialogResult.Yes) return;
			var value = PUB.ChangeValuePopup(100.0, "일괄 속도 변경");

			for (int i = 0; i < this.bsPos.Count; i++)
			{
				this.bsPos.Position = i;
				var drv = this.bsPos.Current as DataRowView;
				if (drv == null) return;
				var dr = drv.Row as DataSet1.MCModelRow;
				dr.Speed = value;
				dr.EndEdit();
			}
		}

		private void toolStripButton2_Click_2(object sender, EventArgs e)
		{
			var dlg = UTIL.MsgQ("Do you want to batch change the acceleration/deceleration of all movement coordinates?");
			if (dlg != System.Windows.Forms.DialogResult.Yes) return;
			var value = PUB.ChangeValuePopup(100.0, "일괄 가(감)속도 변경");

			for (int i = 0; i < this.bsPos.Count; i++)
			{
				this.bsPos.Position = i;
				var drv = this.bsPos.Current as DataRowView;
				if (drv == null) return;
				var dr = drv.Row as DataSet1.MCModelRow;
				dr.SpeedAcc = value;
				dr.EndEdit();
			}
		}

		private void toolStripButton3_Click_1(object sender, EventArgs e)
		{
			var dlg = UTIL.MsgQ("Do you want to batch change the deceleration of all movement coordinates?");
			if (dlg != System.Windows.Forms.DialogResult.Yes) return;
			var value = PUB.ChangeValuePopup(0, "일괄 감속도 변경");

			for (int i = 0; i < this.bsPos.Count; i++)
			{
				this.bsPos.Position = i;
				var drv = this.bsPos.Current as DataRowView;
				if (drv == null) return;
				var dr = drv.Row as DataSet1.MCModelRow;
				dr.SpeedDcc = value;
				dr.EndEdit();
			}
		}

		
		private void dvMot_SelectionChanged(object sender, EventArgs e)
		{
			if (dvMot.SelectedRows.Count < 1)
			{
				Console.WriteLine("no selecte");
				this.axisIndex = -1;
				this.axis = (eAxis)axisIndex;
			}
			else
			{
				var selrow = dvMot.SelectedRows[0];
				this.axisIndex = short.Parse(selrow.Cells["dvc_axis"].Value.ToString());
				this.axis = (eAxis)axisIndex;
				MotAxisSelect(this.axisIndex);
				Console.WriteLine($"select indx {axisIndex}");
			}


		}


		private void toolStripButton5_Click(object sender, EventArgs e)
		{
			this.Validate();
			this.bs.EndEdit();
			this.bsPos.EndEdit();

			//using (var f = new Dialog.Motion_MoveToGroup(this.ds,arLabel18.Text))
			//{
			//	if (f.ShowDialog() == DialogResult.OK)
			//	{
			//		this.bs.EndEdit();
			//		this.bsPos.EndEdit();
			//	}
			//}

		}

		void refreshtreen()
		{
			//모든데이터를 가져와서 트리뷰를 처리한다.

			var cat = this.ds.MCModel.GroupBy(t => t.Category).ToList();
			var catorders = cat.OrderBy(t => t.Key).ToList();

			//var cnt = 0;
			this.treeView1.Nodes.Clear();
			foreach (var item in catorders)
			{
				if (item.Key.isEmpty()) continue;
				var catenames = item.Key.Split(',');
				foreach (var catename in catenames)
				{
					var grpname = catename.Split('|')[0];
					if (catename.Split('|').Length < 2) continue;
					var itemname = catename.Split('|')[1];
					if (treeView1.Nodes.ContainsKey(grpname) == false)
					{
						var nd = treeView1.Nodes.Add(grpname, grpname);
						nd.Nodes.Add(itemname);
					}
					else
					{
						if (itemname.StartsWith("F01"))// == "F01_FSOCKET_BTM")
						{

						}
						var nd = treeView1.Nodes[grpname];
						if (nd.Nodes.ContainsKey(itemname) == false)
						{
							var snd = nd.Nodes.Add(itemname, itemname);
							if (itemname.StartsWith("R"))
								snd.ForeColor = Color.Blue;
							else if (itemname.StartsWith("T"))
								snd.ForeColor = Color.Magenta;
						}
						else
						{
							var snd = nd.Nodes[itemname];
							if (itemname.StartsWith("R"))
								snd.ForeColor = Color.Blue;
							else if (itemname.StartsWith("T"))
								snd.ForeColor = Color.Magenta;
						}
					}
				}


			}

			treeView1.ExpandAll();
			if (treeView1.Nodes.Count > 0)
				treeView1.SelectedNode = this.treeView1.Nodes[0];

		}
		void refreshlist()
		{
			this.listView1.Clear();
			this.listView1.FullRowSelect = true;
			this.listView1.View = View.Details;
			this.listView1.Columns.Add("item");
			this.listView1.Columns[0].Width = (int)(this.listView1.Width - listView1.Width * 0.1f);
			this.listView1.GridLines = true;
			this.listView1.AllowDrop = true;


			var drv = this.bsPos.Current as DataRowView;
			if (drv == null) return;
			var dr = drv.Row as DataSet1.MCModelRow;
			if (dr.Category.isEmpty()) return;

			var catelist = dr.Category.Split(',');
			List<string> cats = new List<string>();


			foreach (var cate in catelist)
			{
				if (cate.isEmpty()) continue;
				if (cats.Contains(cate) == false) cats.Add(cate);
			}

			foreach (var cate in cats.OrderBy(t=>t))
			{
				if (this.listView1.Items.ContainsKey(cate) == false)
				{
					var lv = this.listView1.Items.Add(cate, cate, 0);
				}
				else
				{
					//이미 있다.
				}
			}
	

		}
		private void bsPos_CurrentChanged(object sender, EventArgs e)
		{
			//포지션데이터가 움직이면 처리한다.
			refreshlist();
		}

		private void toolStripButton1_Click_1(object sender, EventArgs e)
		{
			//트립에서 선택된 아이템을 추가한다.
			var tn = this.treeView1.SelectedNode;
			if (tn == null) return;
			if (tn.Level != 1)
			{
				if (tn.Nodes.Count < 1)
				{
					UTIL.MsgE("No sub items found");
					return;
				}

				var dlg = UTIL.MsgQ($"Do you want to add all {tn.Nodes.Count} data items?");
				if (dlg != DialogResult.Yes) return;
				var ucnt = 0;
				foreach (TreeNode node in tn.Nodes)
				{
					var value = node.Parent.Text + "|" + node.Text;
					if (this.listView1.Items.ContainsKey(value) == false)
					{
						this.listView1.Items.Add(value);
						ucnt += 1;
					}
				}
				UTIL.MsgI($"{ucnt} items have been added");
				//현재목록을 리스트로 만들고 업데이트한.ㄷ
				var drv = this.bsPos.Current as DataRowView;
				var dr = drv.Row as DataSet1.MCModelRow;

				List<string> items = new List<string>();

				foreach (ListViewItem item in listView1.Items)
					items.Add(item.SubItems[0].Text);

				dr.Category = string.Join(",", items);
				dr.EndEdit();
			}
			else
			{
				var value = tn.Parent.Text + "|" + tn.Text;
				if (this.listView1.Items.ContainsKey(value) == false)
				{
					this.listView1.Items.Add(value);
					//현재목록을 리스트로 만들고 업데이트한.ㄷ
					var drv = this.bsPos.Current as DataRowView;
					var dr = drv.Row as DataSet1.MCModelRow;

					List<string> items = new List<string>();

					foreach (ListViewItem item in listView1.Items)
						items.Add(item.SubItems[0].Text);

					dr.Category = string.Join(",", items);
					dr.EndEdit();

				}
				else UTIL.MsgE("This item already exists.");
			}



		}

		private void toolStripButton2_Click(object sender, EventArgs e)
		{
			//선택된 항목을 삭제한다.
			if (this.listView1.FocusedItem == null) return;
			this.listView1.Items.Remove(this.listView1.FocusedItem);

			//현재목록을 리스트로 만들고 업데이트한.ㄷ
			var drv = this.bsPos.Current as DataRowView;
			var dr = drv.Row as DataSet1.MCModelRow;

			List<string> items = new List<string>();

			foreach (ListViewItem item in listView1.Items)
				items.Add(item.SubItems[0].Text);

			dr.Category = string.Join(",", items);
			dr.EndEdit();
		}

		private void toolStripButton3_Click(object sender, EventArgs e)
		{
			refreshlist();
		}

		private void toolStripButton4_Click(object sender, EventArgs e)
		{
			//현재선택된 아이템의 데이터를 표시한다.
			var tn = this.treeView1.SelectedNode;
			if (tn == null) return;
			if (tn.Level == 0)
			{
				bsPos.Filter = $"Category like '%{tn.Text}|%'";
			}
			else
			{
				bsPos.Filter = $"Category like '%{tn.Parent.Text}|{tn.Text}%'";
			}
		}

		private void toolStripButton6_Click(object sender, EventArgs e)
		{

		}

		private void toolStripButton7_Click(object sender, EventArgs e)
		{
			refreshtreen();
		}

		private void toolStripButton8_Click(object sender, EventArgs e)
		{

			var tn = treeView1.SelectedNode;
			if (tn == null) return;

			var old = tn.Text.Trim();
			var f = new AR.Dialog.fInput("입력",tn.Text);
			if (f.ShowDialog() != DialogResult.OK) return;

			if (f.ValueString.isEmpty()) return;
			var targetidx = tn.Level;

			foreach (DataSet1.MCModelRow dr in this.ds.MCModel.Rows)
			{
				if (dr.RowState == DataRowState.Deleted || dr.RowState == DataRowState.Detached) continue;

				if (dr.Category.isEmpty()) continue;

				var cats = dr.Category.Split(',');
				List<string> items = new List<string>();
				foreach (var cat in cats)
				{
					if (cat.isEmpty()) continue;

					var buffer = cat.Split('|');

					if (targetidx == 0)
					{
						buffer[targetidx] = buffer[targetidx].Replace(old, f.ValueString);
					}
					else
					{
						//1번의 경우 변경을 하려면 0번이 일치해야한다.
						if (buffer[0] == tn.Parent.Text)
						{
							buffer[targetidx] = buffer[targetidx].Replace(old, f.ValueString);
						}
					}

					items.Add(string.Join("|", buffer));
				}

				dr.Category = string.Join(",", items.ToArray());
				dr.EndEdit();
			}

			refreshtreen();
		}

		private void toolStripButton9_Click(object sender, EventArgs e)
		{
			dvPosition.AutoResizeColumns();
		}
	}
}

