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 fImportSIDInfo : Form
	{
		public fImportSIDInfo()
		{
			InitializeComponent();
		}

		private void component_Reel_SIDConvBindingNavigatorSaveItem_Click(object sender, EventArgs e)
		{
			this.Validate();
			this.bs.EndEdit();
			this.ta.Update(this.dataSet1.Component_Reel_SIDInfo);

		}

		private void fImportSIDConv_Load(object sender, EventArgs e)
		{
			// TODO: 이 코드는 데이터를 'dataSet1.Component_Reel_SIDInfo' 테이블에 로드합니다. 필요 시 이 코드를 이동하거나 제거할 수 있습니다.
			this.ta.Fill(this.dataSet1.Component_Reel_SIDInfo);
			// TODO: 이 코드는 데이터를 'dataSet1.Component_Reel_SIDConv' 테이블에 로드합니다. 필요 시 이 코드를 이동하거나 제거할 수 있습니다.
		}

		private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
			{
				var search = this.tbFind.Text.Trim();
				if (search.isEmpty())
				{
					this.bs.Filter = "";
					this.tbFind.BackColor = SystemColors.Window;
				}
				else
				{
					var list = new string[] { "M101", "M103", "M106", "cust", "partno" };
					var filter = string.Join(" like '%{0}%' or ", list);
					filter += " like '%{0}%'";
					filter = string.Format(filter, search.Replace("'", "''"));
					try
					{
						this.bs.Filter = filter;
						this.tbFind.BackColor = Color.Lime;
						this.tbFind.SelectAll();
						this.tbFind.Focus();
					}
					catch (Exception ex)
					{
						this.tbFind.BackColor = Color.Tomato;
						Pub.log.AddE("sid 변환 테이블 필터 오류 : " + ex.Message);
					}
				}
			}
		}

		private void toolStripButton1_Click(object sender, EventArgs e)
		{
			//엑셀을 읽어와서 처리한다.
			var od = new OpenFileDialog();
			if (od.ShowDialog() != DialogResult.OK) return;
			libxl.Book book;
			var fi = new System.IO.FileInfo(od.FileName);
			var ext = fi.Extension.ToLower();
			if (ext == ".xlsx") book = new libxl.XmlBook();
			else if (ext == ".xls") book = new libxl.BinBook();
			else
			{
				Util.MsgE("지원되지 않는 파일 입니다");
				return;
			}

			var keyinfo = Properties.Settings.Default.libxl.Split('/');
			book.setKey(keyinfo[0], keyinfo[1]);
			book.load(fi.FullName);
			var sheet = book.getSheet(0);


			var cs = sheet.firstCol();
			var ce = sheet.lastCol();
			var rs = sheet.firstRow();
			var re = sheet.lastRow();

			this.progressBar1.Minimum = 0;
			this.progressBar1.Maximum = re;
			this.progressBar1.Value = 0;

			int cntA = 0;
			int cntU = 0;
			for (int row = rs; row <= re; row++)
			{
				if (this.progressBar1.Value < this.progressBar1.Maximum)
					this.progressBar1.Value += 1;
				var cSID = sheet.readStr(row, 1);
				var cCustCode = sheet.readStr(row, 2);
				var cCustName = sheet.readStr(row, 3);

				if (cCustCode.isEmpty() == false && cCustCode.Length != 4)
					cCustCode = cCustCode.PadLeft(4, '0');

				if (cSID.StartsWith("10"))
				{


					EnumerableRowCollection<DataSet1.Component_Reel_SIDInfoRow> plist = null;
					plist = this.dataSet1.Component_Reel_SIDInfo.Where(t => t.SID == cSID);

					if (plist == null || plist.Any() == false)
					{
						//존재하지않으면 추가한다.
						var newdr = this.dataSet1.Component_Reel_SIDInfo.NewComponent_Reel_SIDInfoRow();
						newdr.CustCode = cCustCode;
						newdr.CustName = cCustName;
						newdr.VenderName = string.Empty;
						newdr.SID = cSID;
						newdr.PartNo = string.Empty;
						newdr.PrintPosition = string.Empty;
						newdr.Remark = string.Empty;
						this.dataSet1.Component_Reel_SIDInfo.AddComponent_Reel_SIDInfoRow(newdr);
						cntA += 1;
					}
					else
					{
						//있다면 업데이트 해준다.
						foreach (var item in plist)
						{
							if (cCustCode.isEmpty() == false)
							{
								item.CustCode = cCustCode;
								item.CustName = cCustName;
							}
							item.EndEdit();
							cntU += 1;
						}
					}
				}
				else if (cSID.isEmpty() && cCustCode.isEmpty()) break; //
			}
			Util.MsgI(string.Format("추가:{0},변경:{1}", cntA, cntU));
		}

		private void toolStripButton2_Click(object sender, EventArgs e)
		{
			//엑셀을 읽어와서 처리한다.
			var od = new OpenFileDialog();
			if (od.ShowDialog() != DialogResult.OK) return;
			libxl.Book book;
			var fi = new System.IO.FileInfo(od.FileName);
			var ext = fi.Extension.ToLower();
			if (ext == ".xlsx") book = new libxl.XmlBook();
			else if (ext == ".xls") book = new libxl.BinBook();
			else
			{
				Util.MsgE("지원되지 않는 파일 입니다");
				return;
			}

			var keyinfo = Properties.Settings.Default.libxl.Split('/');
			book.setKey(keyinfo[0], keyinfo[1]);
			book.load(fi.FullName);
			var sheet = book.getSheet(0);


			var cs = sheet.firstCol();
			var ce = sheet.lastCol();
			var rs = sheet.firstRow();
			var re = sheet.lastRow();

			this.progressBar1.Minimum = 0;
			this.progressBar1.Maximum = re;
			this.progressBar1.Value = 0;

			int cntA = 0;
			int cntU = 0;
			for (int row = rs; row <= re; row++)
			{
				if (this.progressBar1.Value < this.progressBar1.Maximum)
					this.progressBar1.Value += 1;

				var cSID = sheet.readStr(row, 0).Trim();
				var cPart = sheet.readStr(row, 1).Trim();  //part
				if (cPart == "N/A") cPart = string.Empty;

				if (cSID.StartsWith("10") && cPart.isEmpty()==false)
				{


					EnumerableRowCollection<DataSet1.Component_Reel_SIDInfoRow> plist = null;
					plist = this.dataSet1.Component_Reel_SIDInfo.Where(t => t.SID == cSID);

					if (plist == null || plist.Any() == false)
					{
						//존재하지않으면 추가한다.
						var newdr = this.dataSet1.Component_Reel_SIDInfo.NewComponent_Reel_SIDInfoRow();
						newdr.CustCode = string.Empty;
						newdr.CustName = string.Empty;
						newdr.VenderName = string.Empty;
						newdr.SID = cSID;
						newdr.PartNo = cPart;
						newdr.PrintPosition = string.Empty;
						newdr.Remark = string.Empty;
						this.dataSet1.Component_Reel_SIDInfo.AddComponent_Reel_SIDInfoRow(newdr);
						cntA += 1;
					}
					else
					{
						//있다면 업데이트 해준다.
						foreach (var item in plist)
						{
							if (cPart.isEmpty() == false)
							{
								item.PartNo = cPart;
							}
							item.EndEdit();
							cntU += 1;
						}
					}
				}
				else if (cSID.isEmpty() && cPart.isEmpty()) break; //
			}
			Util.MsgI(string.Format("추가:{0},변경:{1}", cntA, cntU));
		}
	}
}
