using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using util = FCOMMON.Util;
using NetOffice;
using Outlook = NetOffice.OutlookApi;
using NetOffice.OutlookApi.Enums;

namespace FPJ0000
{
    public partial class fMailSend : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        List<int> idxlist = new List<int>();

        public fMailSend(List<int> idxlist_)
        {
            InitializeComponent();
            this.idxlist = idxlist_;

            //이 목록에 해당하는 프로젝트 정보를 저장한다.
            dsPRJTableAdapters.ProjectsTableAdapter taproj = new dsPRJTableAdapters.ProjectsTableAdapter();
            dsPRJTableAdapters.ProjectsMailListTableAdapter tamail = new dsPRJTableAdapters.ProjectsMailListTableAdapter();
            dsMailTableAdapters.MailFormTableAdapter taform = new dsMailTableAdapters.MailFormTableAdapter();
            // dsPRJTableAdapters.ProjectsHistoryTableAdapter taHist = new dsPRJTableAdapters.ProjectsHistoryTableAdapter();

            var mailformDt = taform.GetData(FCOMMON.info.Login.gcode, "PM");
            dsMail.MailFormRow drForm = null;
            if (mailformDt != null && mailformDt.Rows.Count > 0) drForm = mailformDt.Rows[0] as dsMail.MailFormRow;



            foreach (var pidx in idxlist_)
            {
                if (pidx < 0) continue;
                var prjdt = taproj.GetbyIDX(pidx);

                string updateHistory = "<ul>";
                var dtHIst = taHist.GetbySendMail(pidx);
                int histCnt = 0;
                if (dtHIst != null)
                {
                    foreach (dsPRJ.ProjectsHistoryRow drhist in dtHIst.Rows)
                    {
                        if (drhist.remark.Trim() == "") continue;
                        histCnt += 1;
                        updateHistory += "<li>["+drhist.pdate + "] " + drhist.remark + "</li>";
                    }
                }
                updateHistory += "</ul>";
                if(histCnt < 1)
                {
                    FCOMMON.Util.MsgE("프로젝트:" + pidx.ToString() + "의 변경사항이 존재하지 않습니다.");
                    continue;
                }

                var newdr = this.dsMail.MailData.NewMailDataRow();
                newdr.project = pidx;
                newdr.wuid = FCOMMON.info.Login.no;
                newdr.wdate = DateTime.Now;
                newdr.cate = "PM";
                newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");

                dsPRJ.ProjectsRow prjdr = null;

                //양식의 제목과 본문을 업데이트
                if (drForm != null)
                {
                    newdr.subject = drForm.subject;
                    newdr.body = drForm.body;
                }

                if (prjdt != null && prjdt.Rows.Count > 0)
                {
                    prjdr = prjdt.Rows[0] as dsPRJ.ProjectsRow;
                    //newdr.prj_ddate = prjdr.ddate;
                    //newdr.prj_name = prjdr.name;
                    //newdr.prj_status = prjdr.status;

                    newdr.subject = string.Format(newdr.subject, prjdr.name, prjdr.status, prjdr.ddate, updateHistory);
                    newdr.body = string.Format(newdr.body, prjdr.name, prjdr.status, prjdr.ddate, updateHistory);
                }

                //메일전송대상 정보를 불러온다.
                var maillist = tamail.GetData(pidx);
                if (maillist != null && maillist.Rows.Count > 0)
                {
                    //양식의 tolist/cc/bcc 추가
                    if (drForm != null)
                    {
                        var buffer = drForm.tolist.Split(';');
                        foreach (var address in buffer)
                        {
                            if (address.Trim() == "") continue;
                            if (newdr.tolist.Contains(address) == false)
                            {
                                if (newdr.tolist != "") newdr.tolist += ";";
                                newdr.tolist += address;
                            }
                        }

                        buffer = drForm.cc.Split(';');
                        foreach (var address in buffer)
                        {
                            if (address.Trim() == "") continue;
                            if (newdr.cc.Contains(address) == false)
                            {
                                if (newdr.cc != "") newdr.cc += ";";
                                newdr.cc += address;
                            }
                        }

                        buffer = drForm.bcc.Split(';');
                        foreach (var address in buffer)
                        {
                            if (address.Trim() == "") continue;
                            if (newdr.bcc.Contains(address) == false)
                            {
                                if (newdr.bcc != "") newdr.bcc += ";";
                                newdr.bcc += address;
                            }
                        }
                    }



                    foreach (dsPRJ.ProjectsMailListRow drmail in maillist.Rows)
                    {
                        if (drmail.div == "TO")
                        {
                            if (newdr.tolist.Contains(drmail.address) == false)
                            {
                                if (newdr.tolist != "") newdr.tolist += ";";
                                newdr.tolist += drmail.address;
                            }
                        }
                        else if (drmail.div == "CC")
                        {
                            if (newdr.cc.Contains(drmail.address) == false)
                            {
                                if (newdr.cc != "") newdr.cc += ";";
                                newdr.cc += drmail.address;
                            }
                        }
                        else if (drmail.div == "BCC")
                        {
                            if (newdr.bcc.Contains(drmail.address) == false)
                            {
                                if (newdr.bcc != "") newdr.bcc += ";";
                                newdr.bcc += drmail.address;
                            }
                        }
                    }

                }


                //메일전송 폼을 불러온다.
                this.dsMail.MailData.AddMailDataRow(newdr);
            }
        }

        private void fPartList_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.FormClosed += fPartList_FormClosed;
            this.KeyPreview = true;
            this.KeyDown += fPartList_KeyDown;


            //RefreshData();
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
        }


        void fPartList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape) this.Close();
        }

        void fPartList_FormClosed(object sender, FormClosedEventArgs e)
        {

        }



        void RefreshData()
        {
            //if(dsPRJ.HasChanges())
            //{
            //    var dlg = FCOMMON.Util.MsgQ("변경 사항이 있습니다. 갱신하면 변경 내용이 손실 됩니다.\n지금 갱신 하겠습니까?");
            //    if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            //}

            try
            {
                var sd = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd");
                var ed = DateTime.Now.ToString("yyyy-MM-dd");
                this.ta.Fill(this.dsMail.MailData,FCOMMON.info.Login.gcode,sd,ed);

            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }

        }



        private void exportListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fpSpread1.SaveExcel(sd.FileName,
                    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
            }

            //dv1.ExportData("partlist.csv");
        }


        private void autoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.fpSpread1.ActiveSheet.DataAutoSizeColumns = true;

            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
                this.fpSpread1.ActiveSheet.SetRowHeight(i, 25);
            //dv1.AutoResizeColumns();
        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (FarPoint.Win.Spread.Column col in this.fpSpread1.ActiveSheet.Columns)
            {
                col.Width = 100;
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FPUtil.ColsizeSave(this.fpSpread1, fn_fpcolsize);
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
        }

        private void fpSpread1_EditModeOff(object sender, EventArgs e)
        {
            int Colidx = this.fpSpread1.ActiveSheet.ActiveColumnIndex;
            int Rowidx = this.fpSpread1.ActiveSheet.ActiveRowIndex;

            var taItem = new FCM0000.dsMSSQLTableAdapters.ItemsTableAdapter();
        }

        private void btRefresh_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();

            //아웃룩에서 데이터를 표시한다.
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMail.MailDataRow;

            //이 데이터로 발송된 메일이 있는지 체크한다.
            dsMailTableAdapters.MailDataTableAdapter taMailData = new dsMailTableAdapters.MailDataTableAdapter();
            var dtPreData = taMailData.GetbyProject(dr.project);
            if (dtPreData != null && dtPreData.Rows.Count > 0)
            {
                var predataOne = dtPreData.Rows[0] as dsMail.MailDataRow;
                var dlgexist = FCOMMON.Util.MsgQ("해당 프로젝트는 " + predataOne.pdate + "에 메일이 발송된 기록이 있습니다.\n\n" +
                  "Prject:" + predataOne.subject + "\n\n" +
                  "To:" + predataOne.tolist + "\n" +
                    "CC:" + predataOne.cc + "\n\n" +
                    "그래도 메일을 보내시겠습니까?");
                if (dlgexist != System.Windows.Forms.DialogResult.Yes) return;
            }

            var dlg = FCOMMON.Util.MsgQ("프로젝트의 알림 메일을 전송 하시겠습니까?\n\n" +
                dr.subject + "\n\n" +
                "To:" + dr.tolist + "\n" +
                "CC:" + dr.cc + "\n" +
                "BCC:" + dr.bcc);
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            Outlook.Application outlookApplication = new Outlook.Application();

            var newMail = outlookApplication.CreateItem(OlItemType.olMailItem) as Outlook.MailItem;
            newMail.Display();
            newMail.Subject = dr.subject; // this.tbSubject.Text.Trim(); // dr.title;
            newMail.To = dr.tolist; // to;
            newMail.CC = dr.cc;// tbCC.Text.Trim();
            newMail.BCC = dr.bcc; // tbBCC.Text.Trim();
            // newMail.BodyFormat = OlBodyFormat.olFormatHTML;
            newMail.HTMLBody = dr.body + newMail.HTMLBody; //
            newMail.Send();

            FCOMMON.Util.MsgI("메일이 전송되었습니다.\n\n전송된 메일은 아웃룩의 보낸편지함 혹은 그룹웨어의 보낸편지함에서 확인할 수 있습니다.");

            try
            {
                this.taHist.UpdateMailSend(dr.project);
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("MailSend Update Error\n\n" + ex.Message);
            }
            try
            {
                this.ta.Update(dr);
                dr.AcceptChanges();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("전송 결과 저장 오류\n\n" + ex.Message);
            }
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            string msg = bs.Count.ToString() + "건의 메일을 일괄 전송 하시겠습니까?\n\n" +
                "전송은 아웃룩을 통해서 진행되므로 아웃룩이 보낼수 있는 상태인지 확인하시기 바랍니다";
            var dlg = FCOMMON.Util.MsgQ(msg);
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            //프로그레스바
            this.prb1.Maximum = this.bs.Count;
            this.prb1.Minimum = 0;
            this.prb1.Value = 0;

            Outlook.Application outlookApplication = new Outlook.Application();
            int cntSend = 0;
            foreach (dsMail.MailDataRow dr in this.dsMail.MailData.Rows)
            {
                if (prb1.Value < prb1.Maximum) prb1.Value += 1;
                if (dr.tolist.Trim() == "")
                {
                    FCOMMON.Util.MsgE("받을 주소가 없어서 진행하지 않습니다\n" + dr.subject);
                    continue;
                }


                //이 데이터로 발송된 메일이 있는지 체크한다.
                dsMailTableAdapters.MailDataTableAdapter taMailData = new dsMailTableAdapters.MailDataTableAdapter();
                var dtPreData = taMailData.GetbyProject(dr.project);
                if (dtPreData != null && dtPreData.Rows.Count > 0)
                {
                    var predataOne = dtPreData.Rows[0] as dsMail.MailDataRow;
                    var dlgexist = FCOMMON.Util.MsgQ("해당 프로젝트는 " + predataOne.pdate + "에 메일이 발송된 기록이 있습니다.\n\n" +
                        "Prject:" + predataOne.subject + "\n\n" +
                        "To:" + predataOne.tolist + "\n" +
                        "CC:" + predataOne.cc + "\n\n" +
                        "그래도 메일을 보내시겠습니까?");
                    if (dlgexist != System.Windows.Forms.DialogResult.Yes) continue;
                }


                var newMail = outlookApplication.CreateItem(OlItemType.olMailItem) as Outlook.MailItem;
                newMail.Display();
                newMail.Subject = dr.subject;
                newMail.To = dr.tolist;// to;
                newMail.CC = dr.cc;// tbCC.Text.Trim();
                newMail.BCC = dr.bcc;// tbBCC.Text.Trim();
                // newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                newMail.HTMLBody = dr.body + newMail.HTMLBody; //
                newMail.Send();
                cntSend += 1;

                try
                {
                    this.taHist.UpdateMailSend(dr.project);
                }
                catch (Exception ex)
                {
                    FCOMMON.Util.MsgE("MailSend Update Error\n\n" + ex.Message);
                }
                try
                {
                    dr.EndEdit();
                    ta.Update(dr);
                    dr.AcceptChanges();
                }
                catch (Exception ex)
                {
                    FCOMMON.Util.MsgE("메일 전송 오류\n\n" + ex.Message);
                }

            }
            FCOMMON.Util.MsgI(cntSend.ToString() + " 건의 메일이 전송되었습니다.\n\n전송된 메일은 아웃룩의 보낸편지함 혹은 그룹웨어의 보낸편지함에서 확인할 수 있습니다.");

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            //아웃룩에서 데이터를 표시한다.
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMail.MailDataRow;


            try
            {
                Outlook.Application outlookApplication = new Outlook.Application();

                var newMail = outlookApplication.CreateItem(OlItemType.olMailItem) as Outlook.MailItem;
                newMail.Display();
                newMail.Subject = dr.subject; // this.tbSubject.Text.Trim(); // dr.title;
                newMail.To = dr.tolist; // to;
                newMail.CC = dr.cc;// tbCC.Text.Trim();
                newMail.BCC = dr.bcc; // tbBCC.Text.Trim();
                // newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                newMail.HTMLBody = dr.body + newMail.HTMLBody; //
            }
            catch (Exception ex)
            {
                util.MsgE("전송실패\n\n" + ex.Message + "\n\n" +
                    "아웃룩의 설정이 정상인지 확인하세요");
            }
        }

        private void bn_RefreshItems(object sender, EventArgs e)
        {

        }
    }
}
