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;

namespace Project.Dialog
{
	public partial class fHistory : Form
	{
		public StdLabelPrint.LabelPrint PrinterL = null;
		// public  StdLabelPrint.LabelPrint PrinterR = null;
		public fHistory()
		{
			InitializeComponent();
			//Pub.init();
			this.KeyDown += (s1, e1) =>
			{
				if (e1.KeyCode == Keys.Escape) this.Close();
				else if (e1.KeyCode == Keys.F5) btSearch.PerformClick();
			};
			this.tbSearch.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Enter) btSearch.PerformClick(); };
			this.dv.CellFormatting += (s1, e1) =>
			{
				if (e1.RowIndex >= 0 && e1.ColumnIndex >= 0)
				{
					var dv = s1 as DataGridView;
					//var cell = dv.Rows[e1.RowIndex].Cells["dvc_upload"];
					//if (cell.Value != null)
					//{
					//    if (cell.Value.ToString() == "X")
					//        dv.Rows[e1.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
					//    else
					//        dv.Rows[e1.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
					//}
					//else dv.Rows[e1.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
				}
			};
			this.dv.DataError += dv_DataError;

			this.Text =$"Result Viewer ({SETTING.Data.McName})";
			///this.Text = string.Format("{0} ver{1} - {2}", Application.ProductName, "");
		}

		void dv_DataError(object sender, DataGridViewDataErrorEventArgs e)
		{

		}

		private void fHistory_Load(object sender, EventArgs e)
		{
		
			dtSD.Value = DateTime.Now;
			dtED.Value = DateTime.Now;

			//PrinterL = new StdLabelPrint.LabelPrint(SETTING.Data.PrinterName);
			//PrinterR = new StdLabelPrint.LabelPrint("PrinterR");
			//ApplyZplCode();

			refreshList();

		}

		void refreshList()
		{
			//검색일자 검색
			if (dtED.Value < dtSD.Value)
			{
				UTIL.MsgE("End date is earlier than start date");
				dtSD.Value = dtED.Value;
				dtSD.Focus();
				return;
			}
			//저장소초기화
			this.dataSet1.K4EE_Component_Reel_Result.Clear();

			System.Diagnostics.Stopwatch wat = new System.Diagnostics.Stopwatch();
			wat.Restart();

			//자료를 검색한다.
			var search = tbSearch.Text.Trim();
			if (search.isEmpty()) search = "%";
			else search = "%" + search + "%";

			ta.FillBySearch(this.dataSet1.K4EE_Component_Reel_Result, SETTING.Data.McName, dtSD.Value.ToShortDateString(), dtED.Value.ToShortDateString(), search);

			wat.Stop();

			tbSearch.Focus();
			tbSearch.SelectAll();
			dv.AutoResizeColumns();

		}
		private void btSearch_Click(object sender, EventArgs e)
		{
			refreshList();
		}

		private void tbiSearch_KeyDown(object sender, KeyEventArgs e)
		{
			//내부검색기능
			if (e.KeyCode == Keys.Enter)
			{
				FindData();	
			}

		}
		void FindData()
		{
			string searchkey = tbFind.Text.Trim();
			if (searchkey.isEmpty())
			{
				bs.Filter = "";
				tbFind.BackColor = SystemColors.Control;
			}
			else
			{
				string filter = "rid0 like '%{0}%' or sid0 like '%{0}%'  or qr like '%{0}%' or vlot like '%{0}%'";
				filter = string.Format(filter, searchkey);
				try
				{
					bs.Filter = filter;
					tbFind.BackColor = Color.Lime;
				}
				catch
				{
					bs.Filter = "";
					tbFind.BackColor = Color.Pink;
				}
			}
			tbFind.Focus();
			tbFind.SelectAll();
		}
		private void btExport_Click(object sender, EventArgs e)
		{
			saveXLS();
		}
		void saveXLS()
		{

			var license = ("Amkor Technology/windows-242f240302c3e50d6cb1686ba2q4k0o9").Split('/');
			var xls = new libxl.XmlBook();
			xls.setKey(license[0], license[1]);
			xls.addSheet("Result");
			var Sheet = xls.getSheet(0);

			int row = 0;
			for (int i = 0; i < this.dv.Columns.Count; i++)
			{
				var col = this.dv.Columns[i];
				Sheet.writeStr(row, i, col.HeaderText);
			}
			row += 1;
			foreach (DataGridViewRow dr in this.dv.Rows)
			{
				for (int i = 0; i < this.dv.Columns.Count; i++)
				{
					var propertyName = dv.Columns[i].DataPropertyName;
					if (propertyName.isEmpty())
					{
						Sheet.writeStr(row, i, dr.Cells[i].FormattedValue.ToString());//  dr[colname].ToString());
					}
					else
					{
						var dType = this.dataSet1.K4EE_Component_Reel_Result.Columns[propertyName].DataType;
						if (dType == typeof(float)) Sheet.writeNum(row, i, (float)dr.Cells[i].Value);
						else if (dType == typeof(double)) Sheet.writeNum(row, i, (double)dr.Cells[i].Value);
						else if (dType == typeof(int)) Sheet.writeNum(row, i, (int)dr.Cells[i].Value);
						else Sheet.writeStr(row, i, dr.Cells[i].FormattedValue.ToString());//  dr[colname].ToString());
					}

				}
				row += 1;
			}
			Sheet.setAutoFitArea(0, 0, row, dv.Columns.Count);

			string filename = "export_{0}~{1}.xlsx";
			filename = string.Format(filename, dtSD.Value.ToString("yyyyMMdd"), dtED.Value.ToString("yyyyMMdd"));

			var sd = new SaveFileDialog();
			sd.Filter = "xlsx|*.xlsx";
			sd.FileName = filename;
			sd.RestoreDirectory = true;
			if (sd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

			try
			{

				xls.save(sd.FileName);
				PUB.log.Add("Export Data : " + sd.FileName);
				if (UTIL.MsgQ("The following file has been created.\n\n" + sd.FileName + "\n\nWould you like to check the file?") == DialogResult.Yes)
                    UTIL.RunExplorer(sd.FileName);
			}
			catch (Exception ex)
			{
                PUB.log.AddE(ex.Message);
			}

		}
		private void 목록저장ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			saveXLS();
		}

		private void sendDataToolStripMenuItem_Click(object sender, EventArgs e)
		{
			var drv = this.bs.Current as DataRowView;
			if (drv == null) return;
			var dr = drv.Row as DataSet1.K4EE_Component_Reel_ResultRow;
		
			using(var f = new Dialog.fManualPrint(dr.SID,dr.VLOT, dr.QTY.ToString(),dr.MFGDATE,dr.RID, dr.VNAME, dr.PARTNO))
			{
				f.ShowDialog();
			}
		}
				

		private void button1_Click(object sender, EventArgs e)
		{
			var str = tbFind.Text.Trim();
			var f = new AR.Dialog.fTouchKeyFull("Enter search term", str);
			if (f.ShowDialog() != DialogResult.OK) return;
			tbFind.Text = f.tbInput.Text.Trim();
			FindData();
		}

        private void button2_Click(object sender, EventArgs e)
        {
			var sd = dtSD.Value.AddDays(-1);
			dtSD.Value = sd;
			dtED.Value = sd;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var sd = dtED.Value.AddDays(1);
            dtSD.Value = sd;
            dtED.Value = sd;
        }
    }
}
