/*
 * Backgroudn worker
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Text;

namespace Console_SendMail
{
    partial class Program
    {
        public static void Mail_JobReportDay()
        {
            //  addmsg("업무일지 미 작성자 추출 작업을 시작 합니다");
            var vCate = "JD";

            var taMailForm = new DSMailTableAdapters.MailFormTableAdapter();
            var taMailData = new DSMailTableAdapters.MailDataTableAdapter();
            var taPrjList = new DSMailTableAdapters.ProjectsIngListTableAdapter();
            var taSche = new DSMailTableAdapters.EETGW_ProjectsScheduleTableAdapter();
            var taJobReport = new DSMailTableAdapters.JobReportTableAdapter();
            var taHolidayList = new DSMailTableAdapters.HolidayLIstTableAdapter();
            var taGroupUser = new DSMailTableAdapters.vGroupUserTableAdapter();
            var taJobReportDateList = new DSMailTableAdapters.JobReportDateListTableAdapter();

            //기준일자는 오늘부터 -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.ToString("yyyy-MM-dd");//ToShortDateString();
            var str_ed = ed.ToString("yyyy-MM-dd");//ToShortDateString();
            var str_dt = basedate.ToString("yyyy-MM-dd");

            var gcodelist = DatabaseManager.getGroupListWithoutGcode("gcode", "MailForm", "gcode is not null and gcode <> 'DEV'");

            foreach (var vGcode in gcodelist)
            {
                //메일기능이 꺼져있다면 처리하지 않는다.
                var usemail = DatabaseManager.GetGroupEnableMail(vGcode);
                if (usemail == false) continue;

                //메일정보가 등록되지 않았다면 처리하지 않는다
                var MailForm = taMailForm.GetData(vGcode, vCate).FirstOrDefault();
                if (MailForm == null) continue;
                if (MailForm.exceptmail == null) MailForm.exceptmail = string.Empty;
                if (MailForm.exceptmailcc == null) MailForm.exceptmailcc = string.Empty;
                if (string.IsNullOrEmpty(MailForm.subject) || string.IsNullOrEmpty(MailForm.tolist)) continue;

                //오늘날짜로 데이터가 등록되어있느지 확인한다.
                var Existweek = taMailData.GetData(vGcode, str_dt, vCate).Where(t => t.tolist.Equals("chikyun.kim@amkor.co.kr") == false && t.wuid.Equals("debug") == false).Any();
                if (Existweek) continue;


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

                //대상 사용자 목록을 추출한다;
                var users = taGroupUser.GetData(vGcode);
                Dictionary<string, DSMail.vGroupUserRow> uids = new Dictionary<string, DSMail.vGroupUserRow>();
                foreach (var userinfo in users)
                {
                    //적용대상제거
                    if (userinfo.useJobReport == false || userinfo.useUserState == false)
                        continue;

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

                    //이 대상의 이메일이 받는 사람에 제외되어있다면 처리하지 않는다.
                    var exxptolist = MailForm.exceptmail.ToUpper().Split(';');
                    if (exxptolist.Contains(userinfo.email.ToUpper())) continue;

                    //메일대상자로 선정한다
                    uids.Add(userinfo.id, userinfo);   //자동생성된 자료가 없는 경우에만 처리한다
                }

                //먼저 날짜목록을 가져온다
                var dtDateList = taJobReportDateList.GetData(vGcode, str_sd, str_ed);//

                //날짜대로 루프를 돈다
                List<DateTime> days = new List<DateTime>();
                foreach (var jobdata in dtDateList)
                {
                    //날짜입력데이터 확인
                    if (DateTime.TryParse(jobdata.pdate, out DateTime dt) == false) continue;

                    //토,일요일에는 동작하지 않는다
                    if (dt.DayOfWeek == DayOfWeek.Sunday || dt.DayOfWeek == DayOfWeek.Saturday) continue;

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

                    //이날짜에는 8시간을 근무 해야 한다
                    days.Add(DateTime.Parse(jobdata.pdate));
                }

                //사용자 목록과 날짜 목록을 모두 수집했다
                List<ReportUserData> totWarnList = new List<ReportUserData>();
                foreach (var userinfo in uids)
                {
                    //이사용자의 기간내 근무데이터를 확인
                    var UserDatas = taJobReport.GetData(vGcode, userinfo.Key, str_sd, str_ed);

                    Dictionary<DateTime, double?> WarnList = new Dictionary<DateTime, double?>();
                    foreach (var dt in days.OrderBy(t => t))
                    {
                        var dtstr = dt.ToString("yyyy-MM-dd");
                        var userdata = UserDatas.Where(t => t.pdate == dtstr); //해당날짜의 데이터를 확인한다.
                        var hrs = 0f;
                        if (userdata.Any()) hrs = (float)userdata.Sum(t => t.hrs);

                        //입력시간이 8시간 미만이면 경고한다
                        if (hrs < 8f)
                        {
                            WarnList.Add(dt, hrs);
                            totWarnList.Add(new ReportUserData { date = dt, hrs = hrs, uid = userinfo.Key, uname = userinfo.Value.name }); //전체알림시에 사용하는 목록
                        }
                    }

                    //경고데이터가 있는 경우에만 메일 발송
                    if (WarnList.Any())
                    {
                        if (string.IsNullOrEmpty(userinfo.Value.email))
                        {
                            NoMailList.Add($"{vGcode}\t{userinfo.Key}\t{userinfo.Value}\t{WarnList.Count}");
                            //addmsg($"[{vGcode}] {userinfo.Value}({userinfo.Key}) 의 메일 정보가 존재하지 않습니다");
                        }
                        else
                        {
                            //일별경고(월요일제외)
                            var mail_subject = MailForm.subject.Replace("{담당자}", userinfo.Value.name).Replace("{사번}", userinfo.Value.id);
                            var mail_to = MailForm.tolist.Replace("{담당자}", userinfo.Value.email);
                            var mail_cc = string.Empty; //
                            if (MailForm.cc != null) mail_cc = MailForm.cc.Replace("{담당자}", userinfo.Value.email);
                            var mail_bcc = string.Empty;
                            if (MailForm.bcc != null) mail_bcc = MailForm.bcc.Replace("{담당자}", userinfo.Value.email);
                            var mail_body = MailForm.body.Replace("{담당자}", userinfo.Value.name);
                            mail_body = mail_body.Replace("{사번}", userinfo.Value.id);

                            //메일본문을 생성해서 진행해야함
                            var mail_content = $"<p>일자별 정보({vGcode})</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.ToString("yyyy-MM-dd")}</td><td>{warnitem.Key.DayOfWeek.ToString()}</td><td>{warnitem.Value:N1}</td></tr>";
                            }
                            mail_content += "</table>";

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

                            mail_to = MailSort(mail_to, MailForm.exceptmail);
                            if (string.IsNullOrEmpty(mail_to) == false)
                            {
                                //db = new EEEntities();
                                using (var dt = new DSMail.MailDataDataTable())
                                {
                                    var newdr = dt.NewMailDataRow();
                                    newdr.gcode = vGcode;
                                    newdr.cate = vCate;
                                    newdr.subject = mail_subject;
                                    newdr.fromlist = userinfo.Value.email;
                                    newdr.tolist = MailSort(mail_to, MailForm.exceptmail);
                                    newdr.bcc = mail_bcc;
                                    newdr.cc = MailSort(mail_cc, MailForm.exceptmailcc);
                                    newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");//ToShortDateString();
                                    newdr.body = mail_body.Replace("{내용}", mail_content);
                                    newdr.wuid = "dev";
                                    newdr.wdate = DateTime.Now;

                                    if (System.Diagnostics.Debugger.IsAttached)
                                    {
                                        newdr.tolist = "chikyun.kim@amkor.co.kr";
                                        newdr.bcc = string.Empty;
                                        newdr.cc = string.Empty;
                                        newdr.wuid = "debug";
                                    }

                                    newdr.EndEdit();
                                    dt.AddMailDataRow(newdr);
                                    var cnt = taMailData.Update(dt);
                                    if (cnt == 1) System.Threading.Thread.Sleep(500);
                                }
                            }
                        }
                    }
                }


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




            taMailForm.Dispose();
            taMailData.Dispose();
            taJobReport.Dispose();
            taHolidayList.Dispose();
            taGroupUser.Dispose();
            taJobReportDateList.Dispose();
        }

        public static void Mail_JobReportWeek()
        {
            var vCate = "JW";

            var taMailForm = new DSMailTableAdapters.MailFormTableAdapter();
            var taMailData = new DSMailTableAdapters.MailDataTableAdapter();
            var taPrjList = new DSMailTableAdapters.ProjectsIngListTableAdapter();
            var taSche = new DSMailTableAdapters.EETGW_ProjectsScheduleTableAdapter();
            var taJobReport = new DSMailTableAdapters.JobReportTableAdapter();
            var taHolidayList = new DSMailTableAdapters.HolidayLIstTableAdapter();
            var taGroupUser = new DSMailTableAdapters.vGroupUserTableAdapter();
            var taJobReportDateList = new DSMailTableAdapters.JobReportDateListTableAdapter();


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

            var gcodelist = DatabaseManager.getGroupListWithoutGcode("gcode", "MailForm", "gcode is not null and gcode <> 'DEV'");
            foreach (var vGcode in gcodelist)
            {

                //메일기능이 꺼져있다면 처리하지 않는다.
                var usemail = DatabaseManager.GetGroupEnableMail(vGcode);
                if (usemail == false) continue;

                //메일양식이 지정되어있는지 체크
                var MailForm = taMailForm.GetData(vGcode, vCate).FirstOrDefault();
                if (MailForm == null) continue;
                if (MailForm.exceptmail == null) MailForm.exceptmail = string.Empty;
                if (MailForm.exceptmailcc == null) MailForm.exceptmailcc = string.Empty;
                if (string.IsNullOrEmpty(MailForm.subject) || string.IsNullOrEmpty(MailForm.tolist)) continue;

                //오늘날짜로 주간 데이터가 등록되어있느지 확인한다.
                //var Existweek = taMailData.GetData(vGcode, str_dt, vCate).Any();
                var Existweek = taMailData.GetData(vGcode, str_dt, vCate).Where(t => t.tolist.Equals("chikyun.kim@amkor.co.kr") == false && t.wuid.Equals("debug") == false).Any();
                if (Existweek) continue;

                //대상 사용자 목록을 추출한다
                var users = taGroupUser.GetData(vGcode);
                Dictionary<string, DSMail.vGroupUserRow> uids = new Dictionary<string, DSMail.vGroupUserRow>();
                foreach (var userinfo in users)
                {
                    //적용대상제거
                    if (userinfo.useJobReport == false || userinfo.useUserState == false)
                        continue;

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

                    //이 대상의 이메일이 받는 사람에 제외되어있다면 처리하지 않는다.
                    var exxptolist = MailForm.exceptmail.ToUpper().Split(';');
                    if (exxptolist.Contains(userinfo.email.ToUpper())) continue;

                    //메일대상자로 선정한다
                    uids.Add(userinfo.id, userinfo);   //자동생성된 자료가 없는 경우에만 처리한다
                }

                var 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.GetData(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.ToString("yyyy-MM-dd");
                        var userdata = UserDatas.Where(t => t.pdate == dtstr); //해당날짜의 데이터를 확인한다.
                        var hrs = 0f;
                        if (userdata.Any()) hrs = (float)userdata.Sum(t => t.hrs);

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

                }

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

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

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

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

                    ////참고데이터를 추가한다
                    var usergrplist = totWarnList.OrderBy(t => t.uname).GroupBy(t => t.uid).ToList();
                    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:N1}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 = MailSort(mail_to, MailForm.exceptmail);
                    if (string.IsNullOrEmpty(mail_to) == false)
                    {
                        using (var dt = new DSMail.MailDataDataTable())
                        {

                            var newdr = dt.NewMailDataRow();
                            newdr.gcode = vGcode;
                            newdr.cate = vCate;
                            newdr.subject = mail_subject;
                            newdr.fromlist = "EETGW@amkor.co.kr";
                            newdr.tolist = mail_to;
                            newdr.bcc = mail_bcc;
                            newdr.cc = MailSort(mail_cc, MailForm.exceptmailcc);
                            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
                            newdr.body = mail_body.Replace("{내용}", vmail_body);
                            newdr.wuid = "dev";
                            newdr.wdate = DateTime.Now;
                            if (System.Diagnostics.Debugger.IsAttached)
                            {
                                newdr.tolist = "chikyun.kim@amkor.co.kr";
                                newdr.bcc = string.Empty;
                                newdr.cc = string.Empty;
                                newdr.wuid = "debug";
                            }
                            newdr.EndEdit();
                            dt.AddMailDataRow(newdr);
                            var cnt = taMailData.Update(dt);

                            if (cnt == 1) System.Threading.Thread.Sleep(1000);
                        }
                    }
                }
            }

            taMailForm.Dispose();
            taMailData.Dispose();
            taPrjList.Dispose();
            taSche.Dispose();

            taJobReport.Dispose();
            taHolidayList.Dispose();
            taGroupUser.Dispose();
            taJobReportDateList.Dispose();
        }

        public static void Mail_NoSchedule()
        {
            var taForm = new DSMailTableAdapters.MailFormTableAdapter();
            var taMailData = new DSMailTableAdapters.MailDataTableAdapter();
            var taPrjList = new DSMailTableAdapters.ProjectsIngListTableAdapter();
            var taSche = new DSMailTableAdapters.EETGW_ProjectsScheduleTableAdapter();
            var vCate = "SN";
            try
            {   
                //기준일자는 오늘부터 -15일이다
                var sd = DateTime.Now.AddDays(-15);
                var ed = DateTime.Now;
                var str_sd = sd.ToString("yyyy-MM-dd");
                var str_ed = ed.ToString("yyyy-MM-dd");//ToShortDateString();
                var str_dt = DateTime.Now.ToString("yyyy-MM-dd");//ToShortDateString();

                var gcodelist = DatabaseManager.getGroupListWithoutGcode("gcode", "MailForm", "gcode is not null and gcode <> 'DEV'");
                foreach (var vGcode in gcodelist)
                {
                    //메일기능이 꺼져있다면 처리하지 않는다.
                    var usemail = DatabaseManager.GetGroupEnableMail(vGcode);
                    if (usemail == false) continue;

                    //메일양식이 지정되어있는지 체크
                    var MailForm = taForm.GetData(vGcode, vCate).FirstOrDefault();
                    if (MailForm == null) continue;
                    if (MailForm.exceptmail == null) MailForm.exceptmail = string.Empty;
                    if (MailForm.exceptmailcc == null) MailForm.exceptmailcc = string.Empty;
                    if (string.IsNullOrEmpty(MailForm.subject) || string.IsNullOrEmpty(MailForm.tolist)) continue;

                    //오늘날짜로  데이터가 등록되어있느지 확인한다.
                    var Existweek = taMailData.GetData(vGcode, str_dt, vCate).Where(t => t.tolist.Equals("chikyun.kim@amkor.co.kr") == false && t.wuid.Equals("debug") == false).Any();
                    if (Existweek) continue;

                    var projects = taPrjList.GetData(vGcode);
                    //addmsg($"[{vGcode}] {projects.Count} 건의 데이터가 확인 되었습니다");

                    //메일데이터 생성
                    var body = new System.Text.StringBuilder();
                    body.AppendLine("<table border='1' cellspacing='1' cellpadding='1'  style='text-align:center;'>");
                    body.AppendLine("<tr>");
                    body.AppendLine("<td>시작일</td>");
                    body.AppendLine("<td>상태</td>");
                    body.AppendLine("<td>번호</td>");
                    body.AppendLine("<td>Project</td>");
                    body.AppendLine("<td>요청</td>");
                    body.AppendLine("<td>Champion</td>");
                    body.AppendLine("<td>협업</td>");
                    body.AppendLine("<td>만료일</td>");
                    body.AppendLine("<td>수량</td>");
                    body.AppendLine("<td>외주금액</td>");
                    body.AppendLine("<td>자체금액</td>");
                    body.AppendLine("<td>절감액</td>");
                    body.AppendLine("<td>CR/CF</td>");
                    body.AppendLine("</tr>");

                    //var gp = projects.GroupBy(t => t.idx);
                    foreach (var row in projects)
                    {
                        //스케쥴에서 데이터를 찾는다.
                        var cnt = taSche.GetData(vGcode, row.idx).Any();
                        if (cnt == true) continue;

                        body.AppendLine($"<tr>");
                        body.AppendLine($"<td>{row.sdate}</td>");
                        body.AppendLine($"<td>{row.status}</td>");
                        body.AppendLine($"<td>{row.idx}</td>");
                        body.AppendLine($"<td>{row.name}</td>");
                        body.AppendLine($"<td>{row.reqstaff}</td>");
                        body.AppendLine($"<td>{row.userManager}</td>");
                        body.AppendLine($"<td>{row.usermain}/{row.usersub}/{row.userhw2}</td>");
                        body.AppendLine($"<td>{row.edate}</td>");
                        body.AppendLine($"<td>{row.cnt}</td>");
                        body.AppendLine($"<td>{row.costo}</td>");
                        body.AppendLine($"<td>{row.costn}</td>");
                        body.AppendLine($"<td>{row.costo - row.costn}</td>");
                        body.AppendLine($"<td>{row.orderno}</td>");
                        body.AppendLine($"</tr>");
                    }
                    body.AppendLine("</table>");

                    //일별경고(월요일제외)

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

                        //메일본문을 생성해서 진행해야함
                        var mail_content = mail_body.Replace("{data}", body.ToString());

                        mail_to = MailSort(mail_to, MailForm.exceptmail);
                        if (string.IsNullOrEmpty(mail_to) == false)
                        {
                            using (var dt = new DSMail.MailDataDataTable())
                            {
                                var newdr = dt.NewMailDataRow();
                                newdr.gcode = vGcode;
                                newdr.cate = vCate;
                                newdr.subject = mail_subject;
                                newdr.fromlist = "EETGW@amkor.co.kr";
                                newdr.tolist = mail_to;// MailSort(mail_to, MailForm.exceptmail);
                                newdr.bcc = mail_bcc;
                                newdr.cc = MailSort(mail_cc, MailForm.exceptmailcc);
                                newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
                                newdr.body = mail_content;
                                newdr.wuid = "dev";// "dev";
                                newdr.wdate = DateTime.Now;
                                if (System.Diagnostics.Debugger.IsAttached)
                                {
                                    newdr.tolist = "chikyun.kim@amkor.co.kr";
                                    newdr.bcc = string.Empty;
                                    newdr.cc = string.Empty;
                                    newdr.wuid = "debug";
                                }
                                newdr.EndEdit();
                                dt.AddMailDataRow(newdr);
                                var CNT = taMailData.Update(newdr);
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                using (var dt = new DSMail.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.ToString("yyyy-MM-dd");
                    newdr.body = ex.Message;
                    newdr.wuid = "dev";// "dev";
                    newdr.wdate = DateTime.Now;
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        newdr.tolist = "chikyun.kim@amkor.co.kr";
                        newdr.bcc = string.Empty;
                        newdr.cc = string.Empty;
                        newdr.wuid = "debug";
                    }
                    newdr.EndEdit();
                    dt.AddMailDataRow(newdr);
                    var cnt = taMailData.Update(dt);
                }
            }

            taForm.Dispose();
            taMailData.Dispose();
            taSche.Dispose();
            taPrjList.Dispose();

        }

        /// <summary>
        /// 스케쥴기한임박알림(일)
        /// </summary>
        public static void Mail_MakeScheduleDay()
        {
            var taForm = new DSMailTableAdapters.MailFormTableAdapter();
            var taMailData = new DSMailTableAdapters.MailDataTableAdapter();
            var taMailPrjSche = new DSMailTableAdapters.vMailingProjectScheduleTableAdapter();
            var vCate = "SJ";
            try
            {
                var sd = DateTime.Now.AddDays(-15);
                var ed = DateTime.Now;
                var str_sd = sd.ToString("yyyy-MM-dd");
                var str_ed = ed.ToString("yyyy-MM-dd");
                var str_dt = DateTime.Now.ToString("yyyy-MM-dd");

                var gcodelist = DatabaseManager.getGroupListWithoutGcode("gcode", "MailForm", "gcode is not null and gcode <> 'DEV'");
                foreach (var vGcode in gcodelist)
                {
                    //메일기능이 꺼져있다면 처리하지 않는다.
                    var usemail = DatabaseManager.GetGroupEnableMail(vGcode);
                    if (usemail == false) continue;

                    //메일양식이 지정되어있는지 체크
                    var MailForm = taForm.GetData(vGcode, vCate).FirstOrDefault();
                    if (MailForm == null) continue;
                    if (MailForm.exceptmail == null) MailForm.exceptmail = string.Empty;
                    if (MailForm.exceptmailcc == null) MailForm.exceptmailcc = string.Empty;
                    if (string.IsNullOrEmpty(MailForm.subject) || string.IsNullOrEmpty(MailForm.tolist)) continue;

                    //오늘날짜로  데이터가 등록되어있느지 확인한다.
                    var Existweek = taMailData.GetData(vGcode, str_dt, vCate).Where(t => t.tolist.Equals("chikyun.kim@amkor.co.kr") == false && t.wuid.Equals("debug") == false).Any();
                    if (Existweek) continue;

                    //대상 사용자 목록을 추출한다
                    //var ta = new DataSet1TableAdapters.vMailingProjectScheduleTableAdapter();
                    var users = new DSMail.vMailingProjectScheduleDataTable();
                    taMailPrjSche.Fill(users, vGcode);
                    //var users = db.vMailingProjectSchedule.ToList();// .vJobReportForUser.Where(t => t.gcode == Pub.vGcode).GroupBy(t => t.id);

                    //addmsg($"[{vGcode}] {users.Count} 명의 데이터가 확인 되었습니다");

                    //메일데이터 생성
                    var body = new System.Text.StringBuilder();
                    body.AppendLine("<table border='1' cellspacing='1' cellpadding='1'  style='text-align:center;'>");
                    body.AppendLine("<tr>");
                    body.AppendLine("<td>진행(%)</td>");
                    body.AppendLine("<td>Project</td>");
                    body.AppendLine("<td>Champion</td>");
                    body.AppendLine("<td>등록일</td>");
                    body.AppendLine("<td>스케쥴</td>");
                    body.AppendLine("</tr>");

                    var gp = users.GroupBy(t => t.idx);
                    foreach (var row in gp)
                    {
                        var prc = row.Sum(t => t.progress) / row.Count();
                        var dr = row.FirstOrDefault();
                        body.AppendLine($"<tr>");
                        body.AppendLine($"<td>{prc}</td>");
                        body.AppendLine($"<td>[{dr.idx}] {dr.name}</td>");
                        body.AppendLine($"<td>{dr.userManager}</td>");
                        body.AppendLine($"<td>{dr.pdate}</td>");
                        body.AppendLine("<td>");
                        body.AppendLine("<table border='1' cellspacing='1' cellpadding='1' style='text-align:center;'>");
                        body.AppendLine("<tr>");
                        body.AppendLine("<td rowspan='2'>No</td><td rowspan='2'>Title</td><td colspan='2'>Plan(ww)</td><td colspan='2'>Actual(ww)</td><td>진행</td><td>비고</td>");
                        body.AppendLine("</tr>");
                        body.AppendLine("<tr>");
                        body.AppendLine("<td>시작</td><td>완료</td><td>시작</td><td>완료</td><td>%</td><td>&nbsp;</td>");
                        body.AppendLine("</tr>");
                        var ll = row.OrderBy(t => t.seq).ToList();
                        foreach (var srow in ll)
                        {
                            body.AppendLine($"<tr>");
                            body.AppendLine($"<td>{srow.seq}</td>");
                            body.AppendLine($"<td>{srow.title}</td>");
                            body.AppendLine($"<td>{srow.sw}</td>");
                            body.AppendLine($"<td>{srow.ew}</td>");
                            body.AppendLine($"<td>{srow.swa}</td>");
                            body.AppendLine($"<td>{srow.ewa}</td>");
                            body.AppendLine($"<td>{srow.progress}</td>");
                            body.AppendLine($"<td>{srow.memo}</td>");
                            body.AppendLine($"</tr>");
                        }
                        body.AppendLine("</table>");
                        body.AppendLine("</td>");
                        //여기에 스케쥴이 들어가야한다
                        body.AppendLine($"</tr>");
                    }
                    body.AppendLine("</table>");

                    //일별경고(월요일제외)

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

                    //메일본문을 생성해서 진행해야함
                    var mail_content = mail_body.Replace("{data}", body.ToString());

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

                    mail_to = MailSort(mail_to, MailForm.exceptmail);
                    if (string.IsNullOrEmpty(mail_to) == false)
                    {
                        using (var dt = new DSMail.MailDataDataTable())
                        {
                            var newdr = dt.NewMailDataRow();
                            newdr.gcode = vGcode;
                            newdr.cate = vCate;
                            newdr.subject = mail_subject;
                            newdr.fromlist = "eetgw@amkor.co.kr";
                            newdr.tolist = mail_to;// MailSort(mail_to, MailJD.exceptmail);
                            newdr.bcc = mail_bcc;
                            newdr.cc = MailSort(mail_cc, MailForm.exceptmailcc);
                            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
                            newdr.body = mail_content;
                            newdr.wuid = "dev";// "dev";
                            newdr.wdate = DateTime.Now;
                            if (System.Diagnostics.Debugger.IsAttached)
                            {
                                newdr.tolist = "chikyun.kim@amkor.co.kr";
                                newdr.bcc = string.Empty;
                                newdr.cc = string.Empty;
                                newdr.wuid = "debug";
                            }
                            newdr.EndEdit();
                            dt.AddMailDataRow(newdr);
                            taMailData.Update(dt);
                        }
                    }
                    //}
                }
            }
            catch (Exception ex)
            {

                using (var dt = new DSMail.MailDataDataTable())
                {
                    var newdr = dt.NewMailDataRow();
                    newdr.gcode = "EET1P";
                    newdr.cate = "ER";
                    newdr.subject = "[ERROR] 스케쥴(day) 메일작성 실패";
                    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.ToString("yyyy-MM-dd");
                    newdr.body = ex.Message;
                    newdr.wuid = "dev";// "dev";
                    newdr.wdate = DateTime.Now;
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        newdr.tolist = "chikyun.kim@amkor.co.kr";
                        newdr.bcc = string.Empty;
                        newdr.cc = string.Empty;
                        newdr.wuid = "debug";
                    }
                    newdr.EndEdit();
                    dt.AddMailDataRow(newdr);
                    var cnt = taMailData.Update(dt);
                }

            }
            taMailData.Dispose();
            taForm.Dispose();
            taMailPrjSche.Dispose();
        }


        /// <summary>
        /// 스케쥴기한임박알림(주)
        /// </summary>
        public static void Mail_MakeScheduleDayWeek()
        {

            var taForm = new DSMailTableAdapters.MailFormTableAdapter();
            var taMailData = new DSMailTableAdapters.MailDataTableAdapter();
            var taMailPrjSche = new DSMailTableAdapters.vMailingProjectScheduleTableAdapter();
            var vCate = "SP";
            try
            {
                Console.WriteLine("스케쥴기한임박자료(주) 미 작성자 추출 작업을 시작 합니다");
                var gcodelist = DatabaseManager.getGroupListWithoutGcode("gcode", "MailForm", "gcode is not null and gcode <> 'DEV'");

                //var db = new EEEntities();

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

                //var gcodelist = db.MailForm.GroupBy(t => t.gcode).ToList();

                foreach (var vGcode in gcodelist)
                {
                    //메일기능이 꺼져있다면 처리하지 않는다.
                    var usemail = DatabaseManager.GetGroupEnableMail(vGcode);
                    if (usemail == false) continue;

                    //메일양식이 지정되어있는지 체크
                    var MailJD = taForm.GetData(vGcode, vCate).FirstOrDefault();
                    if (MailJD == null) continue;
                    if (MailJD.exceptmail == null) MailJD.exceptmail = string.Empty;
                    if (MailJD.exceptmailcc == null) MailJD.exceptmailcc = string.Empty;
                    if (string.IsNullOrEmpty(MailJD.subject) || string.IsNullOrEmpty(MailJD.tolist)) continue;

                    //오늘날짜로  데이터가 등록되어있느지 확인한다.
                    var Existweek = taMailData.GetData(vGcode, str_dt, vCate).Where(t => t.tolist.Equals("chikyun.kim@amkor.co.kr") == false && t.wuid.Equals("debug") == false).Any();
                    if (Existweek) return;

                    //대상 사용자 목록을 추출한다
                    var datas = new DSMail.vMailingProjectScheduleDataTable();
                    taMailPrjSche.Fill(datas, vGcode);
                    //var users = db.vMailingProjectSchedule.ToList();// .vJobReportForUser.Where(t => t.gcode == Pub.vGcode).GroupBy(t => t.id);

                    //Console.WriteLine($"[{vGcode}] {users.Count} 명의 데이터가 확인 되었습니다");// ();

                    //메일데이터 생성
                    var body = new System.Text.StringBuilder();
                    body.AppendLine("<table border='1' cellspacing='1' cellpadding='1'  style='text-align:center;'>");
                    body.AppendLine("<tr>");
                    body.AppendLine("<td>진행(%)</td>");
                    body.AppendLine("<td>Project</td>");
                    body.AppendLine("<td>Champion</td>");
                    body.AppendLine("<td>등록일</td>");
                    body.AppendLine("<td>스케쥴</td>");
                    body.AppendLine("</tr>");

                    var gp = datas.GroupBy(t => t.idx);
                    foreach (var row in gp)
                    {
                        var prc = row.Sum(t => t.progress) / row.Count();
                        var dr = row.FirstOrDefault();
                        body.AppendLine($"<tr>");
                        body.AppendLine($"<td>{prc}</td>");
                        body.AppendLine($"<td>[{dr.idx}] {dr.name}</td>");
                        body.AppendLine($"<td>{dr.userManager}</td>");
                        body.AppendLine($"<td>{dr.pdate}</td>");
                        body.AppendLine("<td>");
                        body.AppendLine("<table border='1' cellspacing='1' cellpadding='1' style='text-align:center;'>");
                        body.AppendLine("<tr>");
                        body.AppendLine("<td rowspan='2'>No</td><td rowspan='2'>Title</td><td colspan='2'>Plan(ww)</td><td colspan='2'>Actual(ww)</td><td>진행</td><td>비고</td>");
                        body.AppendLine("</tr>");
                        body.AppendLine("<tr>");
                        body.AppendLine("<td>시작</td><td>완료</td><td>시작</td><td>완료</td><td>%</td><td>&nbsp;</td>");
                        body.AppendLine("</tr>");
                        var ll = row.OrderBy(t => t.seq).ToList();
                        foreach (var srow in ll)
                        {
                            body.AppendLine($"<tr>");
                            body.AppendLine($"<td>{srow.seq}</td>");
                            body.AppendLine($"<td>{srow.title}</td>");
                            body.AppendLine($"<td>{srow.sw}</td>");
                            body.AppendLine($"<td>{srow.ew}</td>");
                            body.AppendLine($"<td>{srow.swa}</td>");
                            body.AppendLine($"<td>{srow.ewa}</td>");
                            body.AppendLine($"<td>{srow.progress}</td>");
                            body.AppendLine($"<td>{srow.memo}</td>");
                            body.AppendLine($"</tr>");
                        }
                        body.AppendLine("</table>");
                        body.AppendLine("</td>");
                        //여기에 스케쥴이 들어가야한다
                        body.AppendLine($"</tr>");
                    }
                    body.AppendLine("</table>");

                    //일별경고(월요일제외)
                    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 = mail_body.Replace("{data}", body.ToString());

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

                    mail_to = MailSort(mail_to, MailJD.exceptmail);
                    if (string.IsNullOrEmpty(mail_to) == false)
                    {
                        using (var dt = new DSMail.MailDataDataTable())
                        {
                            var newdr = dt.NewMailDataRow();
                            newdr.gcode = vGcode;
                            newdr.cate = vCate;
                            newdr.subject = mail_subject;
                            newdr.fromlist = "eetgw@amkor.co.kr";
                            newdr.tolist = mail_to;// MailSort(mail_to, MailJD.exceptmail);
                            newdr.bcc = mail_bcc;
                            newdr.cc = MailSort(mail_cc, MailJD.exceptmailcc);
                            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
                            newdr.body = mail_content;
                            newdr.wuid = "dev";// "dev";
                            newdr.wdate = DateTime.Now;

                            if (System.Diagnostics.Debugger.IsAttached)
                            {
                                newdr.tolist = "chikyun.kim@amkor.co.kr";
                                newdr.bcc = string.Empty;
                                newdr.cc = string.Empty;
                                newdr.wuid = "debug";
                            }
                            newdr.EndEdit();
                            dt.AddMailDataRow(newdr);
                            taMailData.Update(dt);// db.SaveChanges();
                            Console.WriteLine($"[{vGcode}] 메일 전송 완료(스케쥴day)");
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                using (var dt = new DSMail.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.ToString("yyyy-MM-dd");
                    newdr.body = ex.Message;
                    newdr.wuid = "dev";// "dev";
                    newdr.wdate = DateTime.Now;
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        newdr.tolist = "chikyun.kim@amkor.co.kr";
                        newdr.bcc = string.Empty;
                        newdr.cc = string.Empty;
                        newdr.wuid = "debug";
                    }
                    newdr.EndEdit();
                    dt.AddMailDataRow(newdr);
                    var cnt = taMailData.Update(dt);
                }

            }
            finally
            {
                ChkMakeSchDayWeekTime = DateTime.Now;
            }

            taForm.Dispose();
            taMailData.Dispose();
            taMailPrjSche.Dispose();
        }



        /// <summary>
        /// 프로젝트업데이트요청(주)
        /// </summary>
        public static void Mail_MakeUpdateRequireProject()
        {

            var taForm = new DSMailTableAdapters.MailFormTableAdapter();
            var taMailData = new DSMailTableAdapters.MailDataTableAdapter();
            //var taMailPrjSche = new DSMailTableAdapters.vMailingProjectScheduleTableAdapter();
            var vCate = "PN";
            try
            {
                Console.WriteLine("프로젝트업데이트요청(주) 미 작성자 추출 작업을 시작 합니다");
                var gcodelist = DatabaseManager.getGroupListWithoutGcode("gcode", "MailForm", "gcode is not null and gcode <> 'DEV'");

                //var db = new EEEntities();
                //기준일자는 오늘부터 -15일이다
                //var sd = DateTime.Now.AddDays(-15);
                //var ed = DateTime.Now;
                //var str_sd = sd.ToString("yyyy-MM-dd");
                //var str_ed = ed.ToString("yyyy-MM-dd");

                var str_dt = DateTime.Now.ToString("yyyy-MM-dd");
                var sql = "select (select isnull(max(pdate),'') from ProjectsHistory where pidx = Projects.idx) as LastHistory," +
                    " idx,status,name,sdate,ddate,orderno as CR,crdue,dbo.getUserName(isnull(championid,usermanager)) as NameChampion," +
                    " dbo.getUserName(isnull(designid,usermain)) as NameDesign,dbo.getUserName(isnull(epanelid,userhw2)) as NameEPanel," +
                    " dbo.getUserName(isnull(softwareid,usersub)) as NameSoftware,championid as IdChampion,designid as IdDesign," +
                    " epanelid as IdEPanel,softwareid as IdSoftware " +
                    " from Projects where gcode = @gcode and status = '진행'" +
                    $" and pdate >= '{DateTime.Now.AddYears(-2).ToString("yyyy-MM-dd")}'";
                var cs = Properties.Settings.Default.cs;
                var cn = new System.Data.SqlClient.SqlConnection(cs);
                var cmd = new SqlCommand(sql, cn);
                cmd.Parameters.Add("gcode", System.Data.SqlDbType.VarChar);
                cn.Open();


                //대상 그룹코드를 모두 확인한다
                foreach (var vGcode in gcodelist)
                {
                    //메일기능이 꺼져있다면 처리하지 않는다.
                    var usemail = DatabaseManager.GetGroupEnableMail(vGcode);
                    if (usemail == false) continue;

                    //메일양식이 지정되어있는지 체크
                    var MailJD = taForm.GetData(vGcode, vCate).FirstOrDefault();
                    if (MailJD == null) continue;
                    if (MailJD.exceptmail == null) MailJD.exceptmail = string.Empty;
                    if (MailJD.exceptmailcc == null) MailJD.exceptmailcc = string.Empty;
                    if (string.IsNullOrEmpty(MailJD.subject) || string.IsNullOrEmpty(MailJD.tolist)) continue;

                    //오늘날짜로  데이터가 등록되어있느지 확인한다.
                    var Existweek = taMailData.GetData(vGcode, str_dt, vCate).Where(t => t.tolist.Equals("chikyun.kim@amkor.co.kr") == false && t.wuid.Equals("debug") == false).Any();
                    if (Existweek) return;

                    cmd.Parameters[0].Value = vGcode;

                    //메일데이터 생성
                    var body = new System.Text.StringBuilder();
                    body.AppendLine("<table border='1' cellspacing='1' cellpadding='1'  style='text-align:center;'>");
                    body.AppendLine("<tr>");
                    body.AppendLine("<td>idx</td>");
                    body.AppendLine("<td>Project</td>");
                    body.AppendLine("<td>LastUpdate</td>");
                    body.AppendLine("<td>Champion</td>");
                    body.AppendLine("<td>Design</td>");
                    body.AppendLine("<td>EPanel</td>");
                    body.AppendLine("<td>Software</td>");
                    body.AppendLine("<td>Start</td>");
                    body.AppendLine("<td>Due</td>");
                    body.AppendLine("</tr>");

                    var gp = cmd.ExecuteReader();

                    List<string> emaillist = new List<string>();
                    while (gp.Read())
                    {
                        var lasthistory = gp[0]?.ToString() ?? string.Empty;
                        var prjidx = gp["idx"]?.ToString() ?? string.Empty;
                        var prjname = gp["name"]?.ToString() ?? string.Empty;
                        var prjstart = gp["sdate"]?.ToString() ?? string.Empty;
                        var prjend = gp["ddate"]?.ToString() ?? string.Empty;

                        var NameChampion = gp["NameChampion"]?.ToString() ?? string.Empty;
                        var NameDesign = gp["NameDesign"]?.ToString() ?? string.Empty;
                        var NameEPanel = gp["NameEPanel"]?.ToString() ?? string.Empty;
                        var NameSoftware = gp["NameSoftware"]?.ToString() ?? string.Empty;

                        var IdChampion = gp["IdChampion"]?.ToString() ?? string.Empty;
                        var IdDesign = gp["IdDesign"]?.ToString() ?? string.Empty;
                        var IdEPanel = gp["IdEPanel"]?.ToString() ?? string.Empty;
                        var IdSoftware = gp["IdSoftware"]?.ToString() ?? string.Empty;

                        if (string.IsNullOrEmpty(lasthistory) == false)
                        {
                            //일주일 전이라면 넘어간다.
                            if (DateTime.TryParse(lasthistory, out DateTime lastindate))
                            {
                                if (lastindate >= DateTime.Now.AddDays(-7)) continue;
                            }
                        }

                        //담당자의 메일주소를 취합해야한다.
                        var email_champion = DatabaseManager.GetUserEmail(vGcode, IdChampion);
                        var email_design = DatabaseManager.GetUserEmail(vGcode, IdDesign);
                        var email_epanel = DatabaseManager.GetUserEmail(vGcode, IdEPanel);
                        var email_software = DatabaseManager.GetUserEmail(vGcode, IdSoftware);
                        if (string.IsNullOrEmpty(email_champion) == false && emaillist.Contains(email_champion) == false) emaillist.Add(email_champion);
                        if (string.IsNullOrEmpty(email_design) == false && emaillist.Contains(email_design) == false) emaillist.Add(email_design);
                        if (string.IsNullOrEmpty(email_epanel) == false && emaillist.Contains(email_epanel) == false) emaillist.Add(email_epanel);
                        if (string.IsNullOrEmpty(email_software) == false && emaillist.Contains(email_software) == false) emaillist.Add(email_software);

                        body.AppendLine($"<tr>");
                        body.AppendLine($"<td>{prjidx}</td>");
                        body.AppendLine($"<td>{prjname}</td>");
                        body.AppendLine($"<td>{lasthistory}</td>");
                        body.AppendLine($"<td>{NameChampion}</td>");
                        body.AppendLine($"<td>{NameDesign}</td>");
                        body.AppendLine($"<td>{NameEPanel}</td>");
                        body.AppendLine($"<td>{NameSoftware}</td>");
                        body.AppendLine($"<td>{prjstart}</td>");
                        body.AppendLine($"<td>{prjend}</td>");
                        body.AppendLine("</tr>");
                    }
                    body.AppendLine("</table>");

                    //일별경고(월요일제외)
                    var mail_subject = MailJD.subject;//.Replace("{담당자}", userinfo.name).Replace("{사번}", userinfo.id);
                    var mail_to = MailJD.tolist;
                    if (emaillist.Any() && mail_to.Contains("{")) mail_to = mail_to.Replace("{담당자}", string.Join(";", emaillist));

                    var mail_cc = string.Empty; //
                    if (MailJD.cc != null) mail_cc = MailJD.cc;//.Replace("{담당자}", userinfo.email);
                    if (emaillist.Any() && mail_cc.Contains("{")) mail_cc = mail_cc.Replace("{담당자}", string.Join(";", emaillist));


                    var mail_bcc = string.Empty;
                    if (MailJD.bcc != null) mail_bcc = MailJD.bcc;//.Replace("{담당자}", userinfo.email);
                    if (emaillist.Any() && mail_bcc.Contains("{")) mail_bcc = mail_bcc.Replace("{담당자}", string.Join(";", emaillist));


                    var mail_body = MailJD.body;//.Replace("{담당자}", userinfo.name);
                                                //mail_body = mail_body.Replace("{사번}", userinfo.id);

                    //메일본문을 생성해서 진행해야함
                    var mail_content = mail_body;
                    if (mail_content.Contains("{data}"))
                        mail_content = mail_content.Replace("{data}", body.ToString());
                    else
                        mail_content += "<br />" + body.ToString();

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

                    mail_to = MailSort(mail_to, MailJD.exceptmail);
                    if (string.IsNullOrEmpty(mail_to) == false)
                    {
                        using (var dt = new DSMail.MailDataDataTable())
                        {
                            var newdr = dt.NewMailDataRow();
                            newdr.gcode = vGcode;
                            newdr.cate = vCate;
                            newdr.subject = mail_subject;
                            newdr.fromlist = "eetgw@amkor.co.kr";
                            newdr.tolist = mail_to;// MailSort(mail_to, MailJD.exceptmail);
                            newdr.bcc = mail_bcc;
                            newdr.cc = MailSort(mail_cc, MailJD.exceptmailcc);
                            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
                            newdr.body = mail_content;
                            newdr.wuid = "dev";// "dev";
                            newdr.wdate = DateTime.Now;

                            if (System.Diagnostics.Debugger.IsAttached)
                            {
                                newdr.tolist = "chikyun.kim@amkor.co.kr";
                                newdr.bcc = string.Empty;
                                newdr.cc = string.Empty;
                                newdr.wuid = "debug";
                            }
                            newdr.EndEdit();
                            dt.AddMailDataRow(newdr);
                            var cnt = taMailData.Update(dt);// db.SaveChanges();
                            Console.WriteLine($"[{vGcode}] 메일 전송 완료(프로젝트업데이트)");
                        }
                    }
                }

                cmd.Dispose();
                cn.Close();
                cn.Dispose();
            }
            catch (Exception ex)
            {

                using (var dt = new DSMail.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.ToString("yyyy-MM-dd");//.ToString("yyyy-MM-dd");
                    newdr.body = ex.Message;
                    newdr.wuid = "dev";// "dev";
                    newdr.wdate = DateTime.Now;
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        newdr.tolist = "chikyun.kim@amkor.co.kr";
                        newdr.bcc = string.Empty;
                        newdr.cc = string.Empty;
                        newdr.wuid = "debug";
                    }
                    newdr.EndEdit();
                    dt.AddMailDataRow(newdr);
                    var cnt = taMailData.Update(dt);
                }

            }
            finally
            {
                ChkMakeSchDayWeekTime = DateTime.Now;
            }

            taForm.Dispose();
            taMailData.Dispose();
        }

        /// <summary>
        /// 전송되지 않은 메일을 확인하고 그것을 전송한다
        /// </summary>
        public static void SendMail()
        {

            var timestr = DateTime.Now.ToString("yyMMddHHmmss");
            //메일서버역할이 있다.
            try
            {
                var cn = new System.Data.SqlClient.SqlConnection(Properties.Settings.Default.gwcs);
                var cmd = new System.Data.SqlClient.SqlCommand("", cn);
                //var gcode = FCOMMON.info.Login.gcode;
                cn.Open();

                //1개의데이터 가져오기
                var wdate = DateTime.Now.AddDays(-7);
                cmd.CommandText = $"SELECT top 1  * FROM MailData WHERE ISNULL(SendOK2, 0) = 0 and wdate >= '{wdate:yyyy-MM-dd} 00:00:00' order by wdate";
                var dar = cmd.ExecuteReader();

                var list_from = string.Empty;// getMaillist(dar["fromlist"]);
                var list_to = string.Empty;// getMaillist(dar["tolist"]);
                var list_bcc = string.Empty;// getMaillist(dar["bcc"]);
                var list_cc = string.Empty;//getMaillist(dar["cc"]);
                var subject = string.Empty;// getdbdata(dar["subject"]).Trim();
                var body = string.Empty;//getdbdata(dar["body"]).Trim();
                var idx = -1;
                var pdate = string.Empty;
                var developer = string.Empty;



                while (dar.Read())
                {
                    list_from = getMaillist(dar["fromlist"]);
                    list_to = getMaillist(dar["tolist"]);
                    list_bcc = getMaillist(dar["bcc"]);
                    list_cc = getMaillist(dar["cc"]);

                    pdate = dar["wdate"].ToString();
                    subject = getdbdata(dar["subject"]).Trim();
                    body = getdbdata(dar["body"]).Trim();
                    idx = (int)dar["idx"];
                    developer = getdbdata(dar["developer"]);
                }
                dar.Close();

                string sendMsg = "";
                if (string.IsNullOrEmpty(list_from))
                {
                    sendMsg = ("보내는 주소가 없습니다");
                }
                else if (string.IsNullOrEmpty(subject.Trim()))
                {
                    sendMsg = ("메일 제목이 없습니다");
                }
                else if (string.IsNullOrEmpty(body.Trim()))
                {
                    sendMsg = ("본문이 없습니다");
                }
                else if (string.IsNullOrEmpty(list_to.Trim()))
                {
                    sendMsg = ("받는 주소가 없습니다");
                }

                if (idx > 0)
                {
                    //오류메시지가 있다면 업데이트만 한다
                    if (string.IsNullOrWhiteSpace(sendMsg) == false)
                    {
                        //오류가 있다
                        try
                        {
                            cmd.CommandText = "UPDATE MailData SET SendOK2 = 1, SendMsg2 = @msg ,suid2=@suid,sdate2 = @sdate WHERE(idx = @idx) and isnull(sendok2,0) = 0";
                            cmd.Parameters.Clear();
                            cmd.Parameters.Add("msg", System.Data.SqlDbType.VarChar).Value = sendMsg;
                            cmd.Parameters.Add("idx", System.Data.SqlDbType.Int).Value = idx;
                            cmd.Parameters.Add("suid", System.Data.SqlDbType.VarChar).Value = "dev";
                            cmd.Parameters.Add("sdate", System.Data.SqlDbType.SmallDateTime).Value = DateTime.Now;

                            //Console.WriteLine(string.Format("Send Complete index={0},Msg={1}", dar["idx"], sendMsg));
                            //ta.UpdateSendOK(sendMsg, dr.idx);
                            var ucnt = cmd.ExecuteNonQuery();
                            Console.Write($"[{timestr}]-IDX:{idx} [{pdate}] ErrorMessage Update Subject:{getdbdata(subject)} Messqage:{sendMsg}");
                            if (ucnt == 1)
                            {
                                Console.WriteLine($" [OK]");
                            }
                            else
                            {
                                Console.WriteLine($" [ERR COUNT={ucnt}]");
                            }
                        }
                        catch (Exception eX)
                        {
                            sendMsg = eX.Message;
                        }
                    }
                    else
                    {
                        //var body = getdbdata(dar["body"]);
                        if (String.IsNullOrEmpty(developer)) developer = "chikyun.kim@amkor.co.kr";
                        body +=
                            $"<p>" +
                            $"<br />이 메일은 EET 프로그램에서 자동 발신 되었습니다." +
                            $"<br />메일이 잘못 전송 되었다면 [<a href='{developer}'>{developer}</a>] 로 문의 주시기 바랍니다" +
                            $"</p>";

                        subject = subject.Replace("\r", "").Replace("\n", "");
                        body = body.Replace("\r", "").Replace("\n", "");

                        var tolist = list_to.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        var bcclist = list_bcc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        var cclist = list_cc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                        var externalmail = false;
                        foreach (var item in tolist)
                            if (item.ToLower().EndsWith("amkor.co.kr") == false)
                            {
                                externalmail = true;
                                break;
                            }
                        foreach (var item in bcclist)
                            if (item.ToLower().EndsWith("amkor.co.kr") == false)
                            {
                                externalmail = true;
                                break;
                            }
                        foreach (var item in cclist)
                            if (item.ToLower().EndsWith("amkor.co.kr") == false)
                            {
                                externalmail = true;
                                break;
                            }
                        //                        ATK Exim 접속 정보
                        //ATK Exim Domain: k5lexim01.kr.ds.amkor.com
                        //ATK Exim IP : 10.101.2.70
                        //ATK Exim Port: 25, 465, 587
                        var sendsuccess = false;

                        //"10.101.5.150"

                        //전송을 해야 함vvmffh123123
                        Chilkat.MailMan mailman = null;
                        Chilkat.Email email = null;
                        SmtpClient mc = null;
                        MailMessage msg = null;
                        if (externalmail)
                        {
                            mailman = new Chilkat.MailMan();
                            bool success = mailman.UnlockComponent("GAMACM.CB8082024_Tz2XiNck4U5N");
                            if (success == false) Console.WriteLine("license errr");
                            mailman.SmtpHost = "k5lexim01.kr.ds.amkor.com";
                            mailman.SmtpPort = 25;

                            mailman.SmtpUsername = "bookmanager";
                            mailman.SmtpPassword = "BIDA19R=maga2#H9gY[JPx%~M^NyIG";

                            email = new Chilkat.Email();
                            email.Subject = subject;
                            email.SetHtmlBody(body);
                            email.From = list_from;

                            foreach (var item in tolist)
                                email.AddTo(item, item);

                            //bcc

                            foreach (var item in bcclist)
                                email.AddBcc(item, item);

                            //cc

                            foreach (var item in cclist)
                                email.AddCC(item, item);

                        }
                        else
                        {
                            mc = new System.Net.Mail.SmtpClient("10.101.5.150");
                            msg = new System.Net.Mail.MailMessage
                               (list_from,
                               list_to,
                               subject,
                               body);

                            if (list_bcc != "") msg.Bcc.Add(list_bcc);
                            if (list_cc != "") msg.CC.Add(list_cc);
                            msg.IsBodyHtml = true;
                        }

                        //success = mailman.SendEmail(email);


                        bool msgupdate = false;
                        try
                        {
                            sendMsg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            cmd.CommandText = "UPDATE MailData SET SendOK2 = 1, SendMsg2 = @msg, suid2 = @suid,sdate2 = @sdate WHERE(idx = @idx) and isnull(sendok2,0) = 0";
                            cmd.Parameters.Clear();
                            cmd.Parameters.Add("msg", System.Data.SqlDbType.VarChar).Value = sendMsg;
                            cmd.Parameters.Add("idx", System.Data.SqlDbType.Int).Value = idx;
                            cmd.Parameters.Add("suid", System.Data.SqlDbType.VarChar).Value = "dev";
                            cmd.Parameters.Add("sdate", System.Data.SqlDbType.SmallDateTime).Value = DateTime.Now;
                            //Console.WriteLine(string.Format("Send Complete index={0},Msg={1}", dar["idx"], sendMsg));
                            //ta.UpdateSendOK(sendMsg, dr.idx);
                            var ucnt = cmd.ExecuteNonQuery();
                            if (ucnt == 1)
                            {
                                if (mailman != null)
                                {
                                    sendsuccess = mailman.SendEmail(email);
                                }
                                else
                                {
                                    try
                                    {
                                        mc.Send(msg);
                                        sendsuccess = true;
                                    }
                                    catch (Exception ex)
                                    {
                                        sendMsg = ex.Message;
                                        msgupdate = true;
                                        sendsuccess = false;
                                    }
                                }
                                if (sendsuccess == false) Console.WriteLine("send error");
                                else Console.WriteLine($"[{timestr}]-IDX:{idx} [{pdate}]  send mail to [" + list_to + "],subject=" + getdbdata(subject));
                            }
                        }
                        catch (Exception eX)
                        {
                            //오류가 발생하면 해당 오류메세지로 데이터를 업데이트 해준다.
                            Console.WriteLine($"[{timestr}]-IDX:{idx} [sendmail] : " + eX.Message);
                            sendMsg = eX.Message;
                            msgupdate = true;
                        }

                        try
                        {
                            if (msgupdate)
                            {
                                cmd.CommandText = "UPDATE MailData SET  SendMsg2 = @msg,suid2=@suid,sdate2=@sdate WHERE idx = @idx ";
                                cmd.Parameters.Clear();
                                cmd.Parameters.Add("idx", System.Data.SqlDbType.Int).Value = idx;
                                cmd.Parameters.Add("suid", System.Data.SqlDbType.VarChar).Value = "dev";
                                cmd.Parameters.Add("sdate", System.Data.SqlDbType.SmallDateTime).Value = DateTime.Now;
                                cmd.Parameters.Add("msg", System.Data.SqlDbType.VarChar).Value = sendMsg;
                                var ucnt = cmd.ExecuteNonQuery();
                            }
                        }
                        catch (Exception ex)
                        {
                            //sendMsg = eX.Message;
                            //msgupdate = true;
                            Console.WriteLine($"[{timestr}]-IDX:{idx} eror state update failed {ex.Message}");
                        }
                    }
                }




                cmd.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[{timestr}] [sendmail] {ex.Message}");
            }
            finally
            {
                ChkSendMailTime = DateTime.Now;
            }
        }

        /// <summary>
        /// 자동생성 메일 작성
        /// </summary>
        public static void MakeAutoMail()
        {
            try
            {
                var taData = new DSMailTableAdapters.MailDataTableAdapter();
                var taList = new DSMailTableAdapters.MailAutoTableAdapter();
                var dtList = taList.GetByAutoSend();
                var dtInsert = new DSMail.MailDataDataTable();

                //대상
                Console.WriteLine("Make Auto Send Mail Data (" + dtList.Rows.Count.ToString() + ")");

                foreach (DSMail.MailAutoRow dr in dtList)
                {
                    //메일기능이 꺼져있다면 처리하지 않는다.
                    var vGcode = dr.gcode;
                    var usemail = DatabaseManager.GetGroupEnableMail(vGcode);
                    if (usemail == false) continue;

                    //시간정보가 없는 애들은 처리 하지 않음
                    if (dr.stime.IndexOf(":") == -1) continue;
                    if (dr.sday == null || dr.sday.Length < 2) continue;

                    //발신시간을 넘어야 한다
                    var curTime = DateTime.Now.ToString("HH:mm");
                    if (string.Compare(curTime, dr.stime) < 0) continue;   //지정된 시간 이전이면 생성 안한다

                    //자동생성 구분용 카테고리
                    var cate = string.Format("{0},{1}", dr.sday[0], dr.sday[1]);

                    //동륵일
                    var pdate = DateTime.Now.ToString("yyyy-MM-dd");

                    //같은날, 같은 atime aidx pdate 의 같이 있으면 이미 생성된것이므로 추가하지 않는다
                    var existData = taData.FindAutoData(dr.idx, dr.stime, pdate, cate);
                    //var Existweek = taMailData.GetData(vGcode, str_dt, vCate).Where(t => t.tolist.Equals("chikyun.kim@amkor.co.kr") == false && t.wuid.Equals("debug") == false).Any();
                    var PreMakeCount = (int)(existData);
                    if (PreMakeCount > 0) continue;

                    //전송간격과 대상
                    if (dr.sday[0] == 1)
                    {
                        //week
                        var bitString = Convert.ToString(dr.sday[1], 2).PadLeft(8, '0').ToArray();
                        var weeknum = (int)(DateTime.Now.DayOfWeek);
                        if (bitString[weeknum + 1] == '0') continue;
                    }
                    else
                    {
                        //month
                        if (dr.sday[1] != DateTime.Now.Day) continue;
                    }

                    //같은날, 같은 atime aidx pdate 의 같이 있으면 이미 생성된것이므로 추가하지 않는다
                    //생성해야할 자료라면 만들어 준다
                    var newdr = dtInsert.NewMailDataRow();
                    newdr.pdate = pdate;// DateTime.Now.ToString("yyyy-MM-dd");
                    newdr.gcode = dr.gcode;
                    newdr.fromlist = dr.fromlist;
                    newdr.tolist = dr.tolist;
                    newdr.bcc = dr.bcc;
                    newdr.cate = cate;// string.Format("{0},{1}", dr.sday[0], dr.sday[1]);    //cate에 해당 자료를 기록한다.
                    newdr.cc = dr.cc;
                    newdr.subject = dr.subject;
                    newdr.body = dr.body;
                    newdr.aidx = dr.idx;
                    newdr.atime = dr.stime;
                    newdr.wuid = "dev";
                    newdr.wdate = DateTime.Now;
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        newdr.tolist = "chikyun.kim@amkor.co.kr";
                        newdr.bcc = string.Empty;
                        newdr.cc = string.Empty;
                        newdr.wuid = "debug";
                    }
                    newdr.EndEdit();
                    dtInsert.AddMailDataRow(newdr);
                    try
                    {
                        taData.Update(newdr);
                        Console.WriteLine("auto make : " + newdr.tolist + ",subject=" + newdr.subject);
                    }
                    catch (Exception eX)
                    {
                        Console.WriteLine("auto make error : " + eX.Message);
                    }
                }
            }
            catch
            {

            }
            finally
            {
                ChkMakeAutoTime = DateTime.Now;
            }
        }

        /// <summary>
        /// 휴가신청(Remind)
        /// </summary>
        public static void Mail_Take_a_rest_remind()
        {

            var taForm = new DSMailTableAdapters.MailFormTableAdapter();
            var taMailData = new DSMailTableAdapters.MailDataTableAdapter();
            var taMailPrjSche = new DSMailTableAdapters.vMailingProjectScheduleTableAdapter();
            var vCate = "HA";
            try
            {
                Console.WriteLine("휴가신청remind - 검출 시작");
                var gcodelist = DatabaseManager.getGroupListWithoutGcode("gcode", "MailForm", "gcode is not null and gcode <> 'DEV'");

                //var db = new EEEntities();

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

                //var gcodelist = db.MailForm.GroupBy(t => t.gcode).ToList();
                var cn = DatabaseManager.getCn();
                cn.Open();
                var cmd = new System.Data.SqlClient.SqlCommand("", cn);

                foreach (var vGcode in gcodelist)
                {
                    //메일기능이 꺼져있다면 처리하지 않는다.
                    var usemail = DatabaseManager.GetGroupEnableMail(vGcode);
                    if (usemail == false) continue;


                    //메일양식이 지정되어있는지 체크
                    var MailJD = taForm.GetData(vGcode, vCate).FirstOrDefault();
                    if (MailJD == null) continue;
                    if (MailJD.exceptmail == null) MailJD.exceptmail = string.Empty;
                    if (MailJD.exceptmailcc == null) MailJD.exceptmailcc = string.Empty;
                    if (string.IsNullOrEmpty(MailJD.subject) || string.IsNullOrEmpty(MailJD.tolist)) continue;

                    //오늘날짜로  데이터가 등록되어있느지 확인한다.
                    var Existweek = taMailData.GetData(vGcode, str_dt, vCate).Where(t => t.tolist.Equals("chikyun.kim@amkor.co.kr") == false && t.wuid.Equals("debug") == false).Any();
                    if (Existweek) return;

                    //대상 사용자 목록을 추출한다
                    var sql = "select datediff(day, getdate(),sdate ),uid,cate,sdate,edate,isnull(remark,'')" +
                        " ,holydays,holytimes from EETGW_HolydayRequest " +
                        $" where gcode = '{vGcode}'" +
                        " and isnull(conf,0) = 0" +
                        " and datediff(day, getdate(), sdate ) between - 100 and  2" +
                        " order by sdate desc";
                    cmd.CommandText = sql;
                    var dar = cmd.ExecuteReader();


                    //메일데이터 생성
                    var body = new System.Text.StringBuilder();
                    body.AppendLine("<table border='1' cellspacing='1' cellpadding='1'  style='text-align:center;'>");
                    body.AppendLine("<tr>");
                    body.AppendLine("<td>남은일수</td>");
                    body.AppendLine("<td>신청인</td>");
                    body.AppendLine("<td>형태</td>");
                    body.AppendLine("<td>시작일</td>");
                    body.AppendLine("<td>종료일</td>");
                    body.AppendLine("<td>일</td>");
                    body.AppendLine("<td>시간</td>");
                    body.AppendLine("<td>비고</td>");
                    body.AppendLine("</tr>");

                    while (dar.Read())
                    {
                        var idx = 0;
                        var remainday = int.Parse(dar[idx++].ToString());
                        var uid = dar[idx++].ToString();
                        var username = DatabaseManager.GetUserName(vGcode, uid);
                        var cate = dar[idx++].ToString();
                        var sdate = dar[idx++].ToString();
                        var edate = dar[idx++].ToString();
                        var remark = dar[idx++].ToString();
                        var o_days = dar[idx++];
                        var o_time = dar[idx++];
                        var v_days = string.Empty;
                        var v_time = string.Empty;
                        if (o_days != null) v_days = o_days.ToString();
                        if (o_time != null) v_time = o_time.ToString();

                        body.AppendLine($"<tr>");
                        body.AppendLine($"<td>{remainday}</td>");
                        body.AppendLine($"<td>[{uid}] {username}</td>");
                        body.AppendLine($"<td>{cate}</td>");
                        body.AppendLine($"<td>{sdate}</td>");
                        body.AppendLine($"<td>{edate}</td>");
                        body.AppendLine($"<td>{v_days}</td>");
                        body.AppendLine($"<td>{v_time}</td>");
                        body.AppendLine($"<td>{remark}</td>");
                        body.AppendLine("</tr>");
                    }
                    body.AppendLine("</table>");
                    dar.Close();

                    //일별경고(월요일제외)
                    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 = mail_body.Replace("{data}", body.ToString());

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

                    mail_to = MailSort(mail_to, MailJD.exceptmail);
                    if (string.IsNullOrEmpty(mail_to) == false)
                    {
                        using (var dt = new DSMail.MailDataDataTable())
                        {
                            var newdr = dt.NewMailDataRow();
                            newdr.gcode = vGcode;
                            newdr.cate = vCate;
                            newdr.subject = mail_subject;
                            newdr.fromlist = "eetgw@amkor.co.kr";
                            newdr.tolist = mail_to;// MailSort(mail_to, MailJD.exceptmail);
                            newdr.bcc = mail_bcc;
                            newdr.cc = MailSort(mail_cc, MailJD.exceptmailcc);
                            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
                            newdr.body = mail_content;
                            newdr.wuid = "dev";// "dev";
                            newdr.wdate = DateTime.Now;

                            if (System.Diagnostics.Debugger.IsAttached)
                            {
                                newdr.tolist = "chikyun.kim@amkor.co.kr";
                                newdr.bcc = string.Empty;
                                newdr.cc = string.Empty;
                                newdr.wuid = "debug";
                            }
                            newdr.EndEdit();
                            dt.AddMailDataRow(newdr);
                            taMailData.Update(dt);// db.SaveChanges();
                            Console.WriteLine($"[{vGcode}] 메일 전송 완료(holy remind)");
                        }
                    }
                }

                cmd.Dispose();
                cn.Close();
                cn.Dispose();
            }
            catch (Exception ex)
            {

                using (var dt = new DSMail.MailDataDataTable())
                {
                    var newdr = dt.NewMailDataRow();
                    newdr.gcode = "EET1P";
                    newdr.cate = "ER";
                    newdr.subject = "[ERROR] holy remind 메일작성 실패";
                    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.ToString("yyyy-MM-dd");//ToShortDateString();
                    newdr.body = ex.Message;
                    newdr.wuid = "dev";// "dev";
                    newdr.wdate = DateTime.Now;
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        newdr.tolist = "chikyun.kim@amkor.co.kr";
                        newdr.bcc = string.Empty;
                        newdr.cc = string.Empty;
                        newdr.wuid = "debug";
                    }
                    newdr.EndEdit();
                    dt.AddMailDataRow(newdr);
                    var cnt = taMailData.Update(dt);
                }

            }


            taForm.Dispose();
            taMailData.Dispose();
            taMailPrjSche.Dispose();
        }

    }
}
