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 fPickerMove : Form
	{
		public fPickerMove()
		{
			InitializeComponent();
			this.FormClosing += FPickerMove_FormClosing;
		}
		private void fPickerMove_Load(object sender, EventArgs e)
		{
			Pub.flag.set(eFlag.MOVE_PICKER, true, "PICKERMOVE");
			timer1.Start();
		}
		private void FPickerMove_FormClosing(object sender, FormClosingEventArgs e)
		{
			if(ManPosL)
			{
				Util.MsgE("프린터측 모션이 관리위치에 있습니다\n위치를 복귀 한 후 다시 시도하세요", true);
				e.Cancel = true;
				return;
			}
			Pub.flag.set(eFlag.MOVE_PICKER, false, "PICKERMOVE");
			timer1.Stop();
		}

		Boolean CheckSafty()
		{
			if (Util_DO.isSaftyDoorF() == false)
			{
				Util.MsgE("전면 도어가 열려 있습니다");
				return false;
			}

			if (Pub.mot.hasHomeSetOff)
			{
				Util.MsgE("모션의 홈 작업이 완료되지 않았습니다");
				return false;
			}
			return true;
		}

		private void button3_Click(object sender, EventArgs e)
		{
			if (CheckSafty() == false) return;
			var p1 = Util_Mot.GetAxPXPos(eAxisPXPos.PICKOFFL);
			Util_Mot.Move(eAxis.X_PICKER, p1.position, 250, p1.acc, false, false, false);
			DialogResult = DialogResult.OK;
		}

		private void button1_Click(object sender, EventArgs e)
		{
			if (CheckSafty() == false) return;
			var p1 = Util_Mot.GetAxPXPos(eAxisPXPos.READYL);
			Util_Mot.Move(eAxis.X_PICKER, p1.position, 250, p1.acc, false, false, false);
			DialogResult = DialogResult.OK;
		}

		private void button2_Click(object sender, EventArgs e)
		{
			if (CheckSafty() == false) return;
			var p1 = Util_Mot.GetAxPXPos(eAxisPXPos.PICKON);
			Util_Mot.Move(eAxis.X_PICKER, p1.position, 250, p1.acc, false, false, false);
			DialogResult = DialogResult.OK;
		}

		private void button4_Click(object sender, EventArgs e)
		{
			if (CheckSafty() == false) return;
			var p1 = Util_Mot.GetAxPXPos(eAxisPXPos.READYR);
			Util_Mot.Move(eAxis.X_PICKER, p1.position, 250, p1.acc, false, false, false);
			DialogResult = DialogResult.OK;
		}

		private void button5_Click(object sender, EventArgs e)
		{
			if (CheckSafty() == false) return;
			var p1 = Util_Mot.GetAxPXPos(eAxisPXPos.PICKOFFR);
			Util_Mot.Move(eAxis.X_PICKER, p1.position, 250, p1.acc, false, false, false);
			DialogResult = DialogResult.OK;
		}

		private void button8_Click(object sender, EventArgs e)
		{
			Pub.mot.MoveStop("pmove", (int)eAxis.X_PICKER);
		}

		private void button6_Click(object sender, EventArgs e)
		{
			//jog left
		}

		private void button7_Click(object sender, EventArgs e)
		{
			//jog right
		}

		private void button6_MouseDown(object sender, MouseEventArgs e)
		{
			//조그시작
			var bt = sender as Button;
			if (bt.Text.Contains( "<<")) Pub.mot.JOG((short)eAxis.X_PICKER, arDev.AzinAxt.eMotionDirection.Negative);
			else Pub.mot.JOG((short)eAxis.X_PICKER, arDev.AzinAxt.eMotionDirection.Positive);
		}

		private void button6_MouseUp(object sender, MouseEventArgs e)
		{
			//마우스 놓으면 멈춤
			Pub.mot.MoveStop("pmove", (short)eAxis.X_PICKER);
		}

		private void button9_Click(object sender, EventArgs e)
		{

			//왼쪽검증취소
		//	if (Pub.flag.get(eFlag.RDY_VISION0) == false) return;
			var dlg = Util.MsgQ("QR코드 검증을 취소할까요?");
			if (dlg != DialogResult.Yes) return;

			Pub.flag.set(eFlag.RDY_VISION0, false, "CANCEL");
			Pub.flag.set(eFlag.PORTL_ITEMON, false, "CANCEL");
			Pub.ResetRunStepSeq(eRunSequence.VISION0);
			Pub.UpdaterunStepSeqStartTime(eRunSequence.COM_VS0);
			Pub.log.Add(string.Format("QR검증({0}) 취소 JGUID={1}", "L", Pub.Result.ItemData[0].guid));
			UpdateDatabase(0);
			DialogResult = DialogResult.OK;
		}

		private void button10_Click(object sender, EventArgs e)
		{
			//왼쪽검증취소
			//if (Pub.flag.get(eFlag.RDY_VISION0) == false) return;
			var dlg = Util.MsgQ("QR코드 검증을 취소할까요?");
			if (dlg != DialogResult.Yes) return;

			Pub.flag.set(eFlag.RDY_VISION2, false, "CANCEL");
			Pub.flag.set(eFlag.PORTR_ITEMON, false, "CANCEL");
			Pub.ResetRunStepSeq(eRunSequence.VISION2);
			Pub.UpdaterunStepSeqStartTime(eRunSequence.COM_VS2);
			Pub.log.Add(string.Format("QR검증({0}) 취소 JGUID={1}", "R", Pub.Result.ItemData[2].guid));

			UpdateDatabase(2);
			DialogResult = DialogResult.OK;
		}

		void UpdateDatabase(int vidx)
		{
			//취소상태를 DB에도 남긴다.
			using (var db = new EEEntities())
			{
				var itemdata = Pub.Result.ItemData[vidx];
				var dr = db.Component_Reel_Result.AsNoTracking().Where(t => t.JGUID == itemdata.guid).FirstOrDefault();
				if (dr == null)
				{
					var ermsg = string.Format("다음 guid 를 찾을수 없어 검증취소 를 변경하지 못함 vidx={2},guid={0},sid={1}", itemdata.guid, itemdata.VisionData.SID, vidx);
					Pub.AddDebugLog(ermsg, true);
					Pub.log.AddE(ermsg);
				}
				else
				{
					dr.ANGLE = itemdata.VisionData.ApplyAngle; //210331 - 도중에 사용자 angle 이 있다면 그것이 적용되었음
					dr.PRNVALID = false;
					dr.REMARK = "검증취소";
					db.SaveChanges();
				}
			}
		}

		private void button11_Click(object sender, EventArgs e)
		{
			//관리위치L
			MoveMangePos(0);
		}

		private void button13_Click(object sender, EventArgs e)
		{
			//관리위치
			MoveMangePos(2);
		}

		Boolean ManPosL = false;

		void MoveMangePos(int vidx)
		{
			if (Pub.sm.Step != StateMachine.eSMStep.IDLE)
			{
				Util.MsgE("대기상태에서만 사용 가능 합니다");
				return;
			}
			var Xpos = Util_Mot.GetPKX_PosName();
			if (Xpos != ePickYPosition.PICKON)
			{
				Util.MsgE("피커위치가 중앙에서만 사용 가능 합니다");
				return;
			}

			Task.Run(new Action(() =>
			{
				//Z축을 Ready 위치로 이동한다.
				if (vidx == 0)
				{
					var zPos = Util_Mot.GetAxPLZPos(eAxisPLUPDNPos.READY);
					Util_Mot.Move(eAxis.PL_UPDN, zPos.position, zPos.speed, zPos.acc);
					while (Util_Mot.GetPLZ_PosName() != ePrintZPosition.READY)
						System.Threading.Thread.Sleep(10);

					var mPos = Util_Mot.GetAxPLMPos(eAxisPLMovePos.PRINTL07);
					Util_Mot.Move(eAxis.PL_MOVE, mPos.position, mPos.speed, mPos.acc);
					while (Util_Mot.GetPLM_PosName() != ePrintYPosition.PRINTL07)
						System.Threading.Thread.Sleep(10);

					var zPos2 = Util_Mot.GetAxPLZPos(eAxisPLUPDNPos.PICKOFF);
					var tPos = (zPos2.position / 2f);
					Util_Mot.Move(eAxis.PL_UPDN, tPos, zPos.speed, zPos.acc);
					ManPosL = true;
				}
				else
				{
					var zPos = Util_Mot.GetAxPRZPos(eAxisPRUPDNPos.READY);
					Util_Mot.Move(eAxis.PR_UPDN, zPos.position, zPos.speed, zPos.acc);
					while (Util_Mot.GetPRZ_PosName() != ePrintZPosition.READY)
						System.Threading.Thread.Sleep(10);

					var mPos = Util_Mot.GetAxPRMPos(eAxisPRMovePos.PRINTL07);
					Util_Mot.Move(eAxis.PR_MOVE, mPos.position, mPos.speed, mPos.acc);
					while (Util_Mot.GetPRM_PosName() != ePrintYPosition.PRINTL07)
						System.Threading.Thread.Sleep(10);

					var zPos2 = Util_Mot.GetAxPRZPos(eAxisPRUPDNPos.PICKOFF);
					var tPos = (zPos2.position / 2f);
					Util_Mot.Move(eAxis.PR_UPDN, tPos, zPos.speed, zPos.acc);
					//ManPosR = true;
				}

			}));
		}

		private void button12_Click(object sender, EventArgs e)
		{
			var Xpos = Util_Mot.GetPKX_PosName();
			if (Xpos != ePickYPosition.PICKON)
			{
				Util.MsgE("피커위치가 중앙에서만 사용 가능 합니다");
				return;
			}

			//위치복귀
			PosRecover(0);
			PosRecover(2);
		}

		void PosRecover(int vidx)
		{
			Task.Run(new Action(() =>
			{
				//Z축을 Ready 위치로 이동한다.
				if (vidx == 0)
				{
					var zPos = Util_Mot.GetAxPLZPos(eAxisPLUPDNPos.READY);
					Util_Mot.Move(eAxis.PL_UPDN, zPos.position, zPos.speed, zPos.acc);
					while (Util_Mot.GetPLZ_PosName() != ePrintZPosition.READY)
						System.Threading.Thread.Sleep(10);

					var mPos = Util_Mot.GetAxPLMPos(eAxisPLMovePos.READY);
					Util_Mot.Move(eAxis.PL_MOVE, mPos.position, mPos.speed, mPos.acc);
					while (Util_Mot.GetPLM_PosName() != ePrintYPosition.READY)
						System.Threading.Thread.Sleep(10);

					
					ManPosL = false;
				}
				else
				{
					var zPos = Util_Mot.GetAxPRZPos(eAxisPRUPDNPos.READY);
					Util_Mot.Move(eAxis.PR_UPDN, zPos.position, zPos.speed, zPos.acc);
					while (Util_Mot.GetPRZ_PosName() != ePrintZPosition.READY)
						System.Threading.Thread.Sleep(10);

					var mPos = Util_Mot.GetAxPRMPos(eAxisPRMovePos.READY);
					Util_Mot.Move(eAxis.PR_MOVE, mPos.position, mPos.speed, mPos.acc);
					while (Util_Mot.GetPRM_PosName() != ePrintYPosition.PRINTL07)
						System.Threading.Thread.Sleep(10);

					//ManPosR = false;
				}

			}));
		}

		private void timer1_Tick(object sender, EventArgs e)
		{
			//모션홈이 안잡혀있다면 이동 기능은 OFf한다
			btl.Enabled = !Pub.mot.hasHomeSetOff;
			btlw.Enabled = !Pub.mot.hasHomeSetOff;
			btc.Enabled = !Pub.mot.hasHomeSetOff;
			btrw.Enabled = !Pub.mot.hasHomeSetOff;
			btr.Enabled = !Pub.mot.hasHomeSetOff;

			this.button11.Enabled = !Pub.mot.hasHomeSetOff;
			this.button12.Enabled = !Pub.mot.hasHomeSetOff;
			this.button13.Enabled = !Pub.mot.hasHomeSetOff;

			this.button8.BackColor = Util_DO.GetIOInput(eDIName.PICKER_SAFE) ? Color.Lime : Color.Tomato;


		}

		private void button2_Click_1(object sender, EventArgs e)
		{
			Pub.PrinterL.TestPrint( Pub.setting.DrawOutbox,"","",Pub.setting.STDLabelFormat7);
			Pub.log.Add("임시프린트L:" + Pub.PrinterL.LastPrintZPL);
		}

		private void button4_Click_1(object sender, EventArgs e)
		{
			Pub.PrinterR.TestPrint(Pub.setting.DrawOutbox, "", "", Pub.setting.STDLabelFormat7);
			Pub.log.Add("임시프린트R:" + Pub.PrinterR.LastPrintZPL);
		}
	}
}
