using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FEQ0000.Purchase;
using FCOMMON;
using System.Web.Services.Protocols;
using System.Diagnostics;
using FarPoint.Win.Spread.CellType;
using FCM0000;
using FarPoint.Win.Spread;
using System.Resources;

namespace FEQ0000
{
    public partial class fPurchaseEB_ConfRequest : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        List<dsPurchase.EETGW_PurchaseEBRow> rows;
        public fPurchaseEB_ConfRequest(List<dsPurchase.EETGW_PurchaseEBRow> rows_)
        {
            InitializeComponent();
            this.rows = rows_;
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            Properties.Settings.Default["EEEntities"] = FCOMMON.info.CS;

            fn_fpcolsize = FCOMMON.Util.MakeFilePath(FCOMMON.Util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.FormClosing += FPurchase_FormClosing;
            this.FormClosed += __Closed;

            this.bs.DataSource = rows;
            this.dataGridView1.DataError += (s1, e1) => { };
            this.dataGridView1.EditMode = DataGridViewEditMode.EditOnKeystroke;
        }

        private void FPurchase_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (dsPurchase.HasChanges())
            {
                var dlg = FCOMMON.Util.MsgQ("변경된 자료가 있습니다. 화면을 닫을까요? 닫으면 변경된 자료는 손실 됩니다");
                if (dlg != DialogResult.Yes)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }

        void dtSD_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;
            var tb = sender as ToolStripTextBox;
            var input = tb.Text.Trim();
            if (input == "") tb.Text = DateTime.Now.ToString("yyyy-MM-dd");
            else
            {
                string dt = string.Empty;
                if (!FCOMMON.Util.MakeDateString(input, out dt))
                {
                    FCOMMON.Util.MsgE("입력값이 올바르지 않습니다.");
                    tb.SelectAll();
                    tb.Focus();
                    return;
                }
                else
                {
                    tb.Text = dt;
                }
            }

        }

        void __Closed(object sender, FormClosedEventArgs e)
        {

        }


        private void __Load(object sender, EventArgs e)
        {

            EnsureVisibleAndUsableSize();
            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.purchaseEB));
            IsAdmin = curLevel >= 5;
            if (curLevel >= 5)
            {
                btSave.Visible = true;

            }
            else
            {

                btSave.Visible = false;
            }
            btSave.Visible = true;
            refreshData();


        }

        bool IsAdmin = false;

        private void refreshData()
        {

            try
            {

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

            FormattingData();
        }
        void FormattingData()
        {

            dataGridView1.AutoResizeColumns();
        }


        void showSummary()
        {
            decimal sum = 0;

            sum = rows.Sum(t => t.pumamt);
            //foreach (dsPurchase.PurchaseRow dr in this.dsPurchase.Purchase.Rows)
            //if (!dr.IspumamtNull()) sum += dr.pumamt;
            lbSum.Text = sum.ToString("N0");
        }


        private bool getAdminInput
        {
            get
            {
                return FCOMMON.Util.getBit(
                FCOMMON.info.Login.gpermission,
                (int)FCOMMON.eGroupPermission.purchase_adv);
            }
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            //func_delete();
        }


        private int AddItemInfoGetIndex(dsPurchase.EETGW_PurchaseEBRow newdr)
        {
            //이 시드가 아이템목록에 없다면 추가 하고 idx를 조회한 후 설정해준다.
            if (newdr.sid == "신규") return -1;
            int retval = -1;
            var sid = newdr.sid;
            var iteminfo = FCOMMON.DBM.getItemInfo(sid);
            if (iteminfo.idx < 0)
            {
                FCOMMON.Models.ItemModel newitem = new FCOMMON.Models.ItemModel();
                newitem.sid = newdr.sid;
                newitem.name = newdr.pumname;
                newitem.price = newdr.pumprice.ToString();
                newitem.model = newdr.pumscale;
                newitem.unit = newdr.pumunit;
                newitem.scale = 1f;
                newitem.supply = newdr.supply;
                newitem.supplyidx = newdr.supplyidx;
                retval = FCOMMON.DBM.addItemInfo(newitem);
            }
            return retval;
        }



        private void btFind_Click(object sender, EventArgs e)
        {
            var search = tbFind.Text.Trim();
            search = search.Replace("*", "x");
            if (tbFind.Text != search) tbFind.Text = search;
            try
            {
                if (search.isEmpty())
                {
                    this.bs.Filter = "";
                    tbFind.BackColor = Color.White;
                }
                else
                {
                    search = search.Replace("'", "''");
                    string filter = "supply like ? or sid like ? or process like ? or orderno like ? or sc like ? or pumname like ? or pumscale like ? or project like ?";
                    filter = filter.Replace("?", "'%" + search + "%'");
                    this.bs.Filter = filter;
                    tbFind.BackColor = Color.Lime;
                }
                tbFind.SelectAll();
                tbFind.Focus();
                showSummary();
            }
            catch (Exception ex)
            {
                this.tbFind.BackColor = Color.Tomato;
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

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

        void Func_Edit()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var newdr = drv.Row as dsPurchase.EETGW_PurchaseEBRow;

            bool repeat = false;
            DialogResult dlg;
            if (getAdminInput == false)
            {
                repeat = false;
                var f = new fPurchaseEB_Add(newdr);
                dlg = f.ShowDialog();
            }
            else
            {
                var f = new fPurchaseEB_Add(newdr);
                dlg = f.ShowDialog();
                repeat = f.repeatAdd;
            }

            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                //존재하지 않는 sid 는 추가를 해준다.
                var newidx = AddItemInfoGetIndex(newdr);
                if (newidx != -1)
                {
                    newdr.pumidx = newidx;
                    newdr.EndEdit();
                }
                if (newdr.RowState != DataRowState.Unchanged)
                {
                    this.ta.Update(newdr);
                    newdr.AcceptChanges();
                }
            }
            else newdr.RejectChanges();

        }



        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Func_Edit();
        }






        private void sC검색ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //sc
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var newdr = drv.Row as dsPurchase.EETGW_PurchaseEBRow;
            if (newdr.sc.Trim() == "")
            {
                FCOMMON.Util.MsgE("SC값이 없습니다");
                return;
            }
            tbFind.Text = newdr.sc;
            btFind.PerformClick();
        }

        private void cRCF검색ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //crcf
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var newdr = drv.Row as dsPurchase.EETGW_PurchaseEBRow;
            if (newdr.orderno.Trim() == "")
            {
                FCOMMON.Util.MsgE("CR/CF값이 없습니다");
                return;
            }
            tbFind.Text = newdr.orderno;
            btFind.PerformClick();
        }

        private void toolStripLabel2_Click(object sender, EventArgs e)
        {
            if (tbFind.Text != "")
            {
                tbFind.Text = "";
                btFind.PerformClick();
            }

        }

        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            var dr = bs.Current as dsPurchase.EETGW_PurchaseEBRow;
            //if (dr.IschkremarkNull()) richTextBox1.Text = "";
            //else richTextBox1.Text = dr.chkremark;
            //if (dr.IsbigoNull()) richTextBox2.Text = "";
            //else richTextBox2.Text = dr.bigo;
        }


        string getmaxstr(string src, int len = 30)
        {
            if (src.Length > len) return src.Substring(0, len) + "...";
            else return src;
        }

        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;
        }

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

            //데이터를 검색한다.
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                var dr = row.DataBoundItem as dsPurchase.EETGW_PurchaseEBRow;
                var qtyreq = 0;
                var qty = 0;
                if (dr.IspumqtyReqNull() == false) qtyreq = dr.pumqtyReq;
                if (dr.IspumqtyNull() == false) qty = dr.pumqty;
                if(qty < 1)
                {
                    Util.MsgE($"[{dr.sid}] {dr.pumname}의 구매 수량이 없습니다");
                    return; 
                }
                //if(qty > qtyreq)
                //{
                //    Util.MsgE($"[{dr.sid}] {dr.pumname}의 구매 수량이 요청 수량보다 많습니다");
                //    break;
                //}
            }

            //승인요청
            var dlg = FCOMMON.Util.MsgQ("현재 자료를 승인 요청 할까요?");
            if (dlg != DialogResult.Yes) return;

            //모든자료의 승인상태를 업데이트한다.
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                var dr = row.DataBoundItem as dsPurchase.EETGW_PurchaseEBRow;
                dr.conf_status = "1";
                if (dr.state == "---") dr.state = "Approving";
                dr.EndEdit();
                ta.Update(dr);
                dr.AcceptChanges();
            }

            dlg = FCOMMON.Util.MsgQ("메일 전송을 할까요?");
            if (dlg != DialogResult.Yes) return;


            //수신자목록수집

            //var drows = (List<dsPurchase.EETGW_PurchaseEBRow>)(this.bs.DataSource);
            var grp_req = rows.Where(t => t.request.isEmpty() == false).GroupBy(t => t.request).Select(t => t.FirstOrDefault().request).ToList();
            var grp_rec = rows.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 f = new Purchase.fMailForm("PJ");
            if (f.ShowDialog() != DialogResult.OK) return;

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


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

            try
            {
                NetOffice.OutlookApi.Application outlookApplication = new NetOffice.OutlookApi.Application();
                var newMail = outlookApplication.CreateItem(NetOffice.OutlookApi.Enums.OlItemType.olMailItem) as NetOffice.OutlookApi.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());
                string fn = "";
                if (f.chkAttach.Checked)
                {
                    var fi = new System.IO.FileInfo(FCOMMON.Util.CurrentPath + "\\Export\\PurchaseEB_confirmeb_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls");
                    if (fi.Directory.Exists == false) fi.Directory.Create();
                    fn = fi.FullName;
                    //FCOMMON.Util.savetoexcel(this.dataGridView1, fi.FullName);


                    //newMail.Attachments.Add(fi.FullName);
                }
                var rows = this.rows;
                var tabledata = UTIL_EQ0000.MakeDataTableToHTML(rows, fn);


                if (fn.isEmpty() == false)
                    newMail.Attachments.Add(fn);

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

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as dsPurchase.EETGW_PurchaseEBRow;
            if (drv == null) return;
            var dlg = FCOMMON.Util.MsgQ("선택된 줄을 제거 할까요?");
            if (dlg != DialogResult.Yes) return;
            this.rows.Remove(drv);
            if (rows.Any())
            {
                this.bs.DataSource = rows;
                refreshData();
            }
            else
            {
                this.bs.DataSource = null;
                lbSum.Text = "";
            }
            this.dataGridView1.Refresh();
        }

        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();
            var dlg = FCOMMON.Util.MsgQ("입력되지 않은 구매수량을 신청수량으로 일괄 업데이트 할까요?");
            if (dlg != DialogResult.Yes) return;
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                var dr = row.DataBoundItem as dsPurchase.EETGW_PurchaseEBRow;
                if (dr.IspumqtyNull() == false && dr.pumqty > 0)
                {

                }
                else
                {
                    dr.pumqty = dr.pumqtyReq;
                    dr.EndEdit();
                }
            }
        }
    }
}
