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 JobReportMailService
{
	public partial class fJobReportDay : fChildBase
	{

		public fJobReportDay()
		{
			InitializeComponent();
		}

		private void fJobReportDay_Load(object sender, EventArgs e)
		{

			task = Task.Run(() =>
			{
				while (taskrun)
				{
					if (taskwait)
					{
						task.Wait(1000);
						continue;
					}

					var ts = DateTime.Now - ChkMakeSchDayWeekTime;
					if (ts.TotalMinutes <= 15)
					{
						if ((DateTime.Now - ConsoleTime).TotalHours >= 1.0)
						{
							addmsg("15분 미만이라 동작하지 않습니다");
							ConsoleTime = DateTime.Now;
						}
					}
					else if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday ||
					DateTime.Now.DayOfWeek == DayOfWeek.Sunday ||
					DateTime.Now.DayOfWeek == DayOfWeek.Monday)
					{
						//토,일요일에는 동작하지 않는다
						if ((DateTime.Now - ConsoleTime).TotalHours >= 1.0)
						{
							addmsg("토/일/월에는 동작하지 않습니다");
							ConsoleTime = DateTime.Now;
						}
					}
					else if (DateTime.Now.Hour < 9)
					{
						if ((DateTime.Now - ConsoleTime).TotalHours >= 1.0)
						{
							addmsg("9시 이전에는 동작하지 않습니다");
							ConsoleTime = DateTime.Now;
						}
					}
					else
					{
						ChkMakeSchDayWeekTime = DateTime.Now;
						try
						{
							RunData();
						}
						catch (Exception ex)
						{


							addmsg(ex.Message);

							using(var ta = new DataSet1TableAdapters.MailDataTableAdapter())
							{
								using (var dt = new DataSet1.MailDataDataTable())
								{
									var newdr = dt.NewMailDataRow();
									newdr.gcode = "EET1P";
									newdr.cate = "ER";
									newdr.subject = "[ERROR] 업무일지 메일작성 실패";
									newdr.fromlist = "chikyun.kim@amkor.co.kr";
									newdr.tolist = "chikyun.kim@amkor.co.kr";
									newdr.bcc = string.Empty;
									newdr.cc = string.Empty;
									newdr.pdate = DateTime.Now.ToShortDateString();
									newdr.body = ex.Message;
									newdr.wuid = "dev";
									newdr.wdate = DateTime.Now;
									newdr.EndEdit();
									dt.AddMailDataRow(newdr);
									var cnt = ta.Update(dt);
								}
							}
						
							task.Wait(5000);
						}
					}
					Task.Delay(Delaytime).Wait();
				}

			});
			timer1.Start();

			if (Pub.setting.autoRunData)
				btRun.PerformClick();
		}

		void RunData()
		{
			addmsg("업무일지 미 작성자 추출 작업을 시작 합니다");


			//var db = new EEEntities();

			//기준일자는 오늘부터 -15일이다
			//var basedate = new DateTime(2022, 05, 20);// DateTime.Now;
			var basedate = DateTime.Now;
			var sd = basedate.AddDays(-15);
			var ed = basedate.AddDays(-1);
			var str_sd = sd.ToShortDateString();
			var str_ed = ed.ToShortDateString();
			var str_dt = basedate.ToShortDateString();


			var taMailForm = new DataSet1TableAdapters.MailFormTableAdapter();
			var taMailData = new DataSet1TableAdapters.MailDataTableAdapter();
			var taJobReportUserList = new DataSet1TableAdapters.vJobReportUserListTableAdapter();
			var taJobReport = new DataSet1TableAdapters.JobReportTableAdapter();
			var taHolidayList = new DataSet1TableAdapters.HolidayLIstTableAdapter();
			var taGroupUser = new DataSet1TableAdapters.vGroupUserTableAdapter();
			var taJobReportDateList = new DataSet1TableAdapters.JobReportDateListTableAdapter();

			var dtMailForm = new DataSet1.MailFormDataTable();
			var dtMailData = new DataSet1.MailDataDataTable();
			var dtDateList = new DataSet1.JobReportDateListDataTable();

			taMailForm.Fill(dtMailForm);

		


			var gcodelist = dtMailForm.GroupBy(t => t.gcode).Select(t => t.Key).ToList();
			//gcodelist = new List<string>();
			//gcodelist.Add("EETK5");

			foreach (var gcodedata in gcodelist)
			{
				//메일양식이 지정되어있는지 체크
				var vGcode = gcodedata;
				if (string.IsNullOrEmpty(vGcode)) continue;

				if (vGcode.Contains("K5") == false) continue;
				

				var MailJD = dtMailForm.Where(t => t.gcode == vGcode & t.cate == "JD").FirstOrDefault();
				if (MailJD == null)
				{
					addmsg($"[{vGcode}]업무일지 미작성 메일 양식이 입력되지 않았습니다");
					continue;
				}
				if (MailJD.exceptmail == null) MailJD.exceptmail = string.Empty;
				if (MailJD.exceptmailcc == null) MailJD.exceptmailcc = string.Empty;


				//오늘날짜로 주간 데이터가 등록되어있느지 확인한다.
				//  db.MailData.Where(t => t.gcode == vGcode && t.cate == "JD" && t.pdate == str_dt).Any();
				var Existweek = taMailData.GetDataExistDay(vGcode, "JD", str_dt).Any();
				if (Existweek)
				{
					addmsg($"[{vGcode}] 업무일지(일간({str_dt}) 보고 메일이 이미 등록되어 있습니다");
					continue;
				}

				List<string> NoMailList = new List<string>();
				NoMailList.Add($"그룹\t사번\t성명\t경고일");

				//대상 사용자 목록을 추출한다;
				var users = taJobReportUserList.GetData(vGcode);
				//var users = db.vJobReportForUser.Where(t => t.gcode == vGcode).GroupBy(t => t.id);

				Dictionary<string, string> uids = new Dictionary<string, string>();
				foreach (var userinfo in users)
				{
					//해당 사용자의 오늘 날짜로 등록된 자동 데이터가 있다면 대상에 넣지 않는다
					//var userinfo = user.FirstOrDefault();
					if (userinfo == null || string.IsNullOrEmpty(userinfo.id) == true) continue;

					//퇴사자 확인
					var 퇴사일자 = userinfo.outdate;
					if (string.IsNullOrEmpty(퇴사일자) == false)
					{
						//퇴사자
						if (퇴사일자.CompareTo(str_dt) < 1) continue;
					}

					var Exists = taMailData.GetDataByUserData(vGcode, userinfo.id, str_dt, "JD").Any();
					// db.MailData.Where(t => t.gcode == vGcode && t.wuid == userinfo.id && t.pdate == str_dt && t.cate == "JD").Any();
					if (Exists == false) uids.Add(userinfo.id, userinfo.name);   //자동생성된 자료가 없는 경우에만 처리한다
				}

				addmsg($"[{vGcode}] {uids.Count} 명의 전체 사용자가 확인 되었습니다");

				//먼저 날짜목록을 가져온다
				dtDateList = taJobReportDateList.GetData(vGcode, str_sd, str_ed);//
																					//db = new EEEntities();
																					//var lstDate = db.JobReport
																					//    .Where(t => t.gcode == vGcode && t.pdate.CompareTo(str_sd) >= 0 && t.pdate.CompareTo(str_ed) < 0)
																					//    .OrderBy(t => t.pdate)
																					//    .GroupBy(t => t.pdate).ToList();

				//날짜대로 루프를 돈다
				List<DateTime> days = new List<DateTime>();
				foreach (var jobdata in dtDateList)
				{
					// var jobdata = dateitem.FirstOrDefault();
					var dt = DateTime.Parse(jobdata.pdate);
					if (dt.DayOfWeek == DayOfWeek.Sunday || dt.DayOfWeek == DayOfWeek.Saturday) continue;

					//이 날짜가 휴일인지 체크한다.
					//db = new EEEntities();
					var Holyinfo = taHolidayList.GetData(jobdata.pdate).FirstOrDefault();
					// db.HolidayLIst.Where(t =>  t.pdate == jobdata.pdate).FirstOrDefault();
					if (Holyinfo != null && Holyinfo.free == true) continue;

					//이날짜에는 8시간을 근무 해야 한다
					days.Add(DateTime.Parse(jobdata.pdate));
				}
				addmsg($"[{vGcode}] {days.Count} 건의 일자가 확인 되었습니다(기간:{str_sd}~{str_ed}");

				//사용자 목록과 날짜 목록을 모두 수집했다
				List<ReportUserData> totWarnList = new List<ReportUserData>();
				foreach (var uid in uids)
				{
					if (uid.Key == "71188")
						Console.WriteLine("테스트");

					//이사용자의 날짜별 근무시간을 확인한다.
					//db = new EEEntities();
					var UserDatas = taJobReport.GetUserDates(vGcode, uid.Key, str_sd, str_ed);
					// db.JobReport.Where(t => t.gcode == vGcode && t.uid == uid.Key && t.pdate.CompareTo(str_sd) >= 0 && t.pdate.CompareTo(str_ed) < 0).ToList();

					Dictionary<DateTime, double?> WarnList = new Dictionary<DateTime, double?>();
					foreach (var dt in days.OrderBy(t => t))
					{
						var dtstr = dt.ToShortDateString();
						var userdata = UserDatas.Where(t => t.pdate == dtstr); //해당날짜의 데이터를 확인한다.
						var hrs = 0.0;
						if (userdata.Any()) hrs = (double)userdata.Sum(t => t.hrs);
						//else continue; //동작하지 않게함.

						//자료를 입력하지 않았거나, 입력시간이 8시간 미만이면 경고한다
						if (hrs < 8.0)
						{
							WarnList.Add(dt, hrs);
							totWarnList.Add(new ReportUserData { date = dt, hrs = hrs, uid = uid.Key, uname = uid.Value }); //전체알림시에 사용하는 목록
						}
					}

					if (WarnList.Count > 0)
					{
						addmsg($"[{vGcode}] {uid.Value}({uid.Key}) 의 경고 일수는 {WarnList.Count} 건 입니다");

						//db = new EEEntities();
						var userinfo = taGroupUser.GetData(vGcode, uid.Key).FirstOrDefault();
						//  db.vGroupUser.Where(t => t.gcode == vGcode && t.id == uid.Key).FirstOrDefault();
						if (userinfo == null)
						{
							addmsg($"[{vGcode}] {uid.Value}({uid.Key}) 의 사용자 정보를 확인 할 수 없습니다");
						}
						else if (string.IsNullOrEmpty(userinfo.email))
						{
							NoMailList.Add($"{vGcode}\t{uid.Key}\t{uid.Value}\t{WarnList.Count}");
							addmsg($"[{vGcode}] {uid.Value}({uid.Key}) 의 메일 정보가 존재하지 않습니다");
						}
						else
						{
							//일별경고(월요일제외)

							if (DateTime.Now.DayOfWeek != DayOfWeek.Monday && MailJD != null)
							{
								var mail_subject = MailJD.subject.Replace("{담당자}", userinfo.name).Replace("{사번}", userinfo.id);
								var mail_to = MailJD.tolist.Replace("{담당자}", userinfo.email);
								var mail_cc = string.Empty; //
								if (MailJD.cc != null) mail_cc = MailJD.cc.Replace("{담당자}", userinfo.email);
								var mail_bcc = string.Empty;
								if (MailJD.bcc != null) mail_bcc = MailJD.bcc.Replace("{담당자}", userinfo.email);
								var mail_body = MailJD.body.Replace("{담당자}", userinfo.name);
								mail_body = mail_body.Replace("{사번}", userinfo.id);

								//메일본문을 생성해서 진행해야함
								var mail_content = "<p>일자별 정보</p>";
								mail_content += $"<br/>조회기간 : {str_sd}~{str_ed}";
								mail_content += "<br/><table border='1' cellspacing='1' cellpadding='1'><tr><td>날짜</td><td>요일</td><td>시간</td></tr>";
								foreach (var warnitem in WarnList)
								{
									mail_content += $"<tr><td>{warnitem.Key.ToShortDateString()}</td><td>{warnitem.Key.DayOfWeek.ToString()}</td><td>{warnitem.Value.ToString()}</td></tr>";
								}
								mail_content += "</table>";

								//메일데이터를 생성한다.
								//mail_to = "chikyun.kim@amkor.co.kr";
								//mail_bcc = string.Empty;
								//mail_cc = string.Empty;

								mail_to = Pub.MailSort(mail_to, MailJD.exceptmail);
								if (string.IsNullOrEmpty(mail_to) == false)
								{
									//db = new EEEntities();
									using (var dt = new DataSet1.MailDataDataTable())
									{
										var newdr = dt.NewMailDataRow();
										newdr.gcode = vGcode;
										newdr.cate = "JD";
										newdr.subject = mail_subject;
										newdr.fromlist = userinfo.email;
										newdr.tolist = Pub.MailSort(mail_to, MailJD.exceptmail);
										newdr.bcc = mail_bcc;
										newdr.cc = Pub.MailSort(mail_cc, MailJD.exceptmailcc);
										newdr.pdate = DateTime.Now.ToShortDateString();
										newdr.body = mail_body.Replace("{내용}", mail_content);
										newdr.wuid = "dev";
										newdr.wdate = DateTime.Now;
										newdr.EndEdit();
										dt.AddMailDataRow(newdr);
										var cnt = taMailData.Update(dt);

										if (cnt == 1)
										{
											addmsg($"[{vGcode}] {userinfo.name}({userinfo.email}) 메일 생성 완료(day)");
											System.Threading.Thread.Sleep(10000);
										}
										
									}


									//taMailData.Insert()
									//db.MailData.Add(new MailData
									//{
									//	gcode = vGcode,
									//	cate = "JD",
									//	subject = mail_subject,
									//	fromlist = userinfo.email,
									//	tolist = Pub.MailSort(mail_to, MailJD.exceptmail),
									//	bcc = mail_bcc,
									//	cc = Pub.MailSort(mail_cc, MailJD.exceptmailcc),
									//	pdate = DateTime.Now.ToShortDateString(),
									//	body = mail_body.Replace("{내용}", mail_content),
									//	wuid = "dev",
									//	wdate = DateTime.Now,
									//});
									//db.SaveChanges();
						
								}
								else
								{
									addmsg($"[{vGcode}] 받는사람이 소거되어 메일을 생성하지 않습니다");
								}
							}
						}
						System.Threading.Thread.Sleep(3000);
					}
					else
					{
						addmsg($"[{vGcode}] {uid.Value}({uid.Key}) 미 작성 일자가 없습니다");
					}

				}


				//첫줄은 제목이므로 2줄이상 있어야 한다
				if (NoMailList.Count > 1)
				{
					using (var dt = new DataSet1.MailDataDataTable())
					{
						var newdr = dt.NewMailDataRow();
						newdr.gcode = "EET1P";
						newdr.cate = "ERR";
						newdr.subject = $"[GW] {vGcode} - 업무일지 담당자 이메일 경고";
						newdr.fromlist = "chikyun.kim@amkor.co.kr";
						newdr.tolist = "chikyun.kim@amkor.co.kr";
						newdr.bcc = string.Empty;
						newdr.cc = string.Empty;
						newdr.pdate = DateTime.Now.ToShortDateString();
						newdr.body = string.Join("<br/>", NoMailList.ToList());
						newdr.wuid = "dev";
						newdr.wdate = DateTime.Now;
						newdr.EndEdit();
						dt.AddMailDataRow(newdr);
						var cnt = taMailData.Update(dt);
						if (cnt == 1)
						{
							addmsg($"업무일지 메일없는 대상자 생성 완료(day)");
							System.Threading.Thread.Sleep(10000);
						}
					}
				}


				System.Threading.Thread.Sleep(500);
			}


			
			dtMailForm.Dispose();
			dtMailData.Dispose();
			dtDateList.Dispose();


			

			taMailForm.Dispose();// = new DataSet1TableAdapters.MailFormTableAdapter();
			taMailData.Dispose();// = new DataSet1TableAdapters.MailDataTableAdapter();
			taJobReportUserList.Dispose();// = new DataSet1TableAdapters.vJobReportUserListTableAdapter();
			taJobReport.Dispose();// = new DataSet1TableAdapters.JobReportTableAdapter();
			taHolidayList.Dispose();// = new DataSet1TableAdapters.HolidayLIstTableAdapter();
			taGroupUser.Dispose();// = new DataSet1TableAdapters.vGroupUserTableAdapter();
			taJobReportDateList.Dispose();

			
		}

		private void toolStripButton1_Click(object sender, EventArgs e)
		{
			taskwait = !taskwait;
			if (taskwait == false)
				ChkMakeSchDayWeekTime = DateTime.Now.AddHours(-1);
		}

		private void timer1_Tick(object sender, EventArgs e)
		{
			if (task != null)
			{
				if (task.IsCompleted) this.btRun.Text = "완료";
				else if (task.IsCanceled) this.btRun.Text = "취소";
				else if (taskwait) this.btRun.Text = "대기상태";
				else this.btRun.Text = "가동중";
				this.btRun.Enabled = true;
			}
			else
			{
				this.btRun.Text = "사용불가";
				this.btRun.Enabled = false;
			}

		}

		private void toolStripButton1_Click_1(object sender, EventArgs e)
		{
			RunData();
		}
	}
}
