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

        public fScheduleDayWeek()
        {
            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 - LastUpdateTime;
                    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
                    {
                        LastUpdateTime = DateTime.Now;
                        try
                        {
                            RunData();
                        }
                        catch (Exception ex)
                        {
                            addmsg(ex.Message);
                            task.Wait(5000);
                        }
                    }
                    Task.Delay(Delaytime).Wait();
                }

            });
            timer1.Start();
        }

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


            var db = new EEEntities();

            //메일양식이 지정되어있는지 체크
            var MailJD = db.MailForm.Where(t => t.gcode == Pub.vGcode & t.cate == "SP").FirstOrDefault();

            if (MailJD == null)
            {
                //토,일요일에는 동작하지 않는다
                addmsg("메일 양식(SP)이 입력되지 않았습니다");
                return;
            }

            //기준일자는 오늘부터 -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();

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

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

            addmsg($"{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 = 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 = Pub.vGcode,
                        cate = "SP",
                        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 = "395552",
                        wdate = DateTime.Now,
                    });
                    db.SaveChanges();
                    addmsg($"메일 전송 완료(스케쥴day)");
                    System.Threading.Thread.Sleep(10000);
                }
                else
                {
                    addmsg("받는사람이 소거되어 메일을 생성하지 않습니다");
                }
            }
        }

        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.toolStripButton1.Text = "완료";
                else if (task.IsCanceled) this.toolStripButton1.Text = "취소";
                else if (taskwait) this.toolStripButton1.Text = "대기상태";
                else this.toolStripButton1.Text = "가동중";
                this.toolStripButton1.Enabled = true;
            }
            else
            {
                this.toolStripButton1.Text = "사용불가";
                this.toolStripButton1.Enabled = false;
            }

        }
    }
}
