using arUtil;
using FarPoint.Win.Spread;
using FCOMMON;
using GrapeCity.CalcEngine;
using Microsoft.Reporting.Map.WebForms.BingMaps;

using NetOffice;
using Outlook = NetOffice.OutlookApi;
using NetOffice.OutlookApi.Enums;
using NetOffice.OfficeApi;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using libxl;
using FarPoint.Excel;

namespace FEQ0000
{
    public partial class fUserExportColumn : fBase
    {
        string presavefn = "";
        //this.Name, cols,this.dsPurchase.Purchase,this.bs.Filter
        string Source = "";
        dsPurchase.PurchaseDataTable dt;
        public fUserExportColumn(string source, Dictionary<string, string> cols, DataTable dt_, string filter)
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
            presavefn = Util.MakeFilePath("exportsetting", source);
            var prelists = "";
            if (System.IO.File.Exists(presavefn)) prelists = System.IO.File.ReadAllText(presavefn, System.Text.Encoding.Default);
            //     Dictionary<int, string> preitems = new Dictionary<int, string>();
            this.listView2.Items.Clear();
            this.listView1.FullRowSelect = true;
            this.listView1.CheckBoxes = true;

            Source = source;
            dt = new dsPurchase.PurchaseDataTable();
            this.dt.Merge(dt_);
            this.bs.DataSource = dt;
            this.bs.Filter = filter;

            if (prelists.Length > 0)
            {
                var itemsbu = prelists.Split('\n');
                foreach (var item in prelists.Split('\n'))
                {
                    if (item.isEmpty()) continue;
                    var items = item.Split('|');
                    var chk = items[0] == "1";
                    var field = items[1];
                    var title = items[2].Replace("\r", "");

                    var lv = listView2.Items.Add(title);
                    lv.Tag = field;
                    lv.Checked = chk;

                }
            }
            else
            {

                foreach (var item in cols)
                {
                    var title = item.Value.Replace("\n", "").Replace("\r", "");
                    var lv = listView2.Items.Add(title);
                    lv.Tag = item.Key;
                }
            }


            listView2.FullRowSelect = true;
            listView2.HideSelection = false;
            listView2.GridLines = true;
            listView2.MultiSelect = false;

            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 선택된 아이템이 있고, 그것이 첫 번째 아이템이 아닌 경우에만 실행합니다.
            if (listView2.FocusedItem.Index > 0)
            {
                int currentIndex = listView2.FocusedItem.Index;
                ListViewItem currentItem = listView2.FocusedItem;

                // 이전 아이템과 위치를 바꿉니다.
                listView2.Items.RemoveAt(currentIndex);
                listView2.Items.Insert(currentIndex - 1, currentItem);

                // 위로 올리는 동작을 시각적으로 보여주기 위해 선택된 아이템을 변경합니다.
                currentItem.Selected = true;
                currentItem.Focused = true;
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (listView2.FocusedItem.Index < listView2.Items.Count - 1)
            {
                int currentIndex = listView2.FocusedItem.Index;
                ListViewItem currentItem = listView2.FocusedItem;

                // 다음 아이템과 위치를 바꿉니다.
                listView2.Items.RemoveAt(currentIndex);
                listView2.Items.Insert(currentIndex + 1, currentItem);

                // 아래로 내리는 동작을 시각적으로 보여주기 위해 선택된 아이템을 변경합니다.
                currentItem.Selected = true;
                currentItem.Focused = true;
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

        }

        private void fUserExportColumn_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            button3.PerformClick();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //rprewviwe
            var items = this.listView2.CheckedItems;
            SortedDictionary<int, string> cols = new SortedDictionary<int, string>();

            var sb = new System.Text.StringBuilder();
            foreach (ListViewItem lv in items)
            {
                var no = lv.Index;
                var field = lv.SubItems[0].Text + "|" + lv.Tag.ToString();
                cols.Add(no, field);

            }
            foreach (ListViewItem lv in listView2.Items)
            {

                sb.AppendLine($"{(lv.Checked ? "1" : "0")}|{lv.Tag}|{lv.SubItems[0].Text}");
            }
            var fi = new System.IO.FileInfo(presavefn);
            if (fi.Directory.Exists == false) fi.Directory.Create();
            System.IO.File.WriteAllText(fi.FullName, sb.ToString(), System.Text.Encoding.Default);


            listView1.Clear();
            listView1.Columns.Add("No");
            foreach (var item in cols)
            {
                var titles = item.Value.Split('|');
                listView1.Columns.Add(titles[0],titles[0]);
            }
            for (int i = 0; i < bs.Count; i++)
            {
                var drv = bs[i] as DataRowView;

                var no = this.listView1.Items.Count + 1;
                var lv = this.listView1.Items.Add(no.ToString());
                lv.Checked = true;
                lv.Tag = string.Empty;
                var colno = -1;
                foreach (var item in cols)
                {
                    colno += 1;
                    var titles = item.Value.Split('|');
                    var field = titles[1];
                    var title = titles[0];
                    var val = drv[field];
                    var dr = drv.Row;
                    var coldata = dr.Table.Columns[field];
                    if (coldata.DataType == typeof(int))
                    {
                        if (val == null) lv.SubItems.Add("--");
                        else lv.SubItems.Add(((int)val).ToString("N0"));
                        lv.Tag += "," + (colno+1).ToString();
                    }
                    else if (coldata.DataType == typeof(decimal))
                    {
                        if (val == null) lv.SubItems.Add("--");
                        else lv.SubItems.Add(((decimal)val).ToString("N0"));
                        lv.Tag += "," + (colno + 1).ToString();
                    }
                    else
                    {
                        if (val == null) lv.SubItems.Add("");
                        else lv.SubItems.Add(val.ToString());
                    }

                }

            }



        }
        List<string> ChangeMailAddress(List<string> userid)
        {
            var db = new DataClasses1DataContext();

            List<string> retval = new List<string>();
            foreach (var id in userid)
            {
                UInt32 userno;
                if (UInt32.TryParse(id, out userno) == true)
                {
                    var user = db.Users.Where(t => t.id == id).FirstOrDefault();
                    if (user != null)
                    {
                        var data = string.Format("{0}<{1}>", user.name, user.email);
                        if (retval.Contains(data) == false)
                            retval.Add(data);
                    }
                }
                else
                {
                    if (retval.Contains(id) == false)
                        retval.Add(id);
                }
            }
            return retval;
        }

        void save(string fn = "")
        {
            if (fn.isEmpty()) fn = (Util.MakeFilePath("temp", DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx"));
            var fi = new System.IO.FileInfo(fn);
            if (fi.Directory.Exists == false) fi.Directory.Create();


            libxl.Book book;// = new libxl.BinBook();
            book = new libxl.XmlBook();
            book.setKey(FCOMMON.info.libxlCompany, FCOMMON.info.libxlKey);
            var sheet = book.addSheet("data");
            //var colno = 0;
            var rowno = 0;
            for (int i = 0; i < this.listView1.Columns.Count; i++)
            {
                var col = this.listView1.Columns[i];
                sheet.writeStr(rowno, i, col.Text);
            }

            foreach (ListViewItem lv in this.listView1.CheckedItems)
            {
                rowno += 1;
                var tagstr = lv.Tag?.ToString() ?? string.Empty;
                var numcols = tagstr.Split(',');
                for (int i = 0; i < this.listView1.Columns.Count; i++)
                {
                    var data = lv.SubItems[i].Text;

                    if (i == 0) data = rowno.ToString();

                    if (numcols.Contains(i.ToString()))
                        sheet.writeNum(rowno, i, double.Parse(data));
                    else
                        sheet.writeStr(rowno, i, data);
                }
            }
            //sheet.siz
            book.save(fi.FullName);
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            //데이터수집
            if(listView1.CheckedItems.Count < 1)
            {
                Util.MsgE("선택된 대상이 없습니다");
                return;
            }

            //현재표시데이터중에 수신자목록을 가져온다
            var drows = (dsPurchase.PurchaseRow[])(this.dt.Select(this.bs.Filter, this.bs.Sort));
            var grp_req = drows.Where(t => t.request.isEmpty() == false).GroupBy(t => t.request).Select(t => t.FirstOrDefault().request).ToList();
            var grp_rec = drows.Where(t => t.receive.isEmpty() == false).GroupBy(t => t.receive).Select(t => t.FirstOrDefault().receive).ToList();

            List<string> tolist = new List<string>();   //최종받는사람
            List<string> cclist = new List<string>();
            List<string> bcclist = new List<string>();




            var fn = new System.IO.FileInfo(Util.MakeFilePath("mailform", this.Source + ".xml"));
            if (fn.Directory.Exists == false) fn.Directory.Create();



            var xml = new XMLHelper(fn.FullName);
            string form_subject, form_body, form_to, form_cc, form_bcc;

            form_subject = form_body = form_to = form_cc = form_bcc = "";

            form_subject = xml.get_Data("subject");
            form_body = xml.get_Data("body");
            form_to = xml.get_Data("to");
            form_cc = xml.get_Data("cc");
            if (form_cc.isEmpty()) form_cc = "{요청}";
            form_bcc = xml.get_Data("bcc");

            var f = new Purchase.fMailForm(form_subject, form_body, form_to, form_cc, form_bcc);
            if (f.ShowDialog() != DialogResult.OK) return;



            //받는사람
            if (form_to.Contains("{요청}") == true) tolist.AddRange(grp_req);
            if (form_to.Contains("{수령}") == true) tolist.AddRange(grp_rec);
            form_to = form_to.Replace("{요청}", "");
            form_to = form_to.Replace("{수령}", "");
            tolist.AddRange(form_to.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            tolist = ChangeMailAddress(tolist);



            //참조
            if (form_cc.Contains("{요청}") == true) cclist.AddRange(grp_req);
            if (form_cc.Contains("{수령}") == true) cclist.AddRange(grp_rec);
            form_cc = form_cc.Replace("{요청}", "");
            form_cc = form_cc.Replace("{수령}", "");
            cclist.AddRange(form_cc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            cclist = ChangeMailAddress(cclist);

            //숨은참조
            if (form_bcc.Contains("{요청}") == true) bcclist.AddRange(grp_req);
            if (form_bcc.Contains("{수령}") == true) bcclist.AddRange(grp_rec);
            form_bcc = form_bcc.Replace("{요청}", "");
            form_bcc = form_bcc.Replace("{수령}", "");
            bcclist.AddRange(form_bcc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            bcclist = ChangeMailAddress(bcclist);



      
            form_subject = f.tbSubject.Text.Trim();
            form_body = f.htmlEditor1.Html;
            form_to = f.tbTo.Text.Trim();
            form_cc = f.tbCC.Text.Trim();
            form_bcc = f.tbBcc.Text.Trim();




            xml.set_Data("subject", form_subject);
            xml.set_Data("body", form_body);
            xml.set_Data("to", form_to);
            xml.set_Data("cc", form_cc);
            xml.set_Data("bcc", form_bcc);
            xml.Save();


            //받는사람
            if (form_to.Contains("{요청}") == true) tolist.AddRange(grp_req);
            if (form_to.Contains("{수령}") == true) tolist.AddRange(grp_rec);
            form_to = form_to.Replace("{요청}", "");
            form_to = form_to.Replace("{수령}", "");
            tolist.AddRange(form_to.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            tolist = ChangeMailAddress(tolist);

            //참조
            if (form_cc.Contains("{요청}") == true) cclist.AddRange(grp_req);
            if (form_cc.Contains("{수령}") == true) cclist.AddRange(grp_rec);
            form_cc = form_cc.Replace("{요청}", "");
            form_cc = form_cc.Replace("{수령}", "");
            cclist.AddRange(form_cc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            cclist = ChangeMailAddress(cclist);

            //숨은참조
            if (form_bcc.Contains("{요청}") == true) bcclist.AddRange(grp_req);
            if (form_bcc.Contains("{수령}") == true) bcclist.AddRange(grp_rec);
            form_bcc = form_bcc.Replace("{요청}", "");
            form_bcc = form_bcc.Replace("{수령}", "");
            bcclist.AddRange(form_bcc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            bcclist = ChangeMailAddress(bcclist);

            //form_subject = form_subject.Replace("{DATE}", datestr);

            try
            {
                Outlook.Application outlookApplication = new Outlook.Application();
                var newMail = outlookApplication.CreateItem(OlItemType.olMailItem) as Outlook.MailItem;
                newMail.Display();
                newMail.Subject = form_subject; // this.tbSubject.Text.Trim(); // dr.title;
                newMail.To = string.Join(";", tolist.ToArray());
                newMail.CC = string.Join(";", cclist.ToArray());
                newMail.BCC = string.Join(";", bcclist.ToArray());
                if (f.chkAttach.Checked)
                {
                    var fi = new System.IO.FileInfo(FCOMMON.Util.CurrentPath + "\\Export\\Purchase_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls");
                    if (fi.Directory.Exists == false) fi.Directory.Create();

                    ///save file
                    save(fi.FullName);
                    newMail.Attachments.Add(fi.FullName);
                }
                if (f.chkList.Checked)
                {
                    //목록을 본문에 추가한다
                    System.Text.StringBuilder sb = new StringBuilder();
                    sb.AppendLine("<table border='1' cellspacing='0' cellpadding='1'>");
                    sb.AppendLine("<thead>");

                    for (int i = 0; i < this.listView1.Columns.Count; i++)
                    {
                        var col = this.listView1.Columns[i];
                        
                        sb.AppendLine($"<td style='text-align:center;background-color: aqua;'>{col.Text}</td>");
                    }

                    sb.AppendLine("</thead>");
                    sb.AppendLine("<tbody>");


                    var row = 1;
                    foreach (ListViewItem lv in this.listView1.CheckedItems)
                    {
                        sb.AppendLine("<tr>");
                        for (int i = 0; i < this.listView1.Columns.Count; i++)
                        {
                        
                            var data = lv.SubItems[i].Text;
                            var txt = i == 0 ? (row).ToString() : data;
                            sb.AppendLine($"<td>{txt}</td>");
                        }
                        sb.AppendLine("</tr>");
                        row += 1;
                    }


                    sb.AppendLine("</tbody>");
                    sb.AppendLine("</table>");
                    form_body += sb.ToString();
                }

                //newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                //form_body = form_body.Replace("{DATE}", datestr);
                newMail.HTMLBody = form_body + newMail.HTMLBody; //
            }
            catch (System.Exception ex)
            {
                Util.MsgE("전송실패\n\n" + ex.Message + "\n\n" +
                    "아웃룩의 설정이 정상인지 확인하세요");
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (listView1.CheckedItems.Count < 1)
            {
                Util.MsgE("선택된 대상이 없습니다");
                return;
            }
            
            var sd = new SaveFileDialog();
            sd.Filter = "xlsx|*.xlsx";
            if (sd.ShowDialog() != DialogResult.OK) return;
            save(sd.FileName);
            Util.RunExplorer(sd.FileName);
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lv in this.listView1.Items)
                lv.Checked = true;  
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lv in this.listView1.Items)
                lv.Checked = !lv.Checked;
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lv in this.listView1.Items)
                lv.Checked = false;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var lv = this.listView2.FocusedItem;
            if (lv == null)
            {
                Util.MsgE("필터를 적용할 컬럼을 좌측에서 선택하세요");
                return;
            }
            if(lv.Checked ==false)
            {
                Util.MsgE("선택된 열이 아닙니다. 필터는 선택된 열만 가능합니다");
                return;
            }
            var f = new fColumnFilter(lv.SubItems[0].Text);
            if (f.ShowDialog() != DialogResult.OK) return;

            var 조건 = f.comboBox1.Text;
            var 값 = f.textBox1.Text;
            var 체크 = f.checkBox1.Checked;

            var col = listView1.Columns[lv.SubItems[0].Text];
            foreach(ListViewItem item in this.listView1.Items)
            {
                var curvalue = item.SubItems[col.Index].Text;
                if(curvalue.Equals(값))
                {
                    item.Checked = 체크;
                    item.ForeColor = 체크 ? System.Drawing.Color.Blue : System.Drawing.Color.DimGray;
                }

            }
        }
    }
}
