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 ResultView
{
	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 = string.Format("{0} ver{1} - {2}", Application.ProductName, Application.ProductVersion,Pub.setting.MCName);
		}

		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(Pub.setting.PrinterName);
			//PrinterR = new StdLabelPrint.LabelPrint("PrinterR");
			ApplyZplCode();

			refreshList();

		}

		public void ApplyZplCode()
		{
			string zplfil = string.Empty;
			var basedir = new System.IO.DirectoryInfo(Util.CurrentPath);
			if (Pub.setting.PrinterForm7)
			{
				zplfil = System.IO.Path.Combine(basedir.Parent.FullName, "zpl7.txt");
			}
			else
			{
				zplfil = System.IO.Path.Combine(basedir.Parent.FullName, "zpl.txt");
			}

			if (System.IO.File.Exists(zplfil))
			{
				PrinterL.baseZPL = System.IO.File.ReadAllText(zplfil, System.Text.Encoding.Default);
			}
			else
			{
				Pub.log.AddAT("Default ZPL file not found, using settings file content");
				if (Pub.setting.PrinterForm7)
				{
					PrinterL.baseZPL = Properties.Settings.Default.ZPL7;
				}
				else
				{
					PrinterL.baseZPL = Properties.Settings.Default.ZPL;
				}

			}
		}

		private void checkBox5_CheckedChanged(object sender, EventArgs e)
		{
			//            cmbUser.Enabled = checkBox5.Checked;
			//            if(cmbUser.Enabled && cmbUser.Text.isEmpty())
			//            {
			//                cmbUser.Text = string.Format("{0}({1})", Pub.LoginName, Pub.LoginNo);
			//            }
		}

		void refreshList()
		{
			//검색일자 검색
			if (dtED.Value < dtSD.Value)
			{
				Util.MsgE("Search end date is earlier than start date");
				dtSD.Value = dtED.Value;
				dtSD.Focus();
				return;
			}
			//저장소초기화
			this.dataSet1.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.Fill(this.dataSet1.Component_Reel_Result, Pub.setting.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.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 view 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 label2_Click(object sender, EventArgs e)
		{

		}

		private void viewXMLToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//var drv = this.bs.Current as DataRowView;
			//if (drv == null) return;
			//var dr = drv.Row as DataSet1.Component_Reel_ResultRow;
			//var file = dr.info_filename;
			//if (file == "") return;
			//Util.RunExplorer(file);
		}

		private void dv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			//var drv = this.bs.Current as DataRowView;
			//if (drv == null) return;
			//var dr = drv.Row as DataSet1.Component_Reel_ResultRow;
			//var fi = new System.IO.FileInfo(dr.info_filename);

			//if (fi.Exists == false)
			//{
			//    Util.MsgE("결과 파일이 없습니다");
			//    return;
			//}
			//else
			//{
			//    Util.RunExplorer(fi.Directory.FullName);
			//}

		}
		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.Component_Reel_ResultRow;
			var data = dr.QR;
			var bcd = new StdLabelPrint.CAmkorSTDBarcode(data);
			if (bcd.VENDERNAME.isEmpty() && dr.VNAME.isEmpty() == false)
				bcd.VENDERNAME = dr.VNAME.Trim();

			var reeldata = new StdLabelPrint.Reel();
			reeldata.id = bcd.RID;
			reeldata.manu = bcd.VENDERNAME;
			reeldata.lot = bcd.VLOT;
			reeldata.mfg = bcd.MFGDate;
			reeldata.qty = bcd.QTY;
			reeldata.sid = bcd.SID;
			reeldata.partnum = bcd.PARTNO;

			PrinterL.Print(reeldata, false, Pub.setting.DrawBorder, Pub.setting.PrinterForm7);
		}


		private void btSetting_Click(object sender, EventArgs e)
		{
			var f = new fSetting();
			f.ShowDialog();
			PrinterL.printerName = Pub.setting.PrinterName;
		}

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