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 NetOffice;
using Outlook = NetOffice.OutlookApi;
using NetOffice.OutlookApi.Enums;

namespace FBS0000
{
	public partial class fyeonchastate : FCOMMON.fBase
	{
		string fn_fpcolsize = "";
		public fyeonchastate()
		{
			InitializeComponent();
			Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
			fn_fpcolsize = System.IO.Path.Combine(FCOMMON.Util.CurrentPath, "formSetting", "fp_" + this.Name + "i.ini");
			this.dsMSSQL.vHoliday_uselist.TableNewRow += Holyday_TableNewRow;
			//this.dv1.CellFormatting += dv1_CellFormatting;
		}

		void dv1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
		{
			//if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
			//var col = this.dv1.Columns[e.ColumnIndex];
			//var cate = dv1.Rows[e.RowIndex].Cells["dvc_cate"].Value.ToString();
			//if (cate == "0") dv1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Blue;// = Color.Gray;
			//else dv1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
		}
      

        private void __Load(object sender, EventArgs e)
		{
			EnsureVisibleAndUsableSize();
			int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.holyday));
			//엔터키누르면 아래로 이동하게함ㄷ
			FarPoint.Win.Spread.InputMap im = this.fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused);
			FarPoint.Win.Spread.InputMap im2 = this.fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused);
			im.Put(new FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextColumnWrap);
			im2.Put(new FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextColumnWrap);

			dtSD.Text = DateTime.Now.ToString("yyyy") + "-01-01";
			dtED.Text = DateTime.Parse(DateTime.Now.AddMonths(1).ToString("yyyy-MM") + "-01").AddDays(-1).ToString("yyyy-MM-dd");

			//현재 사용자의 그룹명을 가져옴
			var taQuery = new dsMSSQLTableAdapters.QueriesTableAdapter();
			var GrpName = taQuery.GetGrpName(FCOMMON.info.Login.gcode, FCOMMON.info.Login.no);


			//그룹목록
			//var taGrp = new dsMSSQLTableAdapters.WorkTableGrpTableAdapter();
			//var dtGrp = taGrp.GetData(FCOMMON.info.Login.gcode);
			//this.cmbGrp.Items.Clear();
			//foreach (var item in dtGrp)
			//{
			//    cmbGrp.Items.Add(string.Format("{0}", item.grp));
			//}
			//if (string.IsNullOrEmpty(GrpName) == false) cmbGrp.Text = GrpName;
			//else if (cmbGrp.Items.Count > 0) cmbGrp.SelectedIndex = 0;

			UpdateUserList();

			//일반사용자의경우에는 상태를 변경하지 못한다.
			//int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.holyday));
			//curLevel = 5;
			if (curLevel >= 5)
			{
				//권한이 잇으므로 모든 사용자로 한다.
				//if (cmbUser.Items.Count > 0)
//					cmbUser.SelectedIndex = 0;
				//btSave.Enabled = true;
				//btDel.Enabled = true;
				//btAdd.Enabled = true;
				//복사ToolStripMenuItem.Enabled = true;
				//toolStripButton2.Enabled = true;
				//toolStripButton3.Enabled = true;
			}
			else
			{
                cmbUser.Enabled = false;
                toolStripLabel3.Enabled = false;
				//toolStripButton3.Enabled = false;
				//toolStripButton2.Enabled = false;
				//btSave.Enabled = false;
				//btDel.Enabled = false;
				//btAdd.Enabled = false;


				//this.cmbUser.Enabled = false;   //사용자를 고칠수 없게 한다.

			}
			//RefreshData();
		}

		void Holyday_TableNewRow(object sender, DataTableNewRowEventArgs e)
		{
			e.Row["wuid"] = FCOMMON.info.Login.no;
			e.Row["uid"] = FCOMMON.info.Login.no;
			e.Row["wdate"] = DateTime.Now;
			e.Row["cate"] = "0"; //기본 신청
			e.Row["pdate"] = DateTime.Now;
			e.Row["termDr"] = 1.0f;
			e.Row["contents"] = string.Empty;
		}

		string GetUIDValue()
		{
			string uid = "%";
			if (cmbUser.SelectedIndex > 0)
			{
				var si = cmbUser.Text.IndexOf("(");
				var ei = cmbUser.Text.LastIndexOf(")");
				uid = cmbUser.Text.Substring(si + 1, ei - si - 1);
			}
			return uid;
		}

		string seluid = string.Empty;
		void RefreshData()
		{
			if (this.dsMSSQL.Holyday.GetChanges() != null)
			{
				var dlg = FCOMMON.Util.MsgQ("변경된 내용이 있습니다. 새로고침하면 해당 자료가 손실됩니다\n진행하시겠습니까?");
				if (dlg != DialogResult.Yes) return;
			}

			//update data
			seluid = GetUIDValue();
			var sd = DateTime.Parse(dtSD.Text + " 00:00:00");
			var ed = DateTime.Parse(dtED.Text + " 23:59:59");
			//sd = DateTime.Parse(ed.ToString("yyyy-01-01 00:00:00"));
			//this.tbSD.Text = sd.ToString("yyyy-MM-dd");

			try
			{
				this.ta.Fill(this.dsMSSQL.Holyday, dtSD.Text, FCOMMON.info.Login.gcode, seluid, dtED.Text,"년차");
				this.dsMSSQL.Holyday.AcceptChanges();
			}
			catch (Exception ex)
			{
				FCOMMON.Util.MsgE(ex.Message);
			}


			//잔량계산
			double sumdrD = this.dsMSSQL.Holyday.Sum(t => t.termDr);    //전체발생수량
			double sumdrT = this.dsMSSQL.Holyday.Sum(t => t.DrTime);    //전체발생수량

			double sumcrD = this.dsMSSQL.Holyday.Sum(t => t.term);    //전체발생수량
			double sumcrT = this.dsMSSQL.Holyday.Sum(t => t.CrTime);    //전체발생수량

			//double sumcr = sumcrD + sumcrT; //전체 사용수량
			//double sumdr = sumdrD + sumdrT; //전체 발생량

			double janD = sumdrD - sumcrD;
			double janT = sumdrT - sumcrT;
			sbGen.Text = string.Format("{0}+{1}", sumdrD, sumdrT);  //발생량
			sbUse.Text = string.Format("{0}+{1}", sumcrD, sumcrT);  //사용량
			sbJan.Text = string.Format("{0}+{1}", janD, janT);  //잔량
			if (janD < 0) sbJan.ForeColor = Color.Red;
			else sbJan.ForeColor = Color.Blue;

			//현재그룹의 사용자 목록을 조호힌다.
			//taUser.Fill(this.dsMSSQL.EETGW_WorkTableUser, FCOMMON.info.Login.gcode, cmbGrp.Text);

			//모든데이터의 성명을 표시해준다
			var qta = new dsMSSQLTableAdapters.QueriesTableAdapter();
			var col_name = this.fpSpread1.ActiveSheet.Columns["name"].Index;
			var col_jand = this.fpSpread1.ActiveSheet.Columns["jand"].Index;
			//var col_yjand = this.fpSpread1.ActiveSheet.Columns["yjand"].Index;
			//var col_janh = this.fpSpread1.ActiveSheet.Columns["janh"].Index;
			//var col_yjanh = this.fpSpread1.ActiveSheet.Columns["yjanh"].Index;
			var col_src = this.fpSpread1.ActiveSheet.Columns["src"].Index;
			for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
			{
				var drindex = this.fpSpread1.ActiveSheet.GetModelRowFromViewRow(i);
				var dr = this.dsMSSQL.Holyday.Rows[drindex] as dsMSSQL.HolydayRow;
				this.fpSpread1.ActiveSheet.Cells[i, col_name].Value = dr.UserName;

				var fistdate = dr.sdate.ToString("yyyy-01-01");

				//이 사용자의 이전까지의 잔량을 가져온다
				var yjand = qta.WorkUserJan_Yesterday_Day(FCOMMON.info.Login.gcode, dr.uid, fistdate, dr.sdate.ToString("yyyy-MM-dd"), dr.idx.ToString("000000"),"년차");
				//var yjanh = qta.WorkUserJan_YesterDay_Time(FCOMMON.info.Login.gcode, dr.uid, fistdate, dr.sdate.ToString("yyyy-MM-dd"), dr.idx.ToString("000000"));
				var jand = yjand + dr.termDr - dr.term;
				//var janh = yjanh + dr.DrTime - dr.CrTime;
				this.fpSpread1.ActiveSheet.Cells[i, col_jand].Value = jand;
				//this.fpSpread1.ActiveSheet.Cells[i, col_yjanh].Value = yjanh;

				if (dr.extidx > 0 && string.IsNullOrEmpty(dr.extcate) == false)
				{
					if (dr.cate == "대체")
						this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Tomato;
					else if (dr.cate == "년차")
						this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Blue;
					else
						this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Black;

					this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.LightGray;
					this.fpSpread1.ActiveSheet.Rows[i].Locked = true;
				}
				//this.fpSpread1.ActiveSheet.Cells[i, col_src].Value = dr.ext;
				//this.fpSpread1.ActiveSheet.Cells[i, col_janh].Value = janh;
			}

			var sb = new System.Text.StringBuilder();

			var grplist = dsMSSQL.Holyday.GroupBy(t => t.cate).ToList();
			foreach (var grp in grplist)
			{
				//일년치합산을 넣는다
				//var totalJanH = grp.Sum(t => t.DrTime) - grp.Sum(t => t.CrTime);
				var totalJanD = grp.Sum(t => t.termDr) - grp.Sum(t => t.term);
				if (sb.Length > 0) sb.Append(" ");
				sb.Append($"[{grp.Key}] {totalJanD}");
			}
			//var tUseH = dsMSSQL.Holyday.Sum(t => t.CrTime);
			var tUseD = dsMSSQL.Holyday.Sum(t => t.term);

			//var tGenH = dsMSSQL.Holyday.Sum(t => t.DrTime);
			var tGenD = dsMSSQL.Holyday.Sum(t => t.termDr);

			this.sbUse.Text = $"{tUseD}";
			this.sbGen.Text = $"{tGenD}";
			this.sbJan.Text = sb.ToString();

			sbUse.ForeColor = Color.Blue;
			sbGen.ForeColor = Color.Black;
			sbJan.ForeColor = Color.DarkMagenta;

			this.bs.Filter = string.Empty;
			textBox1.BackColor = SystemColors.Control;
			textBox1.Text = string.Empty;
		}
		private void boardBindingNavigatorSaveItem_Click(object sender, EventArgs e)
		{
			this.Validate();
			this.bs.EndEdit();
			var dlg = FCOMMON.Util.MsgQ("변경된 내용을 저장하시겠습니까?");
			if (dlg != System.Windows.Forms.DialogResult.Yes) return;
			try
			{

			}
			catch (Exception ex)
			{
				FCOMMON.Util.MsgE(ex.Message);
			}
		}

		private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
		{
			var newdr = this.dsMSSQL.Holyday.NewHolydayRow();
			if (this.cmbUser.SelectedIndex == 0) newdr.uid = FCOMMON.info.Login.no;
			else newdr.uid = seluid;
			newdr.gcode = FCOMMON.info.Login.gcode;
			newdr.sdate = DateTime.Now;
			newdr.edate = DateTime.Now;
			newdr.contents = string.Empty;
			newdr.wuid = FCOMMON.info.Login.no;
			newdr.wdate = DateTime.Now;
			newdr.UserName = FCOMMON.info.Login.nameK;

			var f = new fHolyday_Add(newdr);
			if (f.ShowDialog() == DialogResult.OK)
			{
				newdr.EndEdit();
				this.dsMSSQL.Holyday.AddHolydayRow(newdr);
			}
			else newdr.Delete();



			//var rowindex = this.bs.Count - 1;



			////잔액및 성명찾기
			////모든데이터의 성명을 표시해준다
			//var qta = new dsMSSQLTableAdapters.QueriesTableAdapter();
			//var col_name = this.fpSpread1.ActiveSheet.Columns["name"].Index;
			//var col_jand = this.fpSpread1.ActiveSheet.Columns["jand"].Index;
			//var col_yjand = this.fpSpread1.ActiveSheet.Columns["yjand"].Index;
			//var col_janh = this.fpSpread1.ActiveSheet.Columns["janh"].Index;
			//var col_yjanh = this.fpSpread1.ActiveSheet.Columns["yjanh"].Index;

			//var drUser = this.dsMSSQL.EETGW_WorkTableUser.Where(t => t.empno == newdr.uid).FirstOrDefault();
			//var username = drUser == null ? string.Empty : drUser.name;
			//fpSpread1.ActiveSheet.Cells[rowindex, col_name].Value = username;

			////이 사용자의 이전까지의 잔량을 가져온다
			//var fistdate = newdr.sdate.ToString("yyyy-01-01");
			//var yjand = 0;// qta.WorkUserJan_Yesterday_Day(FCOMMON.info.Login.gcode, this.seluid, fistdate, newdr.sdate.ToString("yyyy-MM-dd"),"999999");
			//var yjanh = 0;// qta.WorkUserJan_YesterDay_Time(FCOMMON.info.Login.gcode, seluid, fistdate, newdr.sdate.ToString("yyyy-MM-dd"), "999999");



			////var jand = yjand + dr.termDr - dr.term;
			////var janh = yjanh + dr.DrTime - dr.CrTime;
			//this.fpSpread1.ActiveSheet.Cells[rowindex, col_yjand].Value = yjand;
			//this.fpSpread1.ActiveSheet.Cells[rowindex, col_yjanh].Value = yjanh;

		}

		private void autoResizeComlumnsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//  dv1.AutoResizeColumns();
		}

		private void dv1_DataError(object sender, DataGridViewDataErrorEventArgs e)
		{

		}

		private void dv1_DoubleClick(object sender, EventArgs e)
		{
			//var drv = this.bs.Current as DataRowView;
			//if (drv == null) return;
			//var dr = drv.Row as dsMSSQL.vHoliday_uselistRow;
			//var f = new fHolyday_Add(dr.idx);
			//if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			//{
			//    RefreshData();
			//}

		}

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

		private void tbSD_KeyDown(object sender, KeyEventArgs e)
		{
			var tb = sender as ToolStripTextBox;
			if (e.KeyCode == Keys.Enter)
			{
				string datestring;
				if (FCOMMON.Util.MakeDateString(tb.Text, out datestring))
				{
					tb.Text = datestring;
					SendKeys.Send("{TAB}");
				}
			}
		}

		private void sendToMailToolStripMenuItem_Click(object sender, EventArgs e)
		{
			var drv = this.bs.Current as DataRowView;
			if (drv == null) return;
			var dr = drv.Row as dsMSSQL.HolydayRow;

			//string to = dr.tolist;
			//string body = "<html><body>test 2<strong>sfd</strong>nice to meet</body></html>";
			//string bcc = string.Empty;
			//string cc = string.Empty;
			//string subject = "etst mail";

			Outlook.Application outlookApplication = new Outlook.Application();
			Outlook.MailItem newTask = outlookApplication.CreateItem(OlItemType.olMailItem) as Outlook.MailItem;
			newTask.Subject = "mail test";
			newTask.To = "Chikyun.Kim@amkor.co.kr";
			newTask.HTMLBody = "<i><b>this is test mail</b></i>";
			newTask.BodyFormat = OlBodyFormat.olFormatHTML;
			newTask.Display();

			//FCOMMON.Util.RunDefaultMail(to, subject, body, cc, bcc);
		}

		private void toolStripButton2_Click(object sender, EventArgs e)
		{
			this.Validate();
			this.bs.EndEdit();
			try
			{
				var cnt = this.ta.Update(this.dsMSSQL.Holyday);
				this.dsMSSQL.Holyday.AcceptChanges();
				FCOMMON.Util.MsgI(cnt.ToString() + "건의 자료가 저장됨");
			}
			catch (Exception ex)
			{
				FCOMMON.Util.MsgE(ex.Message);
			}
		}

		private void toolStripButton3_Click(object sender, EventArgs e)
		{
			var newdr = this.dsMSSQL.Holyday.NewHolydayRow();
			newdr.uid = FCOMMON.info.Login.no;
			newdr.gcode = FCOMMON.info.Login.gcode;
			newdr.sdate = DateTime.Now;
			newdr.edate = DateTime.Now;
			newdr.contents = string.Empty;
			newdr.wuid = FCOMMON.info.Login.no;
			newdr.wdate = DateTime.Now;
			this.dsMSSQL.Holyday.AddHolydayRow(newdr);
		}


		private void toolStripButton4_Click(object sender, EventArgs e)
		{
			if (this.cmbUser.SelectedIndex < 0)
			{
				FCOMMON.Util.MsgE("담당자가 선택되어야 합니다.");
				return;
			}
			string uid = GetUIDValue();
			var f = new fHolydayJobReport(dtSD.Text, dtED.Text, uid);
			f.Show();
		}

		private void toolStripButton5_Click(object sender, EventArgs e)
		{
			//var sd = DateTime.Now.ToString("yyyy-MM-01");
			//var ed = DateTime.Parse(DateTime.Now.AddMonths(1).ToString("yyyy-MM-01")).AddDays(-1).ToString("yyyy-MM-dd");
			var f = new WorkTable();
			f.Show();
		}

		private void toolStripButton6_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
		{

			var drv = this.bs.Current as DataRowView;
			if (drv == null) return;
			var dr = drv.Row as dsMSSQL.HolydayRow;
			if (string.IsNullOrEmpty(dr.extcate) == false && dr.extidx > 0)
			{
				if (dr.extcate == "휴가") FCOMMON.Util.MsgE("이 자료는 휴가신청/승인된 자료 입니다.\n" +
					 "변경 및 삭제를 하려면 [휴가신청] 화면에서 처리하세요");
				else if (dr.extcate == "HO")
					FCOMMON.Util.MsgE("이 자료는 OT 신청/승인 된 자료입니다\n" +
						"변경 및 삭제를 하려면 [OT승인] 화면에서 처리하세요");
				else
					FCOMMON.Util.MsgE("이 자료는 외부에서 자동생성된 자료 입니다\n" +
						"본래의 데이터를 삭제 하세요\n" +
						$"소스:{dr.extcate}:{dr.extidx}");

				return;
			}

			this.bs.RemoveCurrent();
		}

		private void fHolyday_KeyPress(object sender, KeyPressEventArgs e)
		{

		}

		private void fpSpread1_KeyDown(object sender, KeyEventArgs e)
		{

		}

		private void fpSpread1_EditModeOff(object sender, EventArgs e)
		{

			var cell = this.fpSpread1.ActiveSheet.ActiveCell;
			if (cell.Column.Tag != null && cell.Column.Tag.ToString() == "pdate")
			{
				//날짜가 바뀌면 전일잔액을 바꿔야한다
				var pdate = ((DateTime)cell.Value).ToString("yyyy-MM-dd");
				var empno = fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["empno"].Index].Value.ToString();
				var ta = new dsMSSQLTableAdapters.QueriesTableAdapter();
				var jand = 0;// ta.WorkUserJan_Yesterday_Day(FCOMMON.info.Login.gcode, empno, pdate);
				var janh = 0;// ta.WorkUserJan_YesterDay_Time(FCOMMON.info.Login.gcode, empno, pdate);

				fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["yjand"].Index].Value = jand;
				fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["yjanh"].Index].Value = janh;
			}
			else if (cell.Column.Tag != null && cell.Column.Tag.ToString() == "empno")
			{

				//입력을 새로 했으므로 데이터를 조회해서 이름을 자동 설정 해준다.
				var pdate = ((DateTime)(fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["pdate"].Index].Value)).ToString("yyyy-MM-dd");
				var empno = fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["empno"].Index].Value.ToString();
				var users = this.dsMSSQL.EETGW_WorkTableUser.Where(t => t.empno.Contains(empno) || t.name.Contains(empno)).ToList();
				if (users.Count == 1)
				{
					var dr = users.FirstOrDefault();
					fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["name"].Index].Value = dr.name;
					fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["empno"].Index].Value = dr.empno;
					fpSpread1.ActiveSheet.ActiveColumnIndex = fpSpread1.ActiveSheet.Columns["dr"].Index;
					empno = dr.empno;

					//전일잔액표시
					var ta = new dsMSSQLTableAdapters.QueriesTableAdapter();
					var jand = 0;// ta.WorkUserJan_Yesterday_Day(FCOMMON.info.Login.gcode, empno, pdate);
					var janh = 0;// ta.WorkUserJan_YesterDay_Time(FCOMMON.info.Login.gcode, empno, pdate);
					fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["yjand"].Index].Value = jand;
					fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["yjanh"].Index].Value = janh;

				}
				else if (users.Count == 0)
				{
					FCOMMON.Util.MsgE("입력값({0})에 해당하는 사원번호/이름이 없습니다", empno);
					fpSpread1.ActiveSheet.ActiveColumnIndex = fpSpread1.ActiveSheet.Columns["empno"].Index;
				}
				else
				{
					//lov
					var flov = new fLovWorkUser(users);
					if (flov.ShowDialog() == DialogResult.OK)
					{
						//전일잔액표시
						var ta = new dsMSSQLTableAdapters.QueriesTableAdapter();
						var jand = 0;// ta.WorkUserJan_Yesterday_Day(FCOMMON.info.Login.gcode, flov.dr.empno, pdate);
						var janh = 0;// ta.WorkUserJan_YesterDay_Time(FCOMMON.info.Login.gcode, flov.dr.empno, pdate);
						fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["yjand"].Index].Value = jand;
						fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["yjanh"].Index].Value = janh;

						fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["name"].Index].Value = flov.dr.name;
						fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["empno"].Index].Value = flov.dr.empno;
						fpSpread1.ActiveSheet.ActiveColumnIndex = fpSpread1.ActiveSheet.Columns["dr"].Index;
					}
					else
					{
						fpSpread1.ActiveSheet.Cells[cell.Row.Index, fpSpread1.ActiveSheet.Columns["name"].Index].Value = "?";
						fpSpread1.ActiveSheet.ActiveColumnIndex = fpSpread1.ActiveSheet.Columns["dr"].Index;
					}
				}
			}
		}

		private void fpSpread1_CellClick(object sender, FarPoint.Win.Spread.CellClickEventArgs e)
		{

		}

		private void toolStripMenuItem5_Click(object sender, EventArgs e)
		{
			FCOMMON.Util.FPColsizeSave(this.fpSpread1, fn_fpcolsize);
		}

		private void toolStripMenuItem6_Click(object sender, EventArgs e)
		{
			FCOMMON.Util.FPColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
		}

		private void toolStripMenuItem3_Click(object sender, EventArgs e)
		{
			this.fpSpread1.ActiveSheet.DataAutoSizeColumns = true;

			for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
				this.fpSpread1.ActiveSheet.SetRowHeight(i, 25);
		}

		private void toolStripMenuItem4_Click(object sender, EventArgs e)
		{
			foreach (FarPoint.Win.Spread.Column col in this.fpSpread1.ActiveSheet.Columns)
			{
				col.Width = 100;
			}
		}


		private void 현재사원원장보기ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			var drv = this.bs.Current as DataRowView;
			var dr = drv.Row as dsMSSQL.HolydayRow;
			this.dtSD.Text = DateTime.Now.Year.ToString("0000") + "-01-01";
			this.dtED.Text = DateTime.Now.Year.ToString("0000") + "-12-31";
			var username = string.Format("[{0}] {1}", dr.uid, dr.UserName);
			this.cmbUser.Text = username;
			RefreshData();
		}

		private void lbStt_Click(object sender, EventArgs e)
		{
			var f = new FCOMMON.fSelectMonth();
			if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
			var sdDate = DateTime.Parse(DateTime.Now.ToString("yyyy-") + f.selectmon.ToString() + "-01");
			dtSD.Text = sdDate.ToString("yyyy-MM-dd");
			dtED.Text = sdDate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
			this.RefreshData();
		}

		private void toolStripButton2_Click_1(object sender, EventArgs e)
		{

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

			if (string.IsNullOrEmpty(dr.extcate) == false && dr.extidx > 0)
			{
				if (dr.extcate == "휴가") FCOMMON.Util.MsgE("이 자료는 휴가신청/승인된 자료 입니다.\n" +
					 "변경 및 삭제를 하려면 [휴가신청] 화면에서 처리하세요");
				else if (dr.extcate == "HO")
					FCOMMON.Util.MsgE("이 자료는 OT 신청/승인 된 자료입니다\n" +
						"변경 및 삭제를 하려면 [OT승인] 화면에서 처리하세요");
				else
					FCOMMON.Util.MsgE("이 자료는 외부에서 자동생성된 자료 입니다\n" +
						"본래의 데이터를 삭제 하세요\n" +
						$"소스:{dr.extcate}:{dr.extidx}");

				return;
			}






			var f = new fHolyday_Add(dr);
			if (f.ShowDialog() == DialogResult.OK)
			{
				dr.EndEdit();
			}
			else dr.RejectChanges();
		}
		void SearchText()
		{
			var txt = textBox1.Text.Trim();
			if (string.IsNullOrEmpty(txt))
			{
				bs.Filter = string.Empty;
				textBox1.BackColor = SystemColors.Control;
			}
			else
			{
				this.bs.Filter = "cate like '%" + txt + "%' or contents like '%" + txt + "%'";
				textBox1.BackColor = Color.Lime;
			}
			textBox1.Focus();
			textBox1.SelectAll();

		}
		private void textBox1_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
			{
				SearchText();
			}
		}

		private void 복사ToolStripMenuItem_Click(object sender, EventArgs e)
		{

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

			var newdr = this.dsMSSQL.Holyday.NewHolydayRow();
			if (this.cmbUser.SelectedIndex == 0) newdr.uid = FCOMMON.info.Login.no;
			else newdr.uid = seluid;
			newdr.gcode = FCOMMON.info.Login.gcode;
			newdr.sdate = DateTime.Now;
			newdr.edate = DateTime.Now;
			newdr.cate = dr.cate;
			newdr.contents = dr.contents;// string.Empty;
			newdr.wuid = FCOMMON.info.Login.no;
			newdr.wdate = DateTime.Now;
			newdr.UserName = FCOMMON.info.Login.nameK;

			var f = new fHolyday_Add(newdr);
			if (f.ShowDialog() == DialogResult.OK)
			{
				newdr.EndEdit();
				this.dsMSSQL.Holyday.AddHolydayRow(newdr);
			}
			else newdr.Delete();


		}

		private void toolStripButton3_Click_1(object sender, EventArgs e)
		{
			var f = new FBS0000.Holiday.fImpKunTae();
			f.ShowDialog();
		}

		private void toolStripButton7_Click(object sender, EventArgs e)
		{
			seluid = GetUIDValue();
			var f = new fHolyDayData(dtED.Text, seluid != "%" ? cmbUser.Text : string.Empty);
			f.Show();
		}

		private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
		{

		}

		private void toolStripLabel4_Click(object sender, EventArgs e)
		{
			var f = new FCOMMON.fSelectDay(DateTime.Parse(dtED.Text));
			if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
			dtED.Text = f.dtPick.SelectionStart.ToString("yyyy-MM-dd");
		}

		private void toolStripButton8_Click(object sender, EventArgs e)
		{
			var sdo = DateTime.Parse(dtSD.Text);
			var sd = DateTime.Parse(sdo.AddMonths(-1).ToString("yyyy-MM-01"));
			var ed = sd.AddMonths(1).AddDays(-1);
			dtSD.Text = sd.ToString("yyyy-MM-dd");
			dtED.Text = ed.ToString("yyyy-MM-dd");
		}

		private void toolStripButton9_Click(object sender, EventArgs e)
		{
			var sdo = DateTime.Parse(dtSD.Text);
			var sd = DateTime.Parse(sdo.AddMonths(1).ToString("yyyy-MM-01"));
			var ed = sd.AddMonths(1).AddDays(-1);
			dtSD.Text = sd.ToString("yyyy-MM-dd");
			dtED.Text = ed.ToString("yyyy-MM-dd");
		}

        private void toolStripLabel3_Click(object sender, EventArgs e)
        {
			//담당자 목록을 기간내로 업데이트합니다.
			UpdateUserList(true);
        }

		void UpdateUserList(bool datelist = false)
		{   //this.cmbUser.DisplayMember = "dispName";
			//this.cmbUser.ValueMember = "id";
			// this.bs.DataSource = dr;
			this.cmbUser.Items.Clear();
			this.cmbUser.Items.Add("-- ALL --");
			//해당그룹내의 사용자 목록을 가져와야한다
			if (datelist==false)
            {
				var dtUser = FCOMMON.DBM.getActiveUserTable();
				foreach (DataRow dr in dtUser.Rows)
				{
					this.cmbUser.Items.Add(dr["dispname"].ToString());
				}
            }
            else
            {
				var ta = new dsMSSQLTableAdapters.HolydayUserListTableAdapter();
				var dtUser = ta.GetData(FCOMMON.info.Login.gcode, dtSD.Text, dtED.Text);
				foreach (dsMSSQL.HolydayUserListRow dr in dtUser.Rows)
				{
					this.cmbUser.Items.Add($"{dr.UserName}({dr.uid})");
				}
			}
			this.cmbUser.Text = $"{FCOMMON.info.Login.nameK}({FCOMMON.info.Login.no})";
			//if (this.cmbUser.SelectedIndex < 0) this.cmbUser.SelectedIndex = 0;
		}
	}
}
