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 fScheduleDay : fChildBase
    {
        public fScheduleDay()
        {
            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.Saturday ||
                    DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
                    {
                        //토,일요일에는 동작하지 않는다
                        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 == "SJ").FirstOrDefault();
            if (MailJD == null)
            {
                //토,일요일에는 동작하지 않는다
                addmsg("메일 양식(SJ)이 입력되지 않았습니다");
                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 == "SJ" && 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("
");
            body.AppendLine("");
            body.AppendLine("| 진행(%)");
            body.AppendLine(" | Project");
            body.AppendLine(" | Champion");
            body.AppendLine(" | 등록일");
            body.AppendLine(" | 스케쥴");
            body.AppendLine(" | 
");
            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($"");                
                body.AppendLine($"| {prc}");
                body.AppendLine($" | [{dr.idx}] {dr.name}");
                body.AppendLine($" | {dr.userManager}");
                body.AppendLine($" | {dr.pdate}");
                body.AppendLine(" | ");
                body.AppendLine(" ");
                //여기에 스케쥴이 들어가야한다
                body.AppendLine($"");
                body.AppendLine("");
                body.AppendLine("");
                body.AppendLine("");
                body.AppendLine("| No | Title | Plan(ww) | Actual(ww) | 진행 | 비고");
                body.AppendLine(" |  ");
                body.AppendLine("");
                var ll = row.OrderBy(t => t.seq).ToList();
                foreach (var srow in ll)
                {
                    body.AppendLine($"| 시작 | 완료 | 시작 | 완료 | % | ");
                body.AppendLine(" |  ");
                    body.AppendLine($"");
                }
                body.AppendLine("| {srow.seq}");
                    body.AppendLine($" | {srow.title}");
                    body.AppendLine($" | {srow.sw}");
                    body.AppendLine($" | {srow.ew}");
                    body.AppendLine($" | {srow.swa}");
                    body.AppendLine($" | {srow.ewa}");
                    body.AppendLine($" | {srow.progress}");
                    body.AppendLine($" | {srow.memo}");
                    body.AppendLine($" |  | 
");
            }
            body.AppendLine("
");
            //일별경고(월요일제외)
            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 = "SJ",
                        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;
            }
        }
    }
}