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 util = FCOMMON.Util;

using NetOffice;
using Outlook = NetOffice.OutlookApi;
using NetOffice.OutlookApi.Enums;
using FEQ0000.Purchase;
using FCOMMON;
using NetOffice.OfficeApi;
using System.Web.Services.Protocols;
using System.Diagnostics;
using FarPoint.Win.Spread.CellType;
using FCM0000;
using GrapeCity.Win.Spread.InputMan.CellType;
using FarPoint.Win.Spread;
using System.Globalization;
using static System.Windows.Forms.AxHost;

namespace FEQ0000
{
    public partial class fPurchaseConfirm : FCOMMON.fBase
    {
        string fn_fpcolsize = "";

        public fPurchaseConfirm()
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            Properties.Settings.Default["EEEntities"] = FCOMMON.info.CS;

            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.FormClosing += FPurchase_FormClosing;
            this.FormClosed += __Closed;
            this.KeyPreview = true;
            this.KeyDown += FPurchaseConfirm_KeyDown;
        }

        private void FPurchaseConfirm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5) btReject.PerformClick();
            else if (e.KeyCode == Keys.F8) btConfirm.PerformClick();
        }

        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 (!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.purchase));
            IsAdmin = curLevel >= 5;
            if (curLevel >= 5)
            {
                btConfirm.Visible = true;

            }
            else
            {
                btConfirm.Visible = false;
            }
            toolStripButton5.Visible = btConfirm.Visible;

            //if (curLevel < 5)
            //{
            //    집계표ToolStripMenuItem.Visible = false;
            //}

            refreshData();

        }

        bool IsAdmin = false;

        private void refreshData()
        {
            try
            {
                taNR.FillByApprov(this.dsPurchase.Purchase, FCOMMON.info.Login.gcode);
                taCR.FillByApprov(this.dsPurchase.EETGW_PurchaseCR, FCOMMON.info.Login.gcode);
                taEB.FillByApprov(this.dsPurchase.EETGW_PurchaseEB, FCOMMON.info.Login.gcode);
                showSummary();
                dvCR.AutoResizeColumns();
                dvNR.AutoResizeColumns();
                dvEB.AutoResizeColumns();

                CellFormmatting(dvEB);
                CellFormmatting(dvNR);
                CellFormmatting(dvCR);

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

            FormattingData();
        }
        void FormattingData()
        {
            ////삭제컬럼인덱스
            //this.fpSpread1.SuspendLayout();
            //var delindex = this.fpSpread1.ActiveSheet.Columns["isdel"].Index;
            //var statindex = this.fpSpread1.ActiveSheet.Columns["state"].Index;
            //var crcfindex = this.fpSpread1.ActiveSheet.Columns["crcf"].Index;
            //var prjindex = this.fpSpread1.ActiveSheet.Columns["projectidx"].Index;


            //for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            //{
            //    var state = this.fpSpread1.ActiveSheet.GetValue(i, statindex);
            //    string stateStr = string.Empty;
            //    if (state != null) stateStr = state.ToString();

            //    var value = this.fpSpread1.ActiveSheet.GetValue(i, delindex);
            //    var crcf = this.fpSpread1.ActiveSheet.GetValue(i, crcfindex);

            //    var str_crcf = string.Empty;
            //    if (crcf != null) str_crcf = crcf.ToString();


            //    if (value != null && (Boolean)value)
            //    {
            //        this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.Red;
            //        this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.White;
            //    }
            //    else
            //    {
            //        //crcf 에 따라서 배경색 변경
            //        if (str_crcf != "")
            //            this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.FromArgb(50, Color.PowderBlue);
            //        else
            //            this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.White;


            //        switch (stateStr.ToLower())
            //        {
            //            case "cancled":
            //                this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Red;
            //                break;
            //            case "rejected":
            //                this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Tomato;
            //                break;
            //            case "spr":
            //                this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Magenta;
            //                break;
            //            case "---":
            //            case "----":
            //                this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Blue;
            //                break;
            //            case "received":
            //                this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Gray;
            //                break;
            //            case "hold":
            //                this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.HotPink;
            //                break;
            //            default:
            //                this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Black;
            //                break;
            //        }
            //    }

            //    //프로젝트가 걸린데이터는 글자를 bold체로 변경한다.
            //    var prjdata = this.fpSpread1.ActiveSheet.GetValue(i, prjindex);
            //    if (prjdata != null)
            //    {
            //        var pidx = (int)this.fpSpread1.ActiveSheet.GetValue(i, prjindex);
            //        if (pidx == -1)  //프로젝트가 없다
            //        {
            //            this.fpSpread1.ActiveSheet.Rows[i].Font = fBase;
            //        }
            //        else
            //        {
            //            this.fpSpread1.ActiveSheet.Rows[i].Font = fBold;
            //        }
            //    }
            //    else this.fpSpread1.ActiveSheet.Rows[i].Font = fBold;


            //}
            //this.fpSpread1.ResumeLayout();
        }

        private void saveData(Boolean prompt)
        {
            this.Validate();
            this.bsNR.EndEdit();
            this.bsCR.EndEdit();
            this.bsEB.EndEdit();

            try
            {
                var cnt = this.tam.UpdateAll(this.dsPurchase);
                if (prompt) FCOMMON.Util.MsgI(string.Format("{0}건의 자료가 저장 되었습니다.", cnt));
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("저장 실패\n" + ex.Message);
            }


        }
        void showSummary()
        {

            var sumNR = this.dsPurchase.Purchase.Sum(t => t.pumamt);
            var sumCR = this.dsPurchase.EETGW_PurchaseCR.Sum(t => t.pumamt);
            var sumEB = this.dsPurchase.EETGW_PurchaseEB.Sum(t => t.pumamt);
            //foreach (dsPurchase.PurchaseRow dr in this.dsPurchase.Purchase.Rows)
            //if (!dr.IspumamtNull()) sum += dr.pumamt;
            lbSumNR.Text = sumNR.ToString("N0");
            lbSumCR.Text = sumCR.ToString("N0");
            lbSumEB.Text = sumEB.ToString("N0");

            tabControl1.TabPages[0].Text = $"일반구매({dsPurchase.Purchase.Rows.Count})";
            tabControl1.TabPages[1].Text = $"CR구매({dsPurchase.EETGW_PurchaseCR.Rows.Count})";
            tabControl1.TabPages[2].Text = $"전자실구매({dsPurchase.EETGW_PurchaseEB.Rows.Count})";
        }


        private void btSave_Click(object sender, EventArgs e)
        {
            func_confirm(true);
        }


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

        void func_confirm(bool value)
        {
            var state = value ? "2" : "3";
            if (tabControl1.SelectedIndex == 0)
            {
                var dr = this.bsNR.Current as DataRowView;
                dr["conf_status"] = state;
                dr.EndEdit();
                if (bsNR.Position < bsNR.Count) bsNR.Position += 1;
                CellFormmatting(dvNR);
            }
            else if (tabControl1.SelectedIndex == 1)
            {
                var dr = this.bsCR.Current as DataRowView;
                dr["conf_status"] = state;
                dr.EndEdit();
                if (bsCR.Position < bsCR.Count) bsCR.Position += 1;
                CellFormmatting(dvCR);
            }
            else if (tabControl1.SelectedIndex == 2)
            {
                var dr = this.bsEB.Current as DataRowView;
                dr["conf_status"] = state;
                dr.EndEdit();
                if (bsEB.Position < bsEB.Count) bsEB.Position += 1;
                CellFormmatting(dvEB);
            }
         
        }

        void CellFormmatting(DataGridView dv)
        {
            foreach(DataGridViewRow drow in dv.Rows)
            {
                var dr = drow.DataBoundItem as DataRowView;
                var status = dr["conf_status"]?.ToString() ?? "0";
                if (status == "1") drow.DefaultCellStyle.BackColor = Color.White; //신청
                else if (status == "2") drow.DefaultCellStyle.BackColor = Color.Lime; //ok
                else if (status == "3") drow.DefaultCellStyle.BackColor = Color.Tomato; //ng
                else drow.DefaultCellStyle.BackColor = Color.DimGray; //etc
            }
            dv.Invalidate();
        }
        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            func_confirm(false);
        }
        void func_add()
        {
            var newdr = this.dsPurchase.Purchase.NewPurchaseRow();

            if (FCOMMON.info.Login.no == "dev")
                newdr.request = "395552";//string.Format("[{0}] {1}", "395552", "김치균");
            else
                newdr.request = FCOMMON.info.Login.no;

            var t1 = DBM.getCodeList("65");
            var t2 = DBM.getCodeList("66");
            if (t1.Count == 1)
                newdr.purchase_manager = t1.First().Value;
            if (t2.Count == 1)
                newdr.purchase_admin = t2.First().Value;

            repeat:

            bool repeat = false;
            DialogResult dlg;
            if (getAdminInput == false)
            {
                repeat = false;
                var f = new fPurchase_AddS(newdr);
                dlg = f.ShowDialog();
            }
            else
            {
                var f = new fPurchase_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();
                }

                this.dsPurchase.Purchase.AddPurchaseRow(newdr);

                int cnt = this.taNR.Update(newdr);
                if (cnt == 1)
                {
                    if (repeat)
                    {
                        FCOMMON.Util.MsgI("저장 완료\n\n연속 저장 모드이므로 직전에 입력된 자료가 자동으로 설정 됩니다.");

                    }
                    else FCOMMON.Util.MsgI("저장 완료");
                }
                else
                {
                    FCOMMON.Util.MsgE("저장 실패\n\n다시 시도하시고 증상이 반복되면 chikyun.kim@amkor.co.kr 로 문의 주십시요");
                }


                newdr.AcceptChanges();
                if (repeat)
                {
                    var newdro = this.dsPurchase.Purchase.NewPurchaseRow();
                    FCOMMON.Util.CopyData(newdr, newdro);
                    newdro.idx = -1;
                    newdro.wdate = DateTime.Now;
                    newdr = newdro; //change
                    goto repeat;
                }
                else refreshData(); //181210
            }
            else newdr.Delete();



        }
        void func_delete()
        {
            var drv = bsNR.Current as DataRowView;
            if (drv == null) return;

            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.purchase));
            var dr = drv.Row as dsPurchase.PurchaseRow;
            if (dr.sc != "")
            {
                if (curLevel < 5)
                {
                    FCOMMON.Util.MsgE("일반 사용자는 SC값이 있는 자료를 삭제할 수 없습니다.");
                    return;
                }
            }

            if (dr.request != FCOMMON.info.Login.no)
            {
                if (curLevel < 5)
                {
                    FCOMMON.Util.MsgE("일반 사용자는 타인의 자료를 삭제할 수 없습니다.");
                    return;
                }
            }

            if (curLevel < 5)
            {
                var dlg = FCOMMON.Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }
            else
            {
                var dlg = FCOMMON.Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?\n저장 버튼을 눌러야 최종 삭제 됩니다");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }

            bsNR.RemoveCurrent();

            //일반사용자는 데이터를 바로 삭제한다.
            if (curLevel < 5)
            {
                try
                {
                    int cnt = taNR.Update(this.dsPurchase);
                    if (cnt != 1)
                        FCOMMON.Util.MsgE(cnt.ToString() + "건의 자료가 삭제되었습니다.");
                }
                catch (Exception ex)
                {
                    FCOMMON.Util.MsgE("delete error\n" + ex.Message);
                }
            }
        }

        private int AddItemInfoGetIndex(dsPurchase.PurchaseRow 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 copyDataToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }


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

            bool repeat = false;
            DialogResult dlg;
            if (getAdminInput == false)
            {
                repeat = false;
                var f = new fPurchase_AddS(newdr);
                dlg = f.ShowDialog();
            }
            else
            {
                var f = new fPurchase_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.taNR.Update(newdr);
                    newdr.AcceptChanges();
                }
            }
            else newdr.RejectChanges();

        }


        void func_copy()
        {
            var drv = this.bsNR.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPurchase.PurchaseRow;

            //현재 데이터를 입력하여 신규 추가를 한다.
            var newdr = this.dsPurchase.Purchase.NewPurchaseRow();
            FCOMMON.Util.CopyData((System.Data.DataRow)dr, (System.Data.DataRow)newdr);
            newdr.orderno = string.Empty; //CR값 복사 안하게  210823
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.wdate = DateTime.Now;
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.state = "---";
            if (newdr.sid.Length != 9 && newdr.sid.StartsWith("10") == false)
                newdr.sid = string.Empty;

            newdr.bigo = string.Empty;
            newdr.bigo2 = string.Empty;
            newdr.purchase_manager = string.Empty;

            newdr.request = FCOMMON.info.Login.no;
            newdr.receive = "";// FCOMMON.info.Login.nameK;
            newdr.sc = string.Empty;
            newdr.po = string.Empty;
            newdr.indate = string.Empty;
            newdr.edate = string.Empty;
            newdr.pumqty = 0; //실구매수량은 제거
            newdr.idx = -1;
            newdr.EndEdit();

        repeat:

            bool repeat = false;
            DialogResult dlg;
            if (getAdminInput == false)
            {
                var f = new fPurchase_AddS(newdr);
                dlg = f.ShowDialog();
            }
            else
            {
                var f = new fPurchase_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();
                }

                this.dsPurchase.Purchase.AddPurchaseRow(newdr);
                this.taNR.Update(newdr);
                newdr.AcceptChanges();

                if (repeat)
                {
                    var newdro = this.dsPurchase.Purchase.NewPurchaseRow();
                    FCOMMON.Util.CopyData(newdr, newdro);
                    newdro.idx = -1;
                    newdro.wdate = DateTime.Now;
                    newdr = newdro; //change
                    goto repeat;
                }
            }
            else newdr.Delete();
        }


        private void 집계표ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Purchase.rPurchaseNR f = new Purchase.rPurchaseNR();
            f.MdiParent = this.MdiParent;
            f.Show();
        }


        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            var drv = this.bsNR.Current as DataRowView;

        }



        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 구매승인양식ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //구매승인양식
            var f = new fPurchaseNRList(this.dsPurchase.Purchase);
            f.Show();

        }


        void func_ipgo()
        {
            var drv = this.bsNR.Current as DataRowView;
            var dr = drv.Row as dsPurchase.PurchaseRow;

            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.purchase));
            if (curLevel < 5)   //일반사용자 입고 여부
            {
                if (dr.state != "PO" && dr.state != "PR")
                {
                    FCOMMON.Util.MsgE("PR/PO 상태의 자료만 입고처리가 가능 합니다");
                    return;
                }
                //if (dr.request != FCOMMON.info.Login.no)
                //{
                //    FCOMMON.Util.MsgE("타인의 자료는 입고 처리할 수 없습니다");
                //    return;
                //}
            }
            var f = new FEQ0000.Purchase.fPurchaseNR_Ipgo(dr.idx, string.Empty);
            if (f.ShowDialog() == DialogResult.OK)
            {
                refreshData();
            }
        }


        private void toolStripButton5_Click_1(object sender, EventArgs e)
        {
            //state 가 ---인 데이터를 기준으로 함
            //chk2 ==false 인 자료를 기준으로 함
          

            fSIDCheckNR f = null;

            if(tabControl1.SelectedIndex == 0)
            {
                var newlist = this.dsPurchase.Purchase.Where(t => (t.Ischk2Null() || t.chk2 == false) && t.state.Equals("---")).ToList();
                if (newlist.Any() == false)
                {
                    FCOMMON.Util.MsgE($"신규 신청 데이터가 없습니다");
                    return;
                }
                f = new fSIDCheckNR(newlist);
            }
                
            else if(tabControl1.SelectedIndex == 1)
            {
                var newlist = this.dsPurchase.EETGW_PurchaseCR.Where(t => (t.Ischk2Null() || t.chk2 == false) && t.state.Equals("---")).ToList();
                if (newlist.Any() == false)
                {
                    FCOMMON.Util.MsgE($"신규 신청 데이터가 없습니다");
                    return;
                }
                f = new fSIDCheckNR(newlist);
            }

            else if (tabControl1.SelectedIndex == 2)
            {
                var newlist = this.dsPurchase.EETGW_PurchaseEB.Where(t => (t.Ischk2Null() || t.chk2 == false) && t.state.Equals("---")).ToList();
                if (newlist.Any() == false)
                {
                    FCOMMON.Util.MsgE($"신규 신청 데이터가 없습니다");
                    return;
                }
                f = new fSIDCheckNR(newlist);
            }

            if (f == null) return;

            if (f.ShowDialog() == DialogResult.OK)
            {
                //var cnt = 0;
                //foreach (var idx in f.chklist)
                //{
                //    var dr = newlist.Where(t => t.idx == idx).FirstOrDefault();
                //    if (dr != null)
                //    {
                //        cnt += 1;
                //        dr.chk2 = true;
                //        if (dr.IspumqtyNull() || dr.pumqty == 0) dr.pumqty = dr.pumqtyReq;
                //        dr.EndEdit();
                //    }
                //}
                //FCOMMON.Util.MsgI($"{cnt}건의 자료가 [구매담당확인] 되었습니다\n저장을 눌러야 최종 적용 됩니다");
            }
        }

        private void toolStripButton2_Click_2(object sender, EventArgs e)
        {
            //save
            saveData(true);
        }

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

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