using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using util = FCOMMON.Util;

namespace FPJ0000
{
    public partial class fPartBuyStatus : FCOMMON.fBase
    {
        string fn_fpcolsize = "";



        int colidx_itemname = -1;
        int colidx_item = -1;
        int colidx_qty = -1;
        int colidx_amt = -1;
        int colidx_price = -1;
        int colidx_model = -1;
        int colidx_supply = -1;
        int colidx_supplyidx = -1;
        int colidx_sid = -1;
        int colidx_manu = -1;
        int colidx_unit = -1;


        public fPartBuyStatus()
        {
            InitializeComponent();

            fn_fpcolsize = System.IO.Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                "formSetting",
                "fp_" + this.Name + ".ini");

            this.FormClosed += fPartList_FormClosed;
            this.FormClosing += FPartList_FormClosing;
            this.KeyDown += fPartList_KeyDown;
        }

        private void FPartList_FormClosing(object sender, FormClosingEventArgs e)
        {
            var dt = this.dsPRJ.ProjectsPart.GetChanges();
            if (dt != null && dt.Rows.Count > 0)
            {
                var dlg = FCOMMON.Util.MsgQ("변경된 자료가 있습니다.\n화면을 닫으면 손실됩니다.\n화면을 닫을까요?");
                if (dlg != DialogResult.Yes)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }


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

        void fPartList_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.FormClosed -= fPartList_FormClosed;
            this.KeyDown -= fPartList_KeyDown;
        }

        private void fPartList_Load(object sender, EventArgs e)
        {

            //열번호찾기
            foreach (FarPoint.Win.Spread.Column col in this.fpSpread1.ActiveSheet.Columns)
            {
                string colname = col.DataField.ToLower();
                if (colname == "itemmodel") colidx_model = col.Index;
                else if (colname == "itemname") colidx_itemname = col.Index;
                else if (colname == "item") colidx_item = col.Index;
                else if (colname == "qty") colidx_qty = col.Index;
                else if (colname == "price") colidx_price = col.Index;
                else if (colname == "amt") colidx_amt = col.Index;
                else if (colname == "itemsupplyidx") colidx_supplyidx = col.Index;
                else if (colname == "itemsupply") colidx_supply = col.Index;
                else if (colname == "itemsid") colidx_sid = col.Index;
                else if (colname == "itemmanu") colidx_manu = col.Index;
                else if (colname == "itemunit") colidx_unit = col.Index;
            }
            this.Show();
            //this.bsPart.Sort = "bbuy,ItemSupply,qtyin";
            Application.DoEvents();
            RefreshData();
        }

        string sortkey = string.Empty;
        void RefreshData()
        {
            if (dsPRJ.HasChanges())
            {
                var dlg = FCOMMON.Util.MsgQ("변경 사항이 있습니다. 갱신하면 변경 내용이 손실 됩니다.\n지금 갱신 하겠습니까?");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }
            //if (button3.BackColor != Color.Gold) bsPart.Filter = "status not like '완료%'";
            //else bsPart.Filter = "";

            try
            {
                this.taPartStatus.Fill(this.dsPRJ.ProjectPartStatus, FCOMMON.info.Login.gcode);
                //this.bsPart.Sort = "bbuy,bconfirm,userManager,project";
                if (this.bsPart.Count > 0) this.bsPart.Position = 0; //210120 (박성민s)
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }

            //로딩후에 sid 와 suuply 를 조회해준다.
            //foreach (dsPRJ.ProjectsPartRow dr in this.dsPRJ.ProjectsPart.Rows)
            //{
            //    if (dr.IsItemNull() || dr.Item < 0) continue;
            //    var iteminfo = FCOMMON.DBM.getItemInfo(dr.Item);
            //    if (iteminfo.idx != -1)
            //    {
            //        dr.SID = iteminfo.sid;
            //        //dr.Supply = iteminfo.supply;
            //    }
            //}
            //this.dsPRJ.AcceptChanges();
            RefreshSum();
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            FormattingData();
        }
        void FormattingData()
        {
            //삭제컬럼인덱스
            this.fpSpread1.SuspendLayout();
            var col_sid = this.fpSpread1.ActiveSheet.Columns["sid"].Index;
            //var col_pmp = this.fpSpread1.ActiveSheet.Columns["pmp"].Index;
            var col_buy = this.fpSpread1.ActiveSheet.Columns["buy"].Index;  //구매수량
            var col_amt = this.fpSpread1.ActiveSheet.Columns["amt"].Index;
            var col_amtn = this.fpSpread1.ActiveSheet.Columns["amtn"].Index;
            var col_qtyin = this.fpSpread1.ActiveSheet.Columns["qtyin"].Index;
            var col_qtyn = this.fpSpread1.ActiveSheet.Columns["qtyn"].Index;    //N대수량(전체수량)
            var col_prReady = this.fpSpread1.ActiveSheet.Columns["bbuy"].Index;    //PR여부
            var col_supply = this.fpSpread1.ActiveSheet.Columns["supply"].Index;
            var col_poReady = this.fpSpread1.ActiveSheet.Columns["bconfirm"].Index;   //PO여부


            var 전체건수 = 0;
            var 구매요청건T = 0;
            var 구매요청건C = 0;
            var 비구매건수 = 0;
            var PR대상수량 = 0;
            var PR완료수량 = 0;
            var PO대상수량 = 0;
            var 구매진행 = 0;
            var 구매완료 = 0;
            var 입력오류 = 0;

            //var 검토완료건수 = 0;

            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var row = this.fpSpread1.ActiveSheet.Rows[i];


                var value = this.fpSpread1.ActiveSheet.GetValue(i, col_sid);   //sid값을 확인한다
                var value_buy = this.fpSpread1.ActiveSheet.GetValue(i, col_buy);
                var value_in = this.fpSpread1.ActiveSheet.GetValue(i, col_qtyin);
                var value_prready = this.fpSpread1.ActiveSheet.GetValue(i, col_prReady);
                var db_supply = this.fpSpread1.ActiveSheet.GetValue(i, col_supply);
                var value_supply = string.Empty;
                if (db_supply != null) value_supply = db_supply.ToString().Trim();
                var value_poready = this.fpSpread1.ActiveSheet.GetValue(i, col_poReady);

                Boolean bPR = false;
                Boolean bPO = false;

                if (value_prready != null) bPR = (Boolean)value_prready;
                if (value_poready != null) bPO = (Boolean)value_poready;

                if (bPR)
                {
                    PR완료수량 += 1;

                }

                전체건수 += 1;

                int qty_in = 0;
                int qty_buy = -1;
                if (value_in != null) qty_in = (int)value_in;
                if (value_buy != null) qty_buy = (int)value_buy;

                if (qty_buy < 1)    //구매요청 수량자체가 없다.(비구매건)
                {
                    비구매건수 += 1;
                    row.ForeColor = Color.Black;
                    row.BackColor = Color.White;
                }
                else
                {
                    PR대상수량 += 1;    //비구매아닌건 모두 PR대상수량이다


                    //구매가 필요한 상황임
                    if (bPR == false)
                    {
                        //PR이 입력되지 않았따.                        
                        if (qty_in > 0 )
                        {
                            입력오류 += 1;
                            row.ForeColor = Color.White;
                            row.BackColor = Color.Red;
                        }
                        else
                        {
                            구매요청건C += 1;
                            row.ForeColor = Color.Black;
                            row.BackColor = Color.LightSkyBlue;
                        }
                    }
                    else if (bPO == false) //PO 입력대기 (발주완율)
                    {
                        if (qty_in > 0 )
                        {
                            입력오류 += 1;
                            row.ForeColor = Color.White;
                            row.BackColor = Color.Red;
                        }
                        else
                        {
                            PO대상수량 += 1;
                            row.ForeColor = Color.Black;
                            row.BackColor = Color.Gold;
                        }
         
                    }
                    else
                    {
                        //PR,PO 가 모두 입력되었다

                        if (qty_in < qty_buy)
                        {
                            구매진행 += 1;

                            row.ForeColor = Color.White;
                            row.BackColor = Color.DarkMagenta;
                        }
                        else
                        {
                            구매완료 += 1;
                            row.ForeColor = Color.Black;
                            row.BackColor = Color.LimeGreen;
                        }
                    }
                }
            }

            //프로그레시브입력
            //prb6.Text = string.Format("전체 진행 ({0}/{1})", 비구매건수 + 구매완료건수, 전체건수);
            //prb6.ProgressMax = 전체건수;
            //prb6.ProgressValue = 비구매건수 + 구매완료건수;

            prb1.Text = string.Format("{0}", 구매요청건C);

            prb2.Text = string.Format("{0}", PO대상수량);

            prb3.Text = string.Format("{0}", 구매진행);

            prb4.Text = string.Format("{0}", 입력오류);


            //prb1.Text = string.Format("수량 검토 완료 ({0}/{1})", 검토완료건수, 전체건수);
            //prb1.ProgressMax = 전체건수;
            //prb1.ProgressValue = 검토완료건수;

            //var 전체건수 = 0;
            //var 비구매건수 = 0;
            //var 구매진행건수 = 0;
            //var 구매완료건수 = 0;
            //var 구매등록건수 = 0;
            //var 검토완료건수 = 0;


            this.fpSpread1.ResumeLayout();
        }

        void RefreshSum()
        {
            decimal sum = this.dsPRJ.ProjectsPart.Where(t => t.RowState != DataRowState.Deleted && t.RowState != DataRowState.Detached).Sum(t => t.amt);
            decimal sumN = this.dsPRJ.ProjectsPart.Where(t => t.RowState != DataRowState.Deleted && t.RowState != DataRowState.Detached).Sum(t => t.amtn);


            //lbSum.Text = string.Format("1:{0:N0} / N:{1:N0}", sum, sumN);
        }


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

            ////모든데이터의 공백을 제거(sid)
            //foreach (var item in this.dsPRJ.ProjectsPart)
            //{
            //    //sid에 공백제거
            //    if (item.RowState == DataRowState.Deleted || item.RowState == DataRowState.Detached) continue;
            //    if (item.ItemSid != item.ItemSid.Replace(" ", "").Trim())
            //    {
            //        item.ItemSid = item.ItemSid.Replace(" ", "").Trim();
            //        item.EndEdit();
            //    }
            //}

            try
            {
                var cnt = this.taPartStatus.Update(this.dsPRJ.ProjectPartStatus);
                FCOMMON.Util.MsgI(cnt.ToString() + "건의 자료가 업데이트 되었습니다.");
                this.dsPRJ.AcceptChanges();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            FormattingData();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            var drv = this.bsPart.Current as DataRowView;
            var dr = drv.Row as dsPRJ.ProjectPartStatusRow;
            var f = new rPartList(dr.Project);
            f.Show();
        }


        private void exportListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            var fn = "partliststatus.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();

            switch (this.fpSpread1.ActiveSheet.Columns[Colidx].DataField.ToLower())
            {
                case "supplyname":
                    var valuen1 = fpSpread1.ActiveSheet.Cells[Rowidx, Colidx].Value;//.Rows[Rowidx].Cells[e.ColumnIndex].Value;
                    if (valuen1 != null)
                    {
                        string inputtext1 = valuen1.ToString().Trim();
                        if (inputtext1 != "")
                        {
                            FCM0000.fLovSupply f = new FCM0000.fLovSupply(inputtext1);
                            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supply].Value = f.Title;
                                fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supplyidx].Value = f.Index;
                            }
                            else
                            {
                                //fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supply].Value = string.Empty;
                                fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supplyidx].Value = -1;
                            }
                        }
                    }
                    break;
                case "itemname":
                    var valuen = fpSpread1.ActiveSheet.Cells[Rowidx, Colidx].Value;//.Rows[Rowidx].Cells[e.ColumnIndex].Value;
                    if (valuen != null)
                    {
                        string inputtext = valuen.ToString().Trim();
                        if (inputtext != "")
                        {
                            //검색을 실행해서 보여준다.
                            var SearchDT = taItem.GetSearch("%" + inputtext + "%", FCOMMON.info.Login.gcode);
                            if (SearchDT == null || SearchDT.Rows.Count < 1)
                            {
                                //FCOMMON.Util.MsgE("검색 결과가 없습니다.");
                                fpSpread1.ActiveSheet.ActiveColumnIndex += 2;
                                return;
                            }
                            else
                            {
                                //검색된 결과를 표시해서 보여준다.
                                var f = new FCM0000.fLovItem("%" + inputtext + "%");
                                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                                {
                                    //var c = fpSpread1.ActiveSheet.Columns["sdf"];

                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_item].Value = f.item;
                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_itemname].Value = f.itemName;

                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_sid].Value = f.SID.Replace(" ", "").Trim();

                                    //공급사는 기록하지 않는다  200623
                                    //fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supplyidx].Value = f.itemSupplyidx;
                                    //fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supply].Value = f.itemSupply;

                                    //제조사추가  201022 - 박성민
                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_manu].Value = f.itemManu.Replace(" ", "").Trim();
                                    //단위추가 201028 - 박성민
                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_unit].Value = f.itemUnit.Replace(" ", "").Trim();

                                    if (f.itemmodel != "")
                                        fpSpread1.ActiveSheet.Cells[Rowidx, colidx_model].Value = f.itemmodel;

                                    if (f.itemprice != 0)
                                        fpSpread1.ActiveSheet.Cells[Rowidx, colidx_price].Value = f.itemprice;

                                    var valueq1 = fpSpread1.ActiveSheet.Cells[Rowidx, colidx_qty].Value;
                                    var valuep1 = fpSpread1.ActiveSheet.Cells[Rowidx, colidx_price].Value;

                                    Int32 iQty = 0;
                                    decimal iPrice = 0;
                                    if (valueq1 != null && valueq1.ToString() != "") iQty = (Int32)valueq1;
                                    if (valuep1 != null && valuep1.ToString() != "") iPrice = (decimal)valuep1;
                                    decimal iAmt = iQty * iPrice;
                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_amt].Value = iAmt;
                                }
                            }
                        }
                    }
                    break;
                case "price":
                case "qty":
                    var valueq = fpSpread1.ActiveSheet.Cells[Rowidx, colidx_qty].Value;
                    var valuep = fpSpread1.ActiveSheet.Cells[Rowidx, colidx_price].Value;

                    Int32 iQty1 = 0;
                    decimal iPrice1 = 0;
                    if (valueq != null && valueq.ToString() != "") iQty1 = (Int32)valueq;
                    if (valuep != null && valuep.ToString() != "") iPrice1 = (decimal)valuep;

                    var amt = iQty1 * iPrice1;
                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_amt].Value = amt;
                    //dv1.Rows[e.RowIndex].Cells["dvc_amt"].Value = amt;
                    RefreshSum();
                    break;

            }
        }

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

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            var drv = this.bsPart.Current as DataRowView;
            var dr = drv.Row as dsPRJ.ProjectPartStatusRow;
            var f = new fProjectPartImport(dr.Project);
            f.ShowDialog();
            this.RefreshData();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            var chg = this.dsPRJ.ProjectsPart.GetChanges();
            if (chg != null)
            {
                FCOMMON.Util.MsgE("변경된 자료가 있습니다. \n 해당 자료를 먼저 저장하세요");
                return;
            }
            var drv = this.bsPart.Current as DataRowView;
            var dr = drv.Row as dsPRJ.ProjectPartStatusRow;
            var f = new fProjectPartToPurchase(dr.Project, sortkey);
            f.ShowDialog();
        }

        private void tbFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var search = tbFind.Text.Trim();
                var ColumnList = new string[] { "ItemName", "ItemModel", "ItemSupply", "ItemManu", "ItemSid" };
                var Filter = "";
                if (search != "")
                {
                    foreach (var item in ColumnList)
                    {
                        if (Filter != "") Filter += " or ";
                        Filter += item + " like '%{0}%'";
                    }
                }
                try
                {
                    if (Filter != "")
                    {
                        this.bsPart.Filter = string.Format(Filter, search.Replace("'", "''"));
                        tbFind.BackColor = Color.Lime;
                    }
                    else
                    {
                        this.bsPart.Filter = "";
                        tbFind.BackColor = SystemColors.Window;
                    }
                }
                catch
                {
                    this.bsPart.Filter = "";
                    tbFind.BackColor = Color.HotPink;
                }
                FormattingData();
                this.tbFind.SelectAll();
                this.tbFind.Focus();
                if (this.bsPart.Count > 0) this.bsPart.Position = 0;
                else util.MsgE("자료가 없습니다");
            }
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            var range = this.fpSpread1_Sheet1.GetSelection(0);
            util.MsgE("준비중");
        }

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

        private void toolStripButton5_Click_1(object sender, EventArgs e)
        {
            var dlg = FCOMMON.Util.MsgQ("재고 확인을 실행하시겠습니까?\n재고 확인 완료 후에는 구매수량값이 업데이트 됩니다");
            if (dlg != DialogResult.Yes) return;

            //pmp데이터에서 모두 업데이트 한다
            //컬럼명 qty, qty_pmp, qty_buy

            List<DatabaseManager.sPMPdata> retval = new List<DatabaseManager.sPMPdata>();
            var cn = DatabaseManager.getCn();
            try
            {
                cn.Open();
            }
            catch (Exception ex)
            {
                util.MsgE("데이터베이스 연결 실패\n" + ex.Message);
                return;
            }


            System.Data.SqlClient.SqlDataReader rdr = null;
            System.Data.SqlClient.SqlCommand cmd = null;
            var basesql1 = "select isnull(SIDNo,'') ,isnull(PartName,'') ,isnull(PartNo,'') , isnull(CurrentQty,0)   from SPMaster where SIDNo = '{0}' and isnull(Storage,'') <> 'B-CENTER'";
            var basesql2 = "select isnull(SIDNo,'') ,isnull(PartName,'') ,isnull(PartNo,'') , isnull(CurrentQty,0)   from SPMaster where PartNo = '{0}' and isnull(Storage,'') <> 'B-CENTER'";
            cmd = new System.Data.SqlClient.SqlCommand("", cn);

            var cnt_ok = 0;
            var cnt_no = 0;
            var cnt_ng = 0;
            //    var cnt_reduce = 0;
            foreach (dsPRJ.ProjectsPartRow dr in this.dsPRJ.ProjectsPart.Rows)
            {
                if (dr.RowState == DataRowState.Detached || dr.RowState == DataRowState.Deleted) continue;

                var qty = dr.qtyn; //파트리스트수량(N대수량으로 처리)
                var model = string.IsNullOrEmpty(dr.ItemModel) ? dr.ItemName : dr.ItemModel;

                //검색 sql 생성
                string sql = "";
                if (string.IsNullOrEmpty(dr.ItemSid) == true) sql = string.Format(basesql2, model);
                else sql = string.Format(basesql1, dr.ItemSid);
                cmd.CommandText = sql;

                rdr = cmd.ExecuteReader();
                List<DatabaseManager.sPMPdata> db = new List<DatabaseManager.sPMPdata>();
                while (rdr.Read())
                {
                    //데이터를 가져온다
                    var v_sidno = rdr[0];
                    var v_name = rdr[1];
                    var v_no = rdr[2];
                    var v_qty = rdr[3];

                    var newdr = new DatabaseManager.sPMPdata();
                    if (v_sidno != DBNull.Value) newdr.sid = v_sidno.ToString();
                    if (v_name != DBNull.Value) newdr.partname = v_name.ToString();
                    if (v_no != DBNull.Value) newdr.partno = v_no.ToString();
                    if (v_qty != DBNull.Value) newdr.qty = int.Parse(v_qty.ToString());
                    db.Add(newdr);
                }
                rdr.Close();

                //데이터가 여러개있다면 해당 데이터를 표시한다
                if (db.Count > 1)
                {
                    cnt_ng += 1;
                    dr.qtyjago = "{" + db.Count.ToString() + "}";
                    //dr.qtybuy = qty;
                }
                else if (db.Count == 1 && db[0].qty != 0)
                {
                    cnt_ok += 1;
                    dr.qtyjago = db[0].qty.ToString(); //재고수량
                                                       //dr.qtybuy = Math.Max(qty - db[0].qty, 0);
                                                       //cnt_reduce += (qty - dr.qtybuy);

                }
                else
                {
                    //pmp에 자료 없다
                    cnt_no += 1;
                    dr.qtyjago = "--";
                    //dr.qtybuy = qty;
                }
                dr.EndEdit();
            }


            if (cmd != null) cmd.Dispose();
            if (rdr != null) rdr.Close();

            cn.Close();
            cn.Dispose();

            var msg = string.Format("PMP 검색결과 현황\n" +
                "검색완료 : {0}\n" +
                "복수확인 : {1}\n" +
                "확인불가 : {2}", cnt_ok, cnt_ng, cnt_no);
            FCOMMON.Util.MsgI(msg);
        }

        void searchpmp()
        {
            //PMP조회
            var drv = this.bsPart.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectPartStatusRow;

            //검색어
            var title = string.IsNullOrEmpty(dr.ItemModel) ? dr.ItemName : dr.ItemModel;
            if (string.IsNullOrEmpty(dr.ItemSid) == false) title = dr.ItemSid;

            var f = new fSPMaster(title);
            if (f.ShowDialog() == DialogResult.OK)
            {
                var pmp = f.qty; //pmp재고
                var req = f.qty;
                var buy = Math.Max(req - pmp, 0);
                dr.qtyjago = pmp.ToString();
                dr.qtybuy = buy;
                dr.EndEdit();
            }
        }
        private void pMP조회ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            searchpmp();

        }

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

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

        private void btConf_Click(object sender, EventArgs e)
        {
            var f = new fPartConfirm(this.dsPRJ.ProjectsPart, sortkey);
            f.ShowDialog();
            FormattingData();
        }

        private void 검토목록모두구매등록상태로전환ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ////검토는 되어있지만 구매등록이 안된 목록 가져온다
            //var list = this.dsPRJ.ProjectsPart.Where(t => t.bconfirm == true && t.bbuy == false);
            //var cnt = list.Count();
            //if (cnt < 1)
            //{
            //    FCOMMON.Util.MsgE("검토목록 전체가 구매등록된 상태 입니다");
            //    return;
            //}
            //var dlg = FCOMMON.Util.MsgQ(string.Format("{0}건의 자료가 구매등록 대기 상태입니다\n\n구맹 등록상태로 전환 하시겠습니까?", cnt));
            //if (dlg == DialogResult.Yes)
            //{
            //    foreach (var dr in list)
            //    {
            //        dr.bbuy = true;
            //        dr.EndEdit();
            //    }
            //    this.FormattingData();
            //}
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            //쇼핑카드 데이터를 가져와서 검색을 실행한다
            this.Validate();
            this.bsPart.EndEdit();
            var f = new fSCCheck(this.dsPRJ.ProjectsPart);
            f.ShowDialog();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var drv = this.bsPart.Current as DataRowView;
            var dr = drv.Row as dsPRJ.ProjectPartStatusRow;
            var f = new rPartList(dr.Project);
            f.Show();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var drv = this.bsPart.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectPartStatusRow;


            var serverpath = Properties.Settings.Default.SharePath + @"\Project"; //

            if (dr.path.isEmpty() == false)
            {
                if (dr.path.StartsWith("\\")) serverpath += dr.path;
                else serverpath += "\\" + dr.path;
            }
            else serverpath += "\\" + dr.Project.ToString();
            
            //+ dr.Project.ToString();

            //if (tbPath == "") tbPath = "/" + dr.idx.ToString();

            //if (tbPath.StartsWith("\\") == false)
            //{
            //    if (tbPath.StartsWith("/")) tbPath = tbPath.Replace("/", "\\");
            //    else tbPath = "\\" + tbPath;
            //}
            //\\10.131.32.29\Data
           
            if (System.IO.Directory.Exists(serverpath) == false)
            {
                FCOMMON.Util.MsgE("프로젝트 경로가 존재하지 않아 진행할 수 없습니다\n\n" +
                    serverpath);
                return;
            }


            //if (tbPath.Equals(""))
            //{
            //    util.MsgE("공유폴더가 존재하지 않는 프로젝트 입니다. 프로젝트 정보에서 공유폴더를 클릭해 먼저 생성한 후 다시 시도하세요");
            //    return;
            //}

            //if (tbPath.StartsWith("\\") == false)
            //{
            //    if (tbPath.StartsWith("/")) tbPath = tbPath.Replace("/", "\\");
            //    else tbPath = "\\" + tbPath;
            //}

            //var serverpath = @"\\" + FCOMMON.info.serverip + @"\Data\Project";
            //if (System.IO.Directory.Exists(serverpath) == false)
            //{
            //    FCOMMON.Util.MsgE("프로젝트 기본경로가 존재하지 않아 진행할 수 없습니다\n\n" +
            //        serverpath);
            //    return;
            //}

            //var path = serverpath + tbPath;
            //if (System.IO.Directory.Exists(path) == false)
            //{
            //    FCOMMON.Util.MsgE("프로젝트 저장소 없음");
            //}

            FCOMMON.Util.RunExplorer(serverpath);
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            var drv = this.bsPart.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectPartStatusRow;

            var f = new fProjectPartListEdit(dr);
            if (f.ShowDialog() == DialogResult.OK)
            {
                FormattingData();

            }
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            //if (button3.BackColor == Color.Gold) button3.BackColor = SystemColors.Control;
            //else button3.BackColor = Color.Gold;
            //RefreshData();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var f = new FCOMMON.fSelectDay(DateTime.Now);
            if (f.ShowDialog() == DialogResult.OK)
            {
                var sd = f.dtPick.SelectionStart;
                var dlg = FCOMMON.Util.MsgQ(string.Format("CR# Due Date 값을 변경 할까요?\n" +
                    "변경전 : {0} -> 변경후 : {1}", this.tbDue.Text, sd.ToShortDateString()));
                if (dlg == DialogResult.Yes)
                {
                    var taprj = new dsPRJTableAdapters.ProjectsTableAdapter();
                    var cnt = taprj.UpdateCRDue(sd.ToShortDateString(), int.Parse(textBox5.Text), FCOMMON.info.Login.gcode);
                    if (cnt != 1)
                    {
                        FCOMMON.Util.MsgE($"적용실패 {cnt}건의 자료가 업데이트 됨");
                    }
                }
            }
        }

        private void bsPart_CurrentChanged(object sender, EventArgs e)
        {
            var drv = this.bsPart.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectPartStatusRow;
            if (dr.crdue.isEmpty() == false)
            {
                DateTime dt;
                if (DateTime.TryParse(dr.crdue, out dt))
                {
                    if (DateTime.Now >= dt) tbDue.BackColor = Color.Tomato;
                    else tbDue.BackColor = Color.White;
                }
                else tbDue.BackColor = Color.White;
            }
            else tbDue.BackColor = Color.White;

        }

        private void 선택반전ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void 선택해제ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.fpSpread1_Sheet1.ClearSelection();
        }

        private void 전체선택ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.fpSpread1_Sheet1.AddSelection(0, 0, this.fpSpread1_Sheet1.RowCount, this.fpSpread1_Sheet1.ColumnCount);
        }

        private void oNToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //pr
            var col_idx = this.fpSpread1_Sheet1.Columns["idx"].Index;
            var col_bbuy = this.fpSpread1_Sheet1.Columns["bbuy"].Index;
            var col_bcof = this.fpSpread1_Sheet1.Columns["bconfirm"].Index;

            var allselection = fpSpread1_Sheet1.GetSelections();
            if(allselection.Length < 1 )
            {
                FCOMMON.Util.MsgE("선택된 대상이 없습니다");
                return;
            }
            else
            {
                if (FCOMMON.Util.MsgQ(allselection.Length.ToString() + "건의 PR 상태를 ON으로 변경할까요?") != DialogResult.Yes) return;
            }
            fpSpread1.EditMode = true;
            foreach (var sel in allselection)
            {
                var vIDX = int.Parse(fpSpread1_Sheet1.Cells[sel.Row, col_idx].Value.ToString());
                var dr = this.dsPRJ.ProjectPartStatus.Where(t => t.idx == vIDX).FirstOrDefault();
                if (dr != null)
                {
                    dr.bbuy = true;
                    dr.EndEdit();
                }
                //fpSpread1_Sheet1.Cells[sel.Row, col_bbuy].Value = true;
                
            }
            fpSpread1.EditMode = false;

        }

        private void oFFToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //pr
            var col_idx = this.fpSpread1_Sheet1.Columns["idx"].Index;
            var col_bbuy = this.fpSpread1_Sheet1.Columns["bbuy"].Index;
            var col_bcof = this.fpSpread1_Sheet1.Columns["bconfirm"].Index;

            var allselection = fpSpread1_Sheet1.GetSelections();
            if (allselection.Length < 1)
            {
                FCOMMON.Util.MsgE("선택된 대상이 없습니다");
                return;
            }
            else
            {
                if (FCOMMON.Util.MsgQ(allselection.Length.ToString() + "건의 PR 상태를 OFF 로 변경할까요?") != DialogResult.Yes) return;
            }
            fpSpread1.EditMode = true;
            foreach (var sel in allselection)
            {
                var vIDX = int.Parse(fpSpread1_Sheet1.Cells[sel.Row, col_idx].Value.ToString());
                var dr = this.dsPRJ.ProjectPartStatus.Where(t => t.idx == vIDX).FirstOrDefault();
                if (dr != null)
                {
                    dr.bbuy = false;
                    dr.EndEdit();
                }
                //fpSpread1_Sheet1.Cells[sel.Row, col_bbuy].Value = true;

            }
            fpSpread1.EditMode = false;
        }

        private void oNToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //po
            var col_idx = this.fpSpread1_Sheet1.Columns["idx"].Index;
            var col_bbuy = this.fpSpread1_Sheet1.Columns["bbuy"].Index;
            var col_bcof = this.fpSpread1_Sheet1.Columns["bconfirm"].Index;

            var allselection = fpSpread1_Sheet1.GetSelections();
            if (allselection.Length < 1)
            {
                FCOMMON.Util.MsgE("선택된 대상이 없습니다");
                return;
            }
            else
            {
                if (FCOMMON.Util.MsgQ(allselection.Length.ToString() + "건의 PO 상태를 ON 으로 변경할까요?") != DialogResult.Yes) return;
            }
            fpSpread1.EditMode = true;
            foreach (var sel in allselection)
            {
                var vIDX = int.Parse(fpSpread1_Sheet1.Cells[sel.Row, col_idx].Value.ToString());
                var dr = this.dsPRJ.ProjectPartStatus.Where(t => t.idx == vIDX).FirstOrDefault();
                if (dr != null)
                {
                    dr.bconfirm = true;
                    dr.EndEdit();
                }
                //fpSpread1_Sheet1.Cells[sel.Row, col_bbuy].Value = true;

            }
            fpSpread1.EditMode = false;

        }

        private void oFFToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //po
            var col_idx = this.fpSpread1_Sheet1.Columns["idx"].Index;
            var col_bbuy = this.fpSpread1_Sheet1.Columns["bbuy"].Index;
            var col_bcof = this.fpSpread1_Sheet1.Columns["bconfirm"].Index;

            var allselection = fpSpread1_Sheet1.GetSelections();
            if (allselection.Length < 1)
            {
                FCOMMON.Util.MsgE("선택된 대상이 없습니다");
                return;
            }
            else
            {
                if (FCOMMON.Util.MsgQ(allselection.Length.ToString() + "건의 PO 상태를 OFF 로 변경할까요?") != DialogResult.Yes) return;
            }
            fpSpread1.EditMode = true;
            foreach (var sel in allselection)
            {
                var vIDX = int.Parse(fpSpread1_Sheet1.Cells[sel.Row, col_idx].Value.ToString());
                var dr = this.dsPRJ.ProjectPartStatus.Where(t => t.idx == vIDX).FirstOrDefault();
                if (dr != null)
                {
                    dr.bconfirm = false;
                    dr.EndEdit();
                }
                //fpSpread1_Sheet1.Cells[sel.Row, col_bbuy].Value = true;

            }
            fpSpread1.EditMode = false;
        }
    }
}
