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

        public fNoScheduleDayWeek()
        {
            InitializeComponent();
        }

        private void fJobReportDay_Load(object sender, EventArgs e)
        {
            task = Task.Run(() =>
            {
                while (taskrun)
                {
                    if (taskwait)
                    {
                        if (task != null)
                            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 < 10) //10시부터 동작한다
                    {
                        if ((DateTime.Now - ConsoleTime).TotalHours >= 1.0)
                        {
                            addmsg("9시 이전에는 동작하지 않습니다");
                            ConsoleTime = DateTime.Now;
                        }
                    }
                    else
                    {
                        ChkMakeSchDayWeekTime = DateTime.Now;
                        try
                        {
                            RunData();
                        }
                        catch (Exception ex)
                        {
                            addmsg(ex.Message);

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

                            task.Wait(5000);
                        }
                    }
                    Task.Delay(Delaytime).Wait();
                }

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

        void RunData()
        {
            addmsg("스케쥴입력(주) 미 작성자 추출 작업을 시작 합니다");

            var db = new EEEntities();

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

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

                //메일양식이 지정되어있는지 체크
                var MailJD = db.MailForm.AsNoTracking().Where(t => t.gcode == vGcode & t.cate == "SN").FirstOrDefault();
                if (MailJD == null)
                {
                    //토,일요일에는 동작하지 않는다
                    addmsg($"[{vGcode}] 메일 양식(SN)이 입력되지 않았습니다");
                    continue;
                }
                if (MailJD.exceptmail == null) MailJD.exceptmail = string.Empty;
                if (MailJD.exceptmailcc == null) MailJD.exceptmailcc = string.Empty;

                //오늘날짜로  데이터가 등록되어있느지 확인한다.
                db = new EEEntities();
                var Existweek = db.MailData.AsNoTracking().Where(t => t.gcode == vGcode && t.cate == "SN" && t.pdate == str_dt).Any();
                if (Existweek)
                {
                    addmsg($"[{vGcode}] 스케쥴(day)({str_dt}) 보고 메일이 이미 등록되어 있습니다");
                    continue;
                }

                //대상 사용자 목록을 추출한다
                //var ta = new DataSet1TableAdapters.vMailingProjectScheduleTableAdapter();
                //var users = new DataSet1.vMailingProjectScheduleDataTable();
                //ta.Fill(users);
                db = new EEEntities();
                var projects = db.Projects.AsNoTracking().Where(t => t.gcode == vGcode && t.status == "진행" && (t.isdel == null || t.isdel == false)).OrderBy(t => t.sdate).ToList();
                // db.vMailingProjectSchedule.ToList();// .vJobReportForUser.Where(t => t.gcode == Pub.vGcode).GroupBy(t => t.id);

                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 = db.EETGW_ProjectsSchedule.AsNoTracking().Where(t => t.gcode == vGcode && t.project == 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 (MailJD != null)
                {
                    var mail_subject = MailJD.subject;//.Replace("{담당자}", userinfo.name).Replace("{사번}", userinfo.id);
                    var mail_to = MailJD.tolist;//.Replace("{담당자}", userinfo.email);
                    var mail_cc = string.Empty; //
                    if (MailJD.cc != null) mail_cc = MailJD.cc;//.Replace("{담당자}", userinfo.email);
                    var mail_bcc = string.Empty;
                    if (MailJD.bcc != null) mail_bcc = MailJD.bcc;//.Replace("{담당자}", userinfo.email);
                    var mail_body = MailJD.body;//.Replace("{담당자}", userinfo.name);
                                                //mail_body = mail_body.Replace("{사번}", userinfo.id);

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

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

                    mail_to = Pub.MailSort(mail_to, MailJD.exceptmail);
                    if (string.IsNullOrEmpty(mail_to) == false)
                    {
                        db = new EEEntities();
                        db.MailData.Add(new MailData
                        {
                            gcode = vGcode,
                            cate = "SN",
                            subject = mail_subject,
                            fromlist = "EETGW@amkor.co.kr",
                            tolist = Pub.MailSort(mail_to, MailJD.exceptmail),
                            bcc = mail_bcc,
                            cc = Pub.MailSort(mail_cc, MailJD.exceptmailcc),
                            pdate = DateTime.Now.ToShortDateString(),
                            body = mail_content,
                            wuid = "DEV",
                            wdate = DateTime.Now,
                        });
                        db.SaveChanges();
                        addmsg($"[{vGcode}] 메일 전송 완료(no스케쥴week)");
                        System.Threading.Thread.Sleep(10000);
                    }
                    else
                    {
                        addmsg($"[{vGcode}] 받는사람이 소거되어 메일을 생성하지 않습니다");
                    }
                }

                System.Threading.Thread.Sleep(500);

            }


            
        }

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

        }
    }
}
