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;

using NetOffice;
using Outlook = NetOffice.OutlookApi;
using NetOffice.OutlookApi.Enums;
using System.Security.Cryptography.X509Certificates;
using FCOMMON;

namespace FEQ0000
{
    public partial class fItemin : fBase
    {
        public fItemin()
        {
            InitializeComponent();
            dv1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            tbSearch.Text = string.Empty;
            lbSID.Text = string.Empty;
            lbCOST.Text = string.Empty;
            lbPO.Text = string.Empty;
            tbSearch.Focus();
            //tbFind.Text = string.Empty;
            //findText();
            tbSearch.Focus();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void refreshData()
        {
            try
            {
                var search_mananger = tbman.Text.Trim();
                var search_admin = "";// tbadm.Text.Trim(); 
                if (search_mananger.isEmpty() ) search_mananger = "%";
                if (search_admin.isEmpty() ) search_admin = "%";

                var dt = DateTime.Now.AddYears(-2);
                this.ta.Fill(this.dsPurchase.Ipkolist,
                    dt.ToString("yyyy-MM-dd"),
                    FCOMMON.info.Login.gcode,
                    search_mananger, search_admin);

                dv1.AutoResizeColumn(0);
                dv1.AutoResizeColumn(1);
                dv1.AutoResizeColumn(2);
                dv1.AutoResizeColumn(3);
                dv1.AutoResizeColumn(4);
                dv1.AutoResizeColumn(7);
                dv1.AutoResizeColumn(8);
                dv1.AutoResizeColumn(9);
                dv1.AutoResizeColumn(10);
                dv1.AutoResizeColumn(5);


            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            UpdateSum();
        }

        void UpdateSum()
        {
            decimal sum = 0;
            var drs = this.dsPurchase.Ipkolist.Select(this.bs.Filter);
            foreach(dsPurchase.IpkolistRow dr in drs)
            {
                if (dr.IspumamtNull() == false) sum += dr.pumamt;
            }
            this.lbSum1.Text = $"{sum:N0}";
        }
        void UpdateSum2()
        {
            decimal sum = 0;
            var drs = this.dsPurchase1.Ipkolist.Select(this.bs2.Filter);
            foreach (dsPurchase.IpkolistRow dr in drs)
            {
                if (dr.IspumamtNull() == false) sum += dr.pumamt;
            }
            this.lbSum2.Text = $"{sum:N0}";
        }

        private void btFind_Click(object sender, EventArgs e)
        {
            findText();
        }
        void findText()
        {
            var search = tbFind.Text.Trim();
            if (search.isEmpty())
            {
                bs.Filter = string.Empty;
                tbFind.BackColor = SystemColors.Control;
            }
            else
            {
                try
                {
                    var list = new string[] { "sid","request", "pumname", "bigo","place", "purchase_manager" };
                    var filter = string.Join(" like '%{0}%' or ", list);
                    filter += "  like '%{0}%'";
                    filter = string.Format(filter, search);
                    bs.Filter = filter;
                    tbFind.BackColor = Color.Lime;
                }
                catch 
                {
                    tbFind.BackColor = Color.Tomato;
                }

            }

            dv1.AutoResizeColumn(0);
            dv1.AutoResizeColumn(1);
            dv1.AutoResizeColumn(2);
            dv1.AutoResizeColumn(3);
            dv1.AutoResizeColumn(4);
            dv1.AutoResizeColumn(7);
            dv1.AutoResizeColumn(8);
            dv1.AutoResizeColumn(9);
            dv1.AutoResizeColumn(10);
            dv1.AutoResizeColumn(5);

            tbFind.Focus();
            tbFind.SelectAll();
            UpdateSum();
        }
        void findText2()
        {
            var search = tbFind2.Text.Trim();
            if (search.isEmpty())
            {
                bs2.Filter = string.Empty;
                tbFind2.BackColor = SystemColors.Control;
            }
            else
            {
                try
                {
                    var list = new string[] { "sid", "pumname", "bigo" };
                    var filter = string.Join(" like '%{0}%' or ", list);
                    filter += "  like '%{0}%'";
                    filter = string.Format(filter, search);
                    bs2.Filter = filter;
                    tbFind2.BackColor = Color.Lime;
                }
                catch
                {
                    tbFind2.BackColor = Color.Tomato;
                }

            }

            dv2.AutoResizeColumns();

            tbFind2.Focus();
            tbFind2.SelectAll();

        }
        private void tbFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                findText();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            refreshData();
        }

        private void fItemin_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            using (var tauser = new dsPurchaseTableAdapters.Purchase_ManagerlistTableAdapter())
            {
                var lst_man = tauser.GetByManager(FCOMMON.info.Login.gcode);
                var lat_adm = tauser.GetByAdmin(FCOMMON.info.Login.gcode);

                tbman.Items.Clear();
                //tbadm.Items.Clear();

                
                foreach(dsPurchase.Purchase_ManagerlistRow dr in lst_man)
                {
                    tbman.Items.Add(dr.username);
                }
                //foreach (dsPurchase.Purchase_ManagerlistRow dr in lat_adm)
                //{
                //    tbadm.Items.Add(dr.username);
                //}
            }
      
                
            tbindate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            refreshData();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SearchText();


        }
        void SearchText()
        {
            lbSID.Text = string.Empty;
            lbCOST.Text = string.Empty;
            lbPO.Text = string.Empty;

            //입력된데이터에서 값을 추출한다
            var buf = tbSearch.Text.Split('#');
            if (buf.Length > 5)
            {
                var sid = buf[2].Trim();
                if(decimal.TryParse(sid,out decimal sidnum))
                {
                    lbSID.Text = sidnum.ToString();
                }
                else
                {
                    lbSID.Text = sid;
                }
                
                var qty = buf[3].Trim();
                lbCOST.Text = buf[5].Trim();
                tbFind.Text = lbSID.Text;
                lbPO.Text = buf[0].Trim();
                findText();
            }
            else
            {
                lbCOST.Text = string.Empty;
                lbSID.Text = tbSearch.Text;
                tbFind.Text = lbSID.Text;
                findText();
            }
            tbSearch.Focus();
            tbSearch.SelectAll();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
           
        }
        void func_ipgo()
        {
            var drv = this.bs.Current as DataRowView;
            var dr = drv.Row as dsPurchase.IpkolistRow;

            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.purchase));
            if (curLevel < 5)   //일반사용자 입고 여부
            {
                if (dr.request != FCOMMON.info.Login.no)
                {
                    FCOMMON.Util.MsgE("타인의 자료는 입고 처리할 수 없습니다");
                    return;
                }

                if (dr.state != "PO")
                {
                    FCOMMON.Util.MsgE("PO 상태의 자료만 입고처리가 가능 합니다");
                    return;
                }

            }

            var po = this.lbPO.Text.Trim();
            if (po.StartsWith("--")) po = string.Empty;

            if (dr.source == "NR")
            {
                var f = new FEQ0000.Purchase.fPurchaseNR_Ipgo(dr.idx, po);
                if (f.ShowDialog() == DialogResult.OK)
                {
                    refreshData();
                    tbSearch.Focus();
                    tbSearch.SelectAll();
                }
            }
            else if (dr.source == "EB")
            {
                var f = new FEQ0000.Purchase.fPurchaseEB_Ipgo(dr.idx, po);
                if (f.ShowDialog() == DialogResult.OK)
                {
                    refreshData();
                    tbSearch.Focus();
                    tbSearch.SelectAll();
                }
            }
            else
            {
                var f = new FEQ0000.Purchase.fPurchaseCR_Ipgo(dr.idx, po);
                if (f.ShowDialog() == DialogResult.OK)
                {
                    refreshData();
                    tbSearch.Focus();
                    tbSearch.SelectAll();
                }
            }

        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            tbFind.Text = string.Empty;
            findText();
        }

        private void ipkolistDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void tbSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                SearchText();
        }

        private void ipkolistDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            if (e.ColumnIndex == 0)
            {
                func_ipgo(); ;
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedIndex == 1)
                tbindate.Text = DateTime.Now.ToString("yyyy-MM-dd");
        }

        private void btRefreshIn_Click(object sender, EventArgs e)
        {
            try
            {
                var search_mananger = tbman.Text.Trim();
                var search_admin = "";// tbadm.Text.Trim(); ;
                if (search_mananger.isEmpty() ) search_mananger = "%";
                if (search_admin.isEmpty() ) search_admin = "%";

                this.ta.FillByTodayIn(this.dsPurchase1.Ipkolist, tbindate.Text,
                    FCOMMON.info.Login.gcode,
                    search_mananger,
                    search_admin);

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

        private void toolStripButton13_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton15_Click(object sender, EventArgs e)
        {
            tbFind2.Text = string.Empty;
            btFind2.PerformClick();
        }

        private void tbFind2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) btFind2.PerformClick();
        }
        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;
        }
        string getmaxstr(string src, int len = 30)
        {
            if (src.Length > len) return src.Substring(0, len) + "...";
            else return src;
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {

            //입고품목메일발송
            var db = new DataClasses1DataContext();
            var dr = db.MailForm.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.cate == "PE").FirstOrDefault();

            //현재표시데이터중에 수신자목록을 가져온다
            //var grp_req = new List<string>();
            //var grp_rec = new List<string>();

            var drows = (dsPurchase.IpkolistRow[])(this.dsPurchase1.Ipkolist.Select(this.bs2.Filter, this.bs2.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();

            //var f = new Purchase.fMailForm("PE");
            //if (f.ShowDialog() != DialogResult.OK) return;



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

            if (dr.subject != null) form_subject = dr.subject;
            if (dr.body != null) form_body = dr.body;
            if (dr.tolist != null) form_to = dr.tolist;
            if (dr.cc != null) form_cc = dr.cc;
            if (dr.bcc != null) form_bcc = dr.bcc;


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

            //받는사람
            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);

            var datestr = tbindate.Text;
            //if (dtSD.Text == dtED.Text) datestr = dtSD.Text;
            //else datestr = dtSD.Text + "~" + dtED.Text;
            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());

                var datas = this.dsPurchase1.Ipkolist.OrderBy(t => t.source);

                //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();

                    var xls = new libxl.XmlBook();
                    xls.setKey(FCOMMON.info.libxlCompany, FCOMMON.info.libxlKey);


                    var row = 0;
                    var col = 0;

                    //제목줄 먼저 진행
                    var sheet = xls.addSheet("data");
                    foreach (DataGridViewColumn column in this.dv2.Columns)
                    {
                        if (column.Visible == false || column.Width < 10) continue;
                        sheet.writeStr(row, col++, column.HeaderText);
                    }
                    row += 1;

                    //데이터를 입력한다


                    foreach (dsPurchase.IpkolistRow drow in datas)
                    {
                        col = 0;
                        foreach (DataGridViewColumn column in this.dv2.Columns)
                        {
                            if (column.Visible == false || column.Width < 10) continue;
                            var o_data = drow[column.DataPropertyName];
                            string value = string.Empty;
                            if (o_data != null) value = o_data.ToString();
                            sheet.writeStr(row, col++, value);
                        }


                        row += 1;
                    }
                    xls.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>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>위치</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>신청</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>수령</td>");
                    //sb.AppendLine("<td style='text-align:center;background-color: aqua;'>PO</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>CR/CF</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>SID</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>품명</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>규격</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>수량</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>단가</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>금액</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>공급</td>");
                    sb.AppendLine("</thead>");
                    sb.AppendLine("<tbody>");

                    var htmltable = new System.Text.StringBuilder();
                    foreach (dsPurchase.IpkolistRow drow in datas)
                    {
                        htmltable.AppendLine("<tr>");
                        htmltable.AppendLine($"<td style='text-align:center'>{drow.source}</td>");
                        htmltable.AppendLine($"<td style='text-align:center'>{drow.request}</td>");
                        if (drow.receive.Equals(drow.request))
                            htmltable.AppendLine($"<td style='text-align:center'>=</td>");
                        else
                            htmltable.AppendLine($"<td style='text-align:center'>{drow.receive}</td>");
                        //htmltable.AppendLine($"<td>{drow.po}</td>");
                        htmltable.AppendLine($"<td>{drow.orderno}</td>");
                        htmltable.AppendLine($"<td>{drow.sid}</td>");
                        htmltable.AppendLine($"<td>{drow.pumname}</td>");
                        htmltable.AppendLine($"<td>{drow.pumscale}</td>");
                        htmltable.AppendLine($"<td style='text-align:center'>{drow.pumqty:N0}</td>");
                        htmltable.AppendLine($"<td style='text-align:right'>{drow.pumprice:N0}</td>");
                        htmltable.AppendLine($"<td style='text-align:right'>{drow.pumamt:N0}</td>");
                        htmltable.AppendLine($"<td>{drow.supply}</td>");
                        htmltable.AppendLine("</tr>");
                    }
                    sb.AppendLine(htmltable.ToString());
                    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 (Exception ex)
            {
                FCOMMON.Util.MsgE("전송실패\n\n" + ex.Message + "\n\n" +
                    "아웃룩의 설정이 정상인지 확인하세요");
            }
        }

        private void toolStripLabel6_Click(object sender, EventArgs e)
        {
            if (tbman.Text.isEmpty() == false)
                tbman.Text = string.Empty;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            func_ipgo();
        }

        private void 목록내보내기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "csv|*.csv";
            sd.FileName = "xiplist.csv";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                dv1.ExportData(sd.FileName, false);
                //fpSpread1.SaveExcel(sd.FileName,
                //    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                //    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                //    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                //    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
                var dlg = FCOMMON.Util.MsgQ("생성된 파일을 확인 할까요?\n\n" + sd.FileName);
                if (dlg == DialogResult.Yes) FCOMMON.Util.RunExplorer(sd.FileName);
            }
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "csv|*.csv";
            sd.FileName = "iplist.csv";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                dv2.ExportData(sd.FileName, false);
                //fpSpread1.SaveExcel(sd.FileName,
                //    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                //    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                //    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                //    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
                var dlg = FCOMMON.Util.MsgQ("생성된 파일을 확인 할까요?\n\n" + sd.FileName);
                if (dlg == DialogResult.Yes) FCOMMON.Util.RunExplorer(sd.FileName);
            }
        }
    }
}
