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

namespace FPJ0000
{
    public partial class fPartList : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        int ProjectIndex = -1;


        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 fPartList(int idx_)
        {
            InitializeComponent();

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

            this.ProjectIndex = idx_;
            this.FormClosed += fPartList_FormClosed;
            this.FormClosing += FPartList_FormClosing;
            this.KeyDown += fPartList_KeyDown;
            this.dsPRJ.ProjectsPart.TableNewRow += ProjectsPart_TableNewRow;
        }

        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 ProjectsPart_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["Project"] = this.ProjectIndex;
            e.Row["qtybuy"] = 0;
        }

        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;
            this.dsPRJ.ProjectsPart.TableNewRow -= ProjectsPart_TableNewRow;


            //정렬방식 저장값 저장하기
            var SetFile = util.CurrentPath + "FormSetting.xml";
            arUtil.XMLHelper xml = new arUtil.XMLHelper(SetFile);
            if (xml.Exist() == false) xml.CreateFile();

            if (radSortGrp.Checked)
                xml.set_Data("partlist", "sort", "0");
            else
                xml.set_Data("partlist", "sort", "1");
            xml.Save();
        }

        private void fPartList_Load(object sender, EventArgs e)
        {

            

            //정렬방식 저장값 불러오기
            var SetFile = util.CurrentPath + "FormSetting.xml";
            arUtil.XMLHelper xml = new arUtil.XMLHelper(SetFile);
            if (xml.Exist() == false) xml.CreateFile();
            if (xml.get_Data("partlist", "sort", "0") == "0") radSortGrp.Checked = true;
            else radSortNo.Checked = true;

            //열번호찾기
            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();
            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;
            }

            try
            {
                //프로젝트 정보 채우기
                this.ta.FillByIDX(this.dsPRJ.Projects, this.ProjectIndex);

                //order by 절은 다시 생성한다.
                var SSQl = " SELECT  * FROM ProjectsPart " +
                           " WHERE Project  = @prj";
                if (radSortGrp.Checked)
                {
                    sortkey = "itemgroup asc,option1 asc ,no asc,itemname asc";
                    //SSQl += " order by itemgroup,option1,no,itemname";
                }
                else if (radSortNo.Checked) sortkey = "no";
                else sortkey = "qtyin";

                SSQl += " order by " + sortkey;

                this.dsPRJ.ProjectsPart.Clear();
                var cmd = new System.Data.SqlClient.SqlCommand(SSQl, taPart.Connection);
                cmd.Parameters.Add("prj", SqlDbType.Int).Value = this.ProjectIndex;
                var da = new System.Data.SqlClient.SqlDataAdapter(cmd);
                da.Fill(this.dsPRJ.ProjectsPart);
            }
            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_breq = this.fpSpread1.ActiveSheet.Columns["bbuy"].Index;        //구매요청
            var col_supply = this.fpSpread1.ActiveSheet.Columns["supply"].Index;
            var col_bconf = this.fpSpread1.ActiveSheet.Columns["bconfirm"].Index;   //구매확정
            var col_cancel = this.fpSpread1.ActiveSheet.Columns["cancel"].Index;   //구매확정


            var 전체건수 = 0; //전체자료
            var 비구매 = 0;    //구매수량이 입력안된자료
            var 구매요청 = 0; //PR이 체크안된고 구매수량이 입력된 자료
            var PO대기 = 0; //PR이 체크되어있으나 PO가 체크안된데이터
            var 구매진행 = 0; // PO가 체크되어있으나 입고수량이 구매수량보다 적은 경우
            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_bbuy = this.fpSpread1.ActiveSheet.GetValue(i, col_breq);  //구매요청
                var value_bconf = this.fpSpread1.ActiveSheet.GetValue(i, col_bconf);//구매확정 210118
                var db_cancel = this.fpSpread1.ActiveSheet.GetValue(i, col_cancel);
                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();

                Boolean b_cancel = false;
                if (db_cancel != null) b_cancel = (bool)db_cancel;
                //var value_bconf = this.fpSpread1.ActiveSheet.GetValue(i, col_bconf);

                Boolean bPR = false;
                Boolean bPO = false;

                if (value_bbuy != null) bPR = (Boolean)value_bbuy; //PR체크박스
                if (value_bconf != null) bPO = (Boolean)value_bconf; //PO체크박스


                전체건수 += 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 (b_cancel == true)
                {
                    row.ForeColor = Color.White;
                    row.BackColor = Color.Red;
                }
                else if (qty_buy < 1) //비구매건
                {
                    비구매 += 1;
                    row.ForeColor = Color.Black;
                    row.BackColor = Color.White;
                }
                else
                {
                    //여기서부터는 무조건 구매대상이다
                    if (bPR == false)
                    {
                        if (qty_in > 0 )
                        {
                            입력오류 += 1;
                            row.ForeColor = Color.White;
                            row.BackColor = Color.Red;
                        }
                        else
                        {
                            구매요청 += 1;
                            row.ForeColor = Color.Black;
                            row.BackColor = Color.SkyBlue;
                        }
                    }
                    else if (bPO == false)
                    {
                        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
                    {
                        if (qty_in != qty_buy)
                        {
                            구매진행 += 1;
                            row.ForeColor = Color.White;
                            row.BackColor = Color.DarkMagenta;
                        }
                        else
                        {
                            구매완료 += 1;
                            row.ForeColor = Color.Black;
                            row.BackColor = Color.LimeGreen;
                        }
                    }
                }
            }

            //프로그레시브입력



            prb1.Text = string.Format("비 구매 ({0})", 비구매);
            prb2.Text = string.Format("구매요청 ({0})", 구매요청);
            prb3.Text = string.Format("발주대기 ({0})", PO대기);
            prb4.Text = string.Format("구매진행 ({0})", 구매진행);

            var 구매율 = (구매완료 + 비구매) / (전체건수 * 1.0);
            prb5.Text = string.Format("구매완료 ({0:N0}%)", 구매율 * 100.0);
            prb6.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()
        {

            var rows = dsPRJ.ProjectsPart.Select(this.bsPart.Filter);
            decimal s1 = 0;
            decimal s2 = 0;
            foreach (dsPRJ.ProjectsPartRow dr in rows)
            {
                if (dr.RowState == DataRowState.Detached || dr.RowState == DataRowState.Deleted) continue;
                s1 += dr.amt;
                s2 += dr.amtn;
            }


            //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}", s1, s2);
        }


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

            //모든데이터의 공백을 제거(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.tam.UpdateAll(this.dsPRJ);
                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 f = new rPartList(this.ProjectIndex);
            f.Show();
        }


        private void exportListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            var fn = nameTextBox.Text.Trim();
            if (textBox1.Text.Trim() != "") fn += "_" + textBox1.Text.Trim();
            sd.FileName = fn + ".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.Trim();
                                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.Trim();

                                    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.Trim();

                                    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 f = new fProjectPartImport(ProjectIndex);
            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 f = new fProjectPartToPurchase(ProjectIndex, 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[] { "ItemGroup", "option1", "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;
                    }

                    RefreshSum();
                    //FormattingData();

                }
                catch
                {
                    this.bsPart.Filter = "";
                    tbFind.BackColor = Color.HotPink;
                }
                FormattingData();
                this.tbFind.SelectAll();
                this.tbFind.Focus();

            }
        }

        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.ProjectsPartRow;

            //검색어
            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)
        {

        }

        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.bs.EndEdit();
            this.bsPart.EndEdit();
            var f = new fSCCheck(this.dsPRJ.ProjectsPart);
            f.ShowDialog();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var f = new rPartList(this.ProjectIndex);
            f.Show();
        }

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

            var tbPath = dr.path;
            if (tbPath == "") tbPath = "/" + tbIdx.Text;

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

            var serverpath = @"\\10.131.32.33\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(path);
        }
    }
}
