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 fJobReportWeek : fChildBase
	{

		public fJobReportWeek()
		{
			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.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 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);

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

			var gcodelist = dtMailForm.GroupBy(t => t.gcode).Select(t => t.Key).ToList();
			foreach (var gcodedata in gcodelist)
			{
				//메일양식이 지정되어있는지 체크
				var vGcode = gcodedata;
				if (string.IsNullOrEmpty(vGcode)) continue;

				//메일양식이 지정되어있는지 체크
				var MailJW = dtMailForm.Where(t => t.gcode == vGcode & t.cate == "JW").FirstOrDefault();
				if (MailJW == null)
				{
					addmsg($"[{vGcode}] 업무일지 미작성(주간) 메일 양식이 입력되지 않았습니다");
					continue;
				}
				if (MailJW.exceptmail == null) MailJW.exceptmail = string.Empty;
				if (MailJW.exceptmailcc == null) MailJW.exceptmailcc = string.Empty;

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

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

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

					

					//이 대상의 이메일이 받는 사람에 제외되어있다면 처리하지 않는다.
					if (MailJW.exceptmail == null) MailJW.exceptmail = string.Empty;
					var exxptolist = MailJW.exceptmail.ToUpper().Split(';');
					if (exxptolist.Contains(userinfo.email.ToUpper()) == false)
					{
						//모두대상으로 처리한다
						//if (userdata.email.ToUpper() != ("BongSeok.Jung@amkor.co.kr").ToUpper())
						uids.Add(userinfo.id, userinfo.name);
					}
					else addmsg($"[{vGcode}] 주간 제외대상자임 " + userinfo.email);
				}

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

				//먼저 날짜목록을 가져온다
				//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();

				dtDateList = taJobReportDateList.GetData(vGcode, str_sd, str_ed);//

				//날짜대로 루프를 돈다
				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;

					//이 날짜가 휴일인지 체크한다.
					var Holyinfo = taHolidayList.GetData(jobdata.pdate).FirstOrDefault();
					//var Holyinfo = 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)
				{
					//이사용자의 날짜별 근무시간을 확인한다.
					var UserDatas = taJobReport.GetUserDates(vGcode, uid.Key, str_sd, str_ed);

					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);

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

				}

				if (totWarnList.Count > 0)
				{
					addmsg($"[{vGcode}] 주간 경고 데이터는 {totWarnList.Count} 건 입니다");

					//오늘잘짜로 등록된 자료가 있으면 처리하지 안흔다.
					//해당 사용자의 오늘 날짜로 등록된 자동 데이터가 있다면 대상에 넣지 않는다
					//db = new EEEntities();

					var mail_subject = MailJW.subject;
					var mail_to = MailJW.tolist;//.Replace("{담당자}", userinfo.email);
					var pmail_cc = new List<string>(); //
					if (MailJW.cc != null) pmail_cc = MailJW.cc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();//.Replace("{담당자}", userinfo.email);
					var mail_bcc = string.Empty;
					if (MailJW.bcc != null) mail_bcc = MailJW.bcc;//.Replace("{담당자}", userinfo.email);
					var mail_body = MailJW.body;//.Replace("{담당자}", userinfo.name);

					//메일본문을 생성해서 진행해야함
					var vmail_body = "<p>담당자별 정보</p>";
					vmail_body += "<br/>조회기간 : " + sd.ToShortDateString() + "~" + ed.ToShortDateString();

					////참고데이터를 추가한다
					var usergrplist = totWarnList.OrderBy(t => t.uname).GroupBy(t => t.uid).ToList();
					//foreach (var item in usergrplist)
					//{
					//	//var fitem = item.FirstOrDefault();
					//	//db = new EEEntities();
					//	var userinfo = item.FirstOrDefault();// db.vGroupUser.Where(t => t.gcode == vGcode && t.id == fitem.uid).FirstOrDefault();
					//	var username = string.Empty;
					//	if (userinfo != null)
					//	{
					//		if (string.IsNullOrEmpty(userinfo.email) == false)
					//		{
					//			//if (pmail_cc.Contains(userinfo.email) == false)
					//			//    pmail_cc.Add(userinfo.email);
					//		}
					//		username = userinfo.name;
					//	}
					//}

					vmail_body += "<br/><table border='1' cellspacing='1' cellpadding='1'><tr><td>담당자</td><td>일자별시간</td></tr>";
					var mail_cc = string.Join(";", pmail_cc);   //모든 대상을 세미콜론으로 붙인다.
					foreach (var warnitem in usergrplist)
					{
						var item = warnitem.FirstOrDefault();
						vmail_body += $"<tr><td>{item.uname}({item.uid})</td><td>";
						foreach (var ii in warnitem.OrderBy(t => t.date))
						{
							vmail_body += $" {ii.date.ToString("MM/dd")}({ii.hrs}h)";
						}
						vmail_body += "</td></tr>";
					}
					vmail_body += "</table>";

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

					//db = new EEEntities();
					mail_to = Pub.MailSort(mail_to, MailJW.exceptmail);
					if (string.IsNullOrEmpty(mail_to) == false)
					{
						using (var dt = new DataSet1.MailDataDataTable())
						{

							var newdr = dt.NewMailDataRow();
							newdr.gcode = vGcode;
							newdr.cate = "JW";
							newdr.subject = mail_subject;
							newdr.fromlist = "EETGW@amkor.co.kr";
							newdr.tolist = Pub.MailSort(mail_to, MailJW.exceptmail);
							newdr.bcc = mail_bcc;
							newdr.cc = Pub.MailSort(mail_cc, MailJW.exceptmailcc);
							newdr.pdate = DateTime.Now.ToShortDateString();
							newdr.body = mail_body.Replace("{내용}", vmail_body);
							newdr.wuid = "dev";
							newdr.wdate = DateTime.Now;
							newdr.EndEdit();
							dt.AddMailDataRow(newdr);
							var cnt = taMailData.Update(dt);

							if (cnt == 1)
							{
								addmsg($"[{vGcode}] {cnt}건) 메일 생성 완료(week)");
								System.Threading.Thread.Sleep(10000);
							}
						}
					}
					else
					{
						addmsg($"[{vGcode}] 받는사람이 소거되어 메일을 생성하지 않습니다");
					}
				}


				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;
		}

		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();
		}
	}
}
