using FCOMMON;
using NetOffice.OutlookApi;
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;

namespace FPJ0000
{
    public partial class fProjectPartToPurchaseCR : fBase
    {
        int ProjectIndex = -1;
        List<int> IDXList;
        bool isCR = false;
        public fProjectPartToPurchaseCR(int pidx, List<int> idxlist, bool isCR)
        {
            InitializeComponent();
            // dv1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            IDXList = idxlist;
            this.ProjectIndex = pidx;
            this.KeyPreview = true;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.isCR = isCR;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };

            dv1.CellEndEdit += Dv1_CellEndEdit;
            Col_Price = dv1.Columns["dvc_price"].Index;
            Col_PriceD = dv1.Columns["dvc_priced"].Index;
            Col_Qty = dv1.Columns["dvc_qty"].Index;
            Col_amt = dv1.Columns["dvc_amt"].Index;
            this.Text = isCR ? "파트리스트 CR등록" : "파트리스트 NR등록";
            this.panel1.BackColor = isCR ? Color.FromArgb(192, 192, 255) : Color.FromArgb(192, 255, 255);
            toolStripButton4.Text = isCR ? "CR구매등록" : "NR구매등록";
            toolStripButton6.Visible = isCR == false;

            if (isCR)
            {
                btEQManu.Visible = false;
                btEQModel.Visible = false;
                btEQProc.Visible = false;
                label4.Visible = false;
                label8.Visible = false;
                label5.Visible = false;
            }

        }

        int Col_Price = -1;
        int Col_PriceD = -1;
        int Col_Qty = -1;
        int Col_amt = -1;
        private void Dv1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == Col_Price || e.ColumnIndex == Col_Qty)
            {
                var o_price = dv1.Rows[e.RowIndex].Cells[Col_Price].Value;
                var o_qty = dv1.Rows[e.RowIndex].Cells[Col_Qty].Value;
                decimal v_price = 0;
                decimal v_qty = 0;
                if (o_price != null) v_price = decimal.Parse(o_price.ToString());// (decimal)o_price;
                if (o_qty != null) v_qty = decimal.Parse(o_qty.ToString());//(decimal)o_qty;
                var amt = v_price * v_qty;
                dv1.Rows[e.RowIndex].Cells[Col_amt].Value = amt;
                dv1.EndEdit();
            }



            //newdr.pumprice = (decimal)item.Cells["dvc_price"].Value;
            //newdr.pumqty = (int)item.Cells["dvc_qty"].Value;
        }

        void MakeList(dsPRJ.ProjectsPartDataTable dt)
        {
            var orderdata = dt
                .OrderBy(t => string.Concat(t.ItemSid, t.ItemName));

            this.dv1.Rows.Clear();
            var emptycount = 0;
            foreach (dsPRJ.ProjectsPartRow dr in orderdata)
            {
                if (this.IDXList.Contains(dr.idx) == false) continue;

                if (dr.IsItemSidNull())
                {
                    emptycount += 1;
                    continue;
                }
                else if (dr.ItemSid.Length != 9 && isCR)    //cR은 신규를 허용하지 않는다.
                {
                    emptycount += 1;
                    continue;
                }

                var rowidx = this.dv1.Rows.Add();
                var row = this.dv1.Rows[rowidx];

                var col = 0;
                row.Cells[col++].Value = dr.ItemSid;
                row.Cells[col++].Value = dr.ItemName;
                row.Cells[col++].Value = dr.ItemModel;
                row.Cells[col++].Value = dr.price;
                row.Cells[col++].Value = dr.priceD;
                row.Cells[col].Tag = dr.qty;
                row.Cells[col++].Value = dr.qty;
                row.Cells[col++].Value = dr.qty;
                row.Cells[col++].Value = dr.price * dr.qty;
                // row.Cells[col++].Value = 0;
                row.Cells[col++].Value = "";
                row.Cells[col++].Value = dr.memo;

                row.Tag = dr;

                //Boolean bbuy = dr.bbuy;
                var supplyname = dr.ItemSupply.Trim();
            }

            // this.listView1.ResumeLayout();
            this.dv1.AutoResizeColumns();
            showSummary();
            if (emptycount > 0)
            {
                FCOMMON.Util.MsgE($"{emptycount} 개의 데이터는 SID가 없어 추가되지 않았습니다.");
            }
        }
        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            toolStripButton2.Text = "선택삭제(&D)";
            var dtPrj = taProject.GetbyIDX(this.ProjectIndex);
            var drPrj = dtPrj.Rows[0] as dsPRJ.ProjectsRow;
            this.tbProjectIndex.Text = drPrj.idx.ToString();
            this.textBox1.Text = drPrj.remark_ans;
            this.tbProject.Text = drPrj.name;
            this.btEQProc.Text = drPrj.process; //공정 240207
            this.btEQProc.Tag = "";
            this.btEQManu.Tag = "";
            this.btEQModel.Tag = "";
            this.tbCr.Text = drPrj.orderno;
            //this.tbOrderNo.Text = drPrj.orderno;

            //구매-담당
            var LstMan = FCOMMON.DBM.getCodeTable("65");
            this.tbManager.DisplayMember = "Value";
            this.tbManager.ValueMember = "Value";
            this.tbManager.DataSource = LstMan;

            //파트리스트 합계금액
            var dtPart = taPart.GetData(this.ProjectIndex);
            MakeList(dtPart);


            if (tbManager.Text.isEmpty() && tbManager.Items.Count == 1)
            {
                tbManager.Text = (tbManager.Items[0] as DataRowView)["Value"].ToString();
            }


            ////상태
            //var stateList = FCOMMON.DBM.getCodeTable("04");
            //this.cmbState.DisplayMember = "Value";
            //this.cmbState.ValueMember = "Value";
            //this.cmbState.DataSource = stateList;

            ////장비제조            
            //var dt_dept = FCOMMON.DBM.getCodeTable("06");
            //BindingSource bsManu = new BindingSource(dt_dept, "");
            //this.cbEQManu.DisplayMember = "Value";
            //this.cbEQManu.ValueMember = "Value";
            //this.cbEQManu.DataSource = bsManu;

            ////장비모델            
            //var dt_asset = FCOMMON.DBM.getCodeTable("07");
            //bsModel = new BindingSource(dt_asset, "");
            //bsModel.Filter = "svalue='그런거없다'";
            //this.cbEQModel.DisplayMember = "Value";
            //this.cbEQModel.ValueMember = "Value";
            //this.cbEQModel.DataSource = bsModel;

            ////제조공정
            //var dt_manuproc = FCOMMON.DBM.getCodeTable("08");
            //this.cbManuProc.DisplayMember = "Value";
            //this.cbManuProc.ValueMember = "Value";
            //this.cbManuProc.DataSource = dt_manuproc;

            ////장비기술공정
            //var dt_eetproc = FCOMMON.DBM.getCodeTable("09");
            //this.cbProcess.DisplayMember = "Value";
            //this.cbProcess.ValueMember = "Value";
            //this.cbProcess.DataSource = dt_eetproc;

            ////processlist
            //var procList = FCOMMON.DBM.getGroupTable("process", "Purchase", "process <> ''");
            //this.cbProcess.DisplayMember = "Value";
            //this.cbProcess.ValueMember = "Key";
            //this.cbProcess.DataSource = new BindingSource(procList, "");

            //담당자목록
            //담당자목록 - 사용자목록으로 처리한다.    
            string namestr = string.Format("{0}({1})", FCOMMON.info.Login.nameK, FCOMMON.info.Login.no);
            if (FCOMMON.info.Login.no == "dev") namestr = "김치균(395552)";
            this.cmbRequest.Items.Clear();
            this.cmbRequest.Items.Add(namestr);
            try
            {
                var cn = FCOMMON.DBM.getCn();
                cn.Open();
                string sql = "select [id],[name] " +
                            " from vGroupUser" +
                            " where gcode='{1}' and isnull(useUserState,0) = 1 and id <> '{0}'" +
                            " order by [name]";
                sql = string.Format(sql, FCOMMON.info.Login.no, FCOMMON.info.Login.gcode);
                var cmd = new System.Data.SqlClient.SqlCommand(sql, cn);
                var rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    string cmbdata = string.Format("{1}({0})", rdr[0].ToString(), rdr[1].ToString());
                    this.cmbRequest.Items.Add(cmbdata);
                }
                cmd.Dispose();
                cn.Close();
                cn.Dispose();
            }
            catch (System.Exception ex)
            {
                FCOMMON.Util.MsgE("User List Error\n\n" + ex.Message);
            }
            cmbRequest.Text = namestr;// FCOMMON.info.Login.nameK;


            dtPdate.Value = DateTime.Now;

            //cmbState.Text = "PR";   //po에서 변경 200423 - JBS요청


            this.Show();
            System.Windows.Forms.Application.DoEvents();
        }


        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            //파트리스트 합계금액
            var dtPart = taPart.GetData(this.ProjectIndex);
            MakeList(dtPart);
        }
        void showSummary()
        {
            //모든 선택된 자료의 합계를 표시한다
            decimal sumAmt = 0;
            foreach (DataGridViewRow item in dv1.Rows)
            {
                var v = item.Cells["dvc_amt"].Value;
                if (v != null)
                {
                    if (decimal.TryParse(v.ToString(), out decimal vv))
                        sumAmt += vv;
                }

            }
            this.tbSum.Text = sumAmt.ToString("N0");

        }
        private bool saveData()
        {
            this.Validate();

            //spm에값이 없으면 처리하지 못함
            foreach (DataGridViewRow row in this.dv1.Rows)
            {
                var spmval = row.Cells["dvc_spm"].Value.ToString();
                var sidval = row.Cells["dvc_sid"].Value.ToString();//dvc_price
                var prival = row.Cells["dvc_price"].Value.ToString().Replace(",", "");//dvc_price
                if (spmval.isEmpty())
                {
                    FCOMMON.Util.MsgE("SPM검사가 완료되지 않았습니다");
                    return false;
                }
                if (chkPriceZero.Checked == false)
                {
                    decimal.TryParse(prival, out decimal price);
                    if (price < 2)
                    {
                        FCOMMON.Util.MsgE("단가를 입력해야 합니다\n신규 품목이라면 견적서의 단가를 입력하세요\n" +
                            "기존 품목 중 단가를 알 수 없다면 [구매담당]에게 문의하세요\n" +
                            "0원 단가를 강제 입력하려면 상단의 '단가 0원 입력허용] 체크를 한 후 다시 시도하세요");
                        return false;
                    }
                }
            }


            if (this.dv1.Rows.Count < 1)
            {
                FCOMMON.Util.MsgE("자료가 없습니다");
                return false;
            }

            if (isCR)
            {
                if (tbProject.Text == "")
                {
                    FCOMMON.Util.MsgE("프로젝트 정보를 입력하세요.");
                    tbProject.Focus();
                    return false;
                }

                if (string.IsNullOrEmpty(tbCr.Text))
                {
                    FCOMMON.Util.MsgE("SCR/CF값이 없습니다. 프로젝트 정보를 확인하세요");
                    tbCr.Focus();
                    return false;
                }
            }
            else
            {
                if (btEQProc.Tag.ToString() == "")
                {
                    FCOMMON.Util.MsgE("장비 공정을 선택하세요");
                    return false;
                }
                if (btEQManu.Tag.ToString() == "")
                {
                    FCOMMON.Util.MsgE("장비 제조사를 선택하세요");
                    return false;
                }
            }

            if (tbManager.Text.isEmpty())
            {
                FCOMMON.Util.MsgE("구매담당자를 선택 하세요");
                tbManager.Focus();
                return false;
            }

            int itemCount = 0;
            decimal itemAmt = 0;
            foreach (DataGridViewRow item in dv1.Rows)
            {
                itemCount += 1;
                var amt = (decimal)item.Cells["dvc_amt"].Value;
                itemAmt += amt;// int.Parse(item.SubItems[7].Text.Replace(",", "").Trim());
            }

            //part 목록을 조회해서 NR에 등록해줘야 함
            var dlg2 = FCOMMON.Util.MsgQ("해당 파트리스트를 " + (isCR ? "CR" : "NR") + "구매 목록에 등록 하시겠습니까?\n" +
                itemCount.ToString() + "건 " + itemAmt.ToString("N0") + "원");
            if (dlg2 != System.Windows.Forms.DialogResult.Yes) return false;


            string userNo = this.cmbRequest.Text.Substring(cmbRequest.Text.LastIndexOf('(') + 1);
            userNo = userNo.Substring(0, userNo.Length - 1);

            ////기존에 등록된 자료가 있는지 체크한다.
            //var SQLExist =
            //    " select count(*) from EETGW_PurchaseCR" +
            //    " where import = 1" +
            //    " and gcode = '" + FCOMMON.info.Login.gcode + "' and pdate = '{0}' and state in ('---','PR','')" +
            //    " and projectidx = {1}";
            //SQLExist = string.Format(SQLExist, dtPdate.Value.ToString("yyyy-MM-dd"), this.ProjectIndex.ToString());
            //var ExistCnt = FCOMMON.DBM.ExecuteScalarI(SQLExist);
            //if (ExistCnt > 0)
            //{
            //    var dlgq = FCOMMON.Util.MsgQ(string.Format("생성된 자료가 {0}건 존재 합니다.\n\n" + "기존 자료를 삭제 하시겠습니까?", ExistCnt));
            //    if (dlgq == System.Windows.Forms.DialogResult.Yes)
            //    {
            //        SQLExist =
            //      " delete from EETGW_PurchaseCR" +
            //      " where import = 1" +
            //      " and gcode = '" + FCOMMON.info.Login.gcode + "' and pdate = '{0}' and state in ('---','PR','')" +
            //      " and projectidx = {1}";
            //        SQLExist = string.Format(SQLExist, dtPdate.Value.ToString("yyyy-MM-dd"), this.ProjectIndex.ToString());
            //        var delCnt = FCOMMON.DBM.ExecuteNonQuery(SQLExist);
            //        Console.WriteLine(delCnt.ToString() + "건의 기존 입력된 자료가 삭제됨");
            //    }
            //}

            var fProg = new FCOMMON.fProgress();
            fProg.Title = (isCR ? "CR" : "NR") + "구매파트 자료 집계 중";
            fProg.SetProgress(0, itemCount);
            fProg.Show();
            fProg.Refresh();

            //데이터를 넣는다

            var dtCR = new dsPurchase.EETGW_PurchaseCRDataTable();
            var dtNR = new dsPurchase.PurchaseDataTable();

            var skipcnt = 0;
            foreach (DataGridViewRow item in dv1.Rows)
            {
                var dr = item.Tag as dsPRJ.ProjectsPartRow;
                var sid = dr.ItemSid.Replace(" ", "").Trim();

                var o_price = item.Cells[Col_Price].Value;
                var o_priceD = item.Cells[Col_PriceD].Value;
                var o_qty = item.Cells[Col_Qty].Value;
                decimal v_price = 0;
                decimal v_priceD = 0;
                int v_qty = 0;
                if (o_price != null) v_price = decimal.Parse(o_price.ToString());
                if (o_priceD != null) v_priceD = decimal.Parse(o_priceD.ToString());
                if (o_qty != null) v_qty = int.Parse(o_qty.ToString());

                if (v_qty < 1)
                {
                    skipcnt += 1;
                    fProg.IncProgress();
                    continue;
                }



                bool newadd = false;
                if (isCR)
                {
                    var newdr = dtCR.Where(t => t.sid == sid).FirstOrDefault();
                    //insert query
                    if (newdr == null)
                    {
                        newdr = dtCR.NewEETGW_PurchaseCRRow();
                        newadd = true;
                    }
                    // newdr.asset = cbEQModel.Text.Trim();
                    //  newdr.dept = cbEQModel.Text.Trim();
                    ///newdr.manuproc = cbManuProc.Text.Trim();



                    if (newadd)
                    {
                        newdr.gcode = FCOMMON.info.Login.gcode;
                        newdr.pdate = dtPdate.Value.ToString("yyyy-MM-dd");
                        newdr.state = "---";// cmbState.Text.Trim();
                        newdr.request = userNo.Trim();
                        newdr.sid = dr.ItemSid.Replace(" ", "").Trim();
                        newdr.pumname = dr.ItemName.Trim();
                        newdr.pumidx = dr.Item;
                        newdr.pumscale = dr.ItemModel;
                        newdr.pumunit = dr.ItemUnit;
                        newdr.pumprice = v_price;// (decimal)item.Cells[Col_Price].Value;//dr.price;
                        newdr.pumpriceD = v_priceD;
                        newdr.pumqtyReq = v_qty;// (int)item.Cells[Col_Qty].Value;// dr.qty;      //SQL = SQL.Replace("{qty}", dr.qty.ToString());   //일반수량이 아닌 필요수량으로
                        newdr.pumamt = v_price * v_qty;// (decimal)item.Cells["dvc_amt"].Value;// dr.amt;  //SQL = SQL.Replace("{amt}", dr.amt.ToString());
                        newdr.supply = dr.ItemSupply.Trim();
                        newdr.supplyidx = dr.ItemSupplyidx;
                        newdr.project = tbProject.Text.Trim();
                        newdr.projectidx = int.Parse(tbProjectIndex.Text);
                        newdr.import = true;
                        newdr.wuid = FCOMMON.info.Login.no;
                        newdr.wdate = DateTime.Now;
                        newdr.orderno = tbCr.Text.Trim();
                        newdr.bigo = item.Cells["dvc_remark"].Value.ToString();//dr.memo.Trim();
                   //     if (newdr.bigo.isEmpty()) newdr.bigo = tbProject.Text;
                        newdr.chk1 = true;
                        newdr.currency = "KRW";
              

                        newdr.EndEdit();
                        dtCR.AddEETGW_PurchaseCRRow(newdr);
                    }
                    else
                    {
                        newdr.pumqtyReq += v_qty;// (int)item.Cells[Col_Qty].Value;// dr.qty;      //SQL = SQL.Replace("{qty}", dr.qty.ToString());   //일반수량이 아닌 필요수량으로
                        newdr.pumamt += v_price * v_qty;// (decimal)item.Cells["dvc_amt"].Value;// dr.amt;  //SQL = SQL.Replace("{amt}", dr.amt.ToString());
                        if (newdr.bigo.isEmpty() == false) newdr.bigo += ",";
                        newdr.bigo += item.Cells["dvc_remark"].Value.ToString();//dr.memo.Trim();
                        if (newdr.IscurrencyNull() || newdr.currency.isEmpty())
                            newdr.currency = "KRW";

                 //       if (newdr.bigo.isEmpty()) newdr.bigo = tbProject.Text;

             

                        newdr.chk1 = true;
                        newdr.EndEdit();
                    }

                    //if (radioButton1.Checked)
                    //

                    //}
                    //else
                    //{
                    //    //실제 구매에 필요한 수량으로 처리
                    //    newdr.pumqty = dr.qtybuy;
                    //    newdr.pumamt = dr.qtybuy * dr.price;
                    //}

                }
                else
                {
                    var newdr = dtNR.Where(t => t.sid == sid).FirstOrDefault();
                    //insert query
                    if (newdr == null || sid.Equals("신규"))
                    {
                        newdr = dtNR.NewPurchaseRow();
                        newadd = true;
                    }
                    // newdr.asset = cbEQModel.Text.Trim();
                    //  newdr.dept = cbEQModel.Text.Trim();
                    ///newdr.manuproc = cbManuProc.Text.Trim();



                    if (newadd)
                    {
                        newdr.process = FCOMMON.info.Login.process;
                        newdr.gcode = FCOMMON.info.Login.gcode;
                        newdr.pdate = dtPdate.Value.ToString("yyyy-MM-dd");
                        newdr.state = "---";// cmbState.Text.Trim();
                        newdr.request = userNo.Trim();
                        newdr.sid = dr.ItemSid.Replace(" ", "").Trim();
                        newdr.pumname = dr.ItemName.Trim();
                        newdr.pumidx = dr.Item;
                        newdr.pumscale = dr.ItemModel;
                        newdr.pumunit = dr.ItemUnit;
                        newdr.pumprice = v_price;// (decimal)item.Cells[Col_Price].Value;//dr.price;
                        newdr.pumpriceD = v_priceD;
                        newdr.pumqtyReq = v_qty;// (int)item.Cells[Col_Qty].Value;// dr.qty;      //SQL = SQL.Replace("{qty}", dr.qty.ToString());   //일반수량이 아닌 필요수량으로
                        newdr.pumamt = v_price * v_qty;// (decimal)item.Cells["dvc_amt"].Value;// dr.amt;  //SQL = SQL.Replace("{amt}", dr.amt.ToString());
                        newdr.supply = dr.ItemSupply.Trim();
                        newdr.supplyidx = dr.ItemSupplyidx;
                        newdr.project = tbProject.Text.Trim();
                        newdr.projectidx = int.Parse(tbProjectIndex.Text);
                        newdr.import = true;
                        newdr.wuid = FCOMMON.info.Login.no;
                        newdr.wdate = DateTime.Now;
                        newdr.orderno = tbCr.Text.Trim();
                        newdr.purchase_manager = tbManager.Text.Trim();
                        newdr.currency = "KRW";
                        newdr.bigo = item.Cells["dvc_remark"].Value.ToString();//dr.memo.Trim();
                        if (newdr.bigo.isEmpty()) newdr.bigo = $"[{tbProject.Text}]";
                        newdr.chk1 = true;
                        newdr.dept = btEQProc.Tag.ToString();
                        newdr.manuproc = btEQManu.Tag.ToString();
                        newdr.asset = btEQModel.Tag.ToString();
                        newdr.EndEdit();
                        dtNR.AddPurchaseRow(newdr);
                    }
                    else
                    {
                        newdr.chk1 = true;
                        newdr.pumqtyReq += v_qty;// (int)item.Cells[Col_Qty].Value;// dr.qty;      //SQL = SQL.Replace("{qty}", dr.qty.ToString());   //일반수량이 아닌 필요수량으로
                        newdr.pumamt += v_price * v_qty;// (decimal)item.Cells["dvc_amt"].Value;// dr.amt;  //SQL = SQL.Replace("{amt}", dr.amt.ToString());
                        newdr.process = FCOMMON.info.Login.process;
                        if (newdr.bigo.isEmpty() == false) newdr.bigo += ",";
                        newdr.bigo += item.Cells["dvc_remark"].Value.ToString();//dr.memo.Trim();
                        //if (newdr.bigo.isEmpty()) newdr.bigo = $"[{tbProject.Text}]";

                        if (newdr.IscurrencyNull() || newdr.currency.isEmpty())
                            newdr.currency = "KRW";
                        newdr.dept = btEQProc.Tag.ToString();
                        newdr.manuproc = btEQManu.Tag.ToString();
                        newdr.asset = btEQModel.Tag.ToString();
                        //newdr.bigo += "," + item.Cells["dvc_remark"].Value.ToString();//dr.memo.Trim();
                        newdr.purchase_manager = tbManager.Text.Trim();
                        newdr.EndEdit();
                    }

                    //if (radioButton1.Checked)
                    //

                    //}
                    //else
                    //{
                    //    //실제 구매에 필요한 수량으로 처리
                    //    newdr.pumqty = dr.qtybuy;
                    //    newdr.pumamt = dr.qtybuy * dr.price;
                    //}

                }



                // Console.WriteLine(SQL);
                fProg.IncProgress();

            }
            int addcnt = 0;
            if (isCR)
            {
                var ta = new dsPurchaseTableAdapters.EETGW_PurchaseCRTableAdapter();
                addcnt = ta.Update(dtCR);
            }
            else
            {
                var ta = new dsPurchaseTableAdapters.PurchaseTableAdapter();
                addcnt = ta.Update(dtNR);
            }

            //비고를 업데이트한다.
            foreach (DataGridViewRow row in this.dv1.Rows)
            {
                var drpart = row.Tag as dsPRJ.ProjectsPartRow;

                var vmemo = row.Cells["dvc_remark"].Value;
                if (vmemo != null)
                {
                    drpart.memo = vmemo.ToString();
                    drpart.EndEdit();
                }
            }

            if (skipcnt > 0)
            {
                FCOMMON.Util.MsgE($"{skipcnt}건은 수량이 없어 등록되지 않았습니다");
            }


            FCOMMON.Util.MsgI(string.Format("{0}/{1}건의 자료가 생성 되었습니다.\n\n구매등록 화면에서 내용을 확인하세요.", addcnt, itemCount));
            fProg.Close();
            fProg.Dispose();

            return true;
        }



        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            var dlg = FCOMMON.Util.MsgQ("현재 선택된 줄을 삭제 할까요?");
            if (dlg != DialogResult.Yes) return;

            var rows = this.dv1.SelectedCells;
            if (rows.Count < 1)
            {
                FCOMMON.Util.MsgE("선택된 줄이 없습니다");
                return;
            }

            List<int> delrows = new List<int>();
            foreach (DataGridViewCell cel in rows)
            {
                if (delrows.Contains(cel.RowIndex) == false)
                    delrows.Add(cel.RowIndex);
            }
            if (delrows.Count < 1)
            {
                FCOMMON.Util.MsgE("선택된 줄이 없습니다");
                return;
            }

            foreach (var r in delrows.OrderByDescending(t => t))
            {
                this.dv1.Rows.RemoveAt(r);
            }


            //foreach (ListViewItem lv in this.listView1.Items)
            //    lv.Checked = false;
            showSummary();
        }



        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.dv1.EndEdit();
            if (!saveData()) return;
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

            var cnt = 0;
            var ecnt = 0;
            foreach (DataGridViewRow row in dv1.Rows)
            {
                var spm = row.Cells["dvc_spm"].Value.ToString();
                if (spm.isEmpty() == false) continue;
                var sid = row.Cells["dvc_sid"].Value.ToString();
                if (sid.Length != 9 || sid.StartsWith("10") == false)
                {
                    row.Cells["dvc_spm"].Value = "SID오류";
                    row.Cells["dvc_spm"].Tag = 0;
                    cnt += 1;
                }
                else
                {
                    var dt = AmkorRestfulService.SPMSIDSearch(sid);
                    if (dt.Complete)
                    {
                        row.Cells["dvc_spm"].Value = $"{dt.Result.Rows.Count}건";
                        row.Cells["dvc_spm"].Tag = dt.Result.Rows.Count;
                        ecnt += 1;
                    }
                    else
                    {
                        row.Cells["dvc_spm"].Value = $"없음";
                        row.Cells["dvc_spm"].Tag = 0;
                        cnt += 1;
                    }
                }
            }
            if (ecnt > 0)
            {
                FCOMMON.Util.MsgI($"{ecnt} 개의 자료가 SPM에서 자료가 검색되었습니다\n각 수량을 클릭해서 내용을 확인하세요");
            }
            this.dv1.AutoResizeColumns();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            var dlg = FCOMMON.Util.MsgQ("현재 구매수량에 SPM수량을 일괄 제외 할까요?");
            foreach (DataGridViewRow row in dv1.Rows)
            {
                var spm = row.Cells["dvc_spm"].Value.ToString();

            }
        }

        private void dv1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
            var col = this.dv1.Columns[e.ColumnIndex];
            if (col.Name == "dvc_spm")
            {
                //site검색 해야한다
                var sid = dv1.Rows[e.RowIndex].Cells["dvc_sid"].Value.ToString();// dr.sid;
                if (sid.Length != 9 || sid.StartsWith("10") == false)
                {
                    dv1.Rows[e.RowIndex].Cells["dvc_spm"].Value = "SID오류";
                    dv1.Rows[e.RowIndex].Cells["dvc_spm"].Tag = 0;
                }
                else
                {
                    var dt = AmkorRestfulService.SPMSIDSearch(sid);
                    if (dt.Complete)
                    {
                        dv1.Rows[e.RowIndex].Cells["dvc_spm"].Value = $"{dt.Result.Rows.Count}건";
                        dv1.Rows[e.RowIndex].Cells["dvc_spm"].Tag = dt.Result.Rows.Count;
                        var f = new FCM0000.fSIDListSelect(sid, dt.Result);
                        if (f.ShowDialog() == DialogResult.OK)
                        {
                            var oldvalue = dv1.Rows[e.RowIndex].Cells["dvc_remark"].Value;
                            if (oldvalue == null)
                                dv1.Rows[e.RowIndex].Cells["dvc_remark"].Value = "SPM:" + f.selectbatch;
                            else
                                dv1.Rows[e.RowIndex].Cells["dvc_remark"].Value = oldvalue.ToString() + ",SPM:" + f.selectbatch;
                        }
                    }
                    else
                    {
                        dv1.Rows[e.RowIndex].Cells["dvc_spm"].Value = "없음";
                        dv1.Rows[e.RowIndex].Cells["dvc_spm"].Tag = 0;
                    }
                }
            }
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {

            var url = @"https://atknet.amkor.co.kr/#/department/ee/spm";
            FCOMMON.Util.RunExplorer(url);
        }

        private void dv1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
           // var colr = "dvc_qtyreq";
           // var col = "dvc_qty";
            //dv1.Rows[e.RowIndex].Cells[e.ColumnIndex]
        }

        private void dv1_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            var coli = dv1.Columns["dvc_qty"].Index;
            var colr = dv1.Columns["dvc_qtyreq"].Index;
            if (e.ColumnIndex != coli && e.ColumnIndex != colr) return;
            var vqty = dv1.Rows[e.RowIndex].Cells[coli].Value;
            var vqtr = dv1.Rows[e.RowIndex].Cells[colr].Value;
            if (vqty != null && vqtr != null)
            {
                if (vqty.ToString() != vqtr.ToString())
                {
                    dv1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightSkyBlue;
                }
                else
                {
                    dv1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
                }
            }
            else dv1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.DimGray;
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            var datapath = FCOMMON.DBM.getCodeSvalue("55", "02");
            if (datapath.isEmpty())
            {
                FCOMMON.Util.MsgE("견적서 기본폴더 공용코드 55-02 값을 입력하세요");
                return;
            }
            string path = System.IO.Path.Combine(datapath, DateTime.Now.Year.ToString("0000") + "년");// "\\\\k4fs3201n\\ee1t$\\1. 장비기술1파트\\24_Project & Overhaul 예산 사용 실적\\구매 견적서\\" + DateTime.Now.Year.ToString("0000") + "년";
            if (System.IO.Directory.Exists(path) == false)
                FCOMMON.Util.RunExplorer(datapath);
            else
                FCOMMON.Util.RunExplorer(path);
        }

        private void cmbProcess_Click(object sender, EventArgs e)
        {
            var bt = sender as Button;
            var guun = "08";// bt.Tag.ToString();
            var f = new FCM0000.fCode(guun);
            var dlg = f.ShowDialog();
            if (dlg == DialogResult.OK)
            {
                //장비기술공정;
                bt.Text = f.SelectedTitle;// cbProcess.SelectedIndex = -1;
                bt.Tag = f.SelectedTitle;
            }
        }

        private void cmbManu_Click(object sender, EventArgs e)
        {
            var bt = sender as Button;
            var guun = "06";// bt.Tag.ToString();
            var f = new FCM0000.fCode(guun);
            var dlg = f.ShowDialog();
            if (dlg == DialogResult.OK)
            {
                //장비기술공정;
                bt.Text = f.SelectedTitle;// cbProcess.SelectedIndex = -1;
                bt.Tag = f.SelectedTitle;
            }
        }

        private void cmbModel_Click(object sender, EventArgs e)
        {
            if (btEQManu.Text.isEmpty())
            {
                FCOMMON.Util.MsgE("장비 제조사가 선택되지 않았습니다");
                btEQManu.Focus();
                return;
            }

            string filter = "svalue='" + btEQManu.Text.Replace("'", "''") + "'";

            var bt = sender as Button;
            var guun = "07";// bt.Tag.ToString();
            var f = new FCM0000.fCode(guun, filter);
            var dlg = f.ShowDialog();
            if (dlg == DialogResult.OK)
            {
                //장비기술공정;
                bt.Text = f.SelectedTitle;// cbProcess.SelectedIndex = -1;
                bt.Tag = f.SelectedTitle;
            }
        }
    }
}
