using AR;
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)
        {

            EnsureVisibleAndUsableSize();

            //정렬방식 저장값 불러오기
            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();
            if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
            if (this.RestoreBounds.X + this.RestoreBounds.Width < 300 && this.RestoreBounds.X < 0)
                this.Location = new Point(0, 0);
        }

        string sortkey = string.Empty;

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


            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

        void RefreshData()
        {
            if (dsPRJ.HasChanges())
            {
                var dlg = FCOMMON.Util.MsgQ("변경 사항이 있습니다. 갱신하면 변경 내용이 손실 됩니다.\n지금 갱신 하겠습니까?");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }

            RefreshPrjectData();

            //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);



            //로딩후에 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_qtyn = this.fpSpread1.ActiveSheet.Columns["qtyn"].Index;    //N대수량(전체수량)
            var col_supply = this.fpSpread1.ActiveSheet.Columns["ItemSupply"].Index;

            //구매요청컬럼값
            var col_buyrq = this.fpSpread1.ActiveSheet.Columns["구매요청"].Index;
            var col_buypr = this.fpSpread1.ActiveSheet.Columns["구매승인"].Index;
            var col_buypo = this.fpSpread1.ActiveSheet.Columns["구매진행"].Index;
            var col_byuin = this.fpSpread1.ActiveSheet.Columns["구매완료"].Index;

            //var col_inuser = this.fpSpread1.ActiveSheet.Columns["구매수령인"].Index;
            //var col_indate = this.fpSpread1.ActiveSheet.Columns["구매수령일"].Index;
            //var col_inbigo = this.fpSpread1.ActiveSheet.Columns["구매비고"].Index;


            var 전체건수 = 0; //전체자료
            var 비구매 = 0;    //구매수량이 입력안된자료
            var 구매요청 = 0; //PR이 체크안된고 구매수량이 입력된 자료
            var PO대기 = 0; //PR이 체크되어있으나 PO가 체크안된데이터
            var 구매진행 = 0; // PO가 체크되어있으나 입고수량이 구매수량보다 적은 경우
            var 구매완료 = 0; // 입고수량 >= 구매수량
            //var 입력오류 = 0;

            var project = int.Parse(tbIdx.Text);
            var TotInfo = new FCOMMON.DBM.buyinfo();

            List<string> sidlist = new List<string>();
            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var v_supply = string.Empty;
                var v_sid = string.Empty;
                //Boolean bPR = false;
                //Boolean bPO = false;

                var row = this.fpSpread1.ActiveSheet.Rows[i];
                //     var value_buy = this.fpSpread1.ActiveSheet.GetValue(i, col_buy);
                var db_supply = this.fpSpread1.ActiveSheet.GetValue(i, col_supply);
                var db_sid = this.fpSpread1.ActiveSheet.GetValue(i, col_sid);
                if (db_sid != null) v_sid = db_sid.ToString();
                if (db_supply != null) v_supply = db_supply.ToString().Trim();

                //해당 자료의 CR구매현황을 확인한다(gcode,project,sid)
                FCOMMON.DBM.buyinfo sidinfo;
                if (v_sid.isEmpty() == false && v_sid.Length == 9 && v_sid.StartsWith("10"))
                {
                    if (v_sid == "109017115")
                    {
                        System.Diagnostics.Debugger.Break();
                    }

                    if (sidlist.Contains(v_sid))
                    {
                        //한번 계산했던 SID이다
                        //sidinfo = new FCOMMON.DBM.buyinfo();
                        row.ForeColor = Color.Gray;
                        row.BackColor = Color.WhiteSmoke;

             

                        sidinfo = FCOMMON.DBM.GetPartBuyInfo(project, v_sid);

                        fpSpread1.ActiveSheet.Cells[i, col_buyrq].Value = sidinfo.Request;
                        fpSpread1.ActiveSheet.Cells[i, col_buypr].Value = sidinfo.PR;
                        fpSpread1.ActiveSheet.Cells[i, col_buypo].Value = sidinfo.PO;
                        fpSpread1.ActiveSheet.Cells[i, col_byuin].Value = sidinfo.Received;

                        continue;
                    }
                    else
                    {
                        sidinfo = FCOMMON.DBM.GetPartBuyInfo(project, v_sid);
                        sidlist.Add(v_sid);
                        fpSpread1.ActiveSheet.Cells[i, col_buyrq].Value = sidinfo.Request;
                        fpSpread1.ActiveSheet.Cells[i, col_buypr].Value = sidinfo.PR;
                        fpSpread1.ActiveSheet.Cells[i, col_buypo].Value = sidinfo.PO;
                        fpSpread1.ActiveSheet.Cells[i, col_byuin].Value = sidinfo.Received;
                    }

                }
                else if (v_sid.StartsWith("신규"))
                {
                    sidinfo = new FCOMMON.DBM.buyinfo();
                    row.ForeColor = Color.Gray;
                    row.BackColor = Color.WhiteSmoke;
                    continue;
                }
                else
                {
                    sidinfo = new FCOMMON.DBM.buyinfo();
                    row.ForeColor = Color.Black;
                    row.BackColor = Color.White;
                    continue;
                }

                //fpSpread1.ActiveSheet.Cells[i, col_buyrq].Value = sidinfo.Total_Request;
                //fpSpread1.ActiveSheet.Cells[i, col_byuin].Value = sidinfo.Total_Ipko;


                TotInfo.PO += sidinfo.PO;
                TotInfo.PR += sidinfo.PR;
                TotInfo.Received += sidinfo.Received;
                TotInfo.Request += sidinfo.Request;

                전체건수 += 1;

                int qty_in = sidinfo.Total_Ipko;// 0;
                int qty_buy = sidinfo.Total_Request;// ;

                if (sidinfo.Total_Request < 1) //비구매건
                {
                    비구매 += 1;
                    row.ForeColor = Color.Black;
                    row.BackColor = Color.White;
                }
                else
                {
                    //if(v_sid == "108963609")
                    //{

                    //}
                    //여기서부터는 무조건 구매대상이다
                    //입고수량이 구매수량을 넘어가면 완료이다
                    if (sidinfo.Received >= sidinfo.Total_Request)
                    {
                        구매완료 += 1;
                        row.ForeColor = Color.Black;
                        row.BackColor = Color.LimeGreen;
                    }
                    else if (sidinfo.PO > 0)  //구매진행중이다
                    {
                        구매진행 += 1;
                        row.ForeColor = Color.White;
                        row.BackColor = Color.DarkMagenta;
                    }
                    else if (sidinfo.PR > 0) //승인요청
                    {
                        PO대기 += 1;
                        row.ForeColor = Color.Black;
                        row.BackColor = Color.Gold;
                    }
                    else
                    {
                        if (sidinfo.Request > 0)
                        {
                            구매요청 += 1;
                            row.ForeColor = Color.Black;
                            row.BackColor = Color.LightSkyBlue;
                        }
                        else
                        {
                            비구매 += 1;
                            row.ForeColor = Color.Black;
                            row.BackColor = Color.White;
                        }
                    }
                    //if (bPR == false)
                    //{

                    //    {
                    //        구매요청 += 1;
                    //        row.ForeColor = Color.Black;

                    //        if (db_sid == null || db_sid.ToString().isEmpty()) row.BackColor = Color.CornflowerBlue;
                    //        else row.BackColor = Color.LightSkyBlue;


                    //        //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;
                    //    }
                    //}
                }
                //this.fpSpread1.ActiveSheet.Cells[i, col_buyqty].BackColor = Color.FromArgb(230, 230, 230);
                //this.fpSpread1.ActiveSheet.Cells[i, col_inqty].BackColor = Color.FromArgb(230, 230, 230);
                //this.fpSpread1.ActiveSheet.Cells[i, col_indate].BackColor = Color.FromArgb(230, 230, 230);
                //this.fpSpread1.ActiveSheet.Cells[i, col_inuser].BackColor = Color.FromArgb(230, 230, 230);
                //this.fpSpread1.ActiveSheet.Cells[i, col_inbigo].BackColor = Color.FromArgb(230, 230, 230);
            }

            //프로그레시브입력

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

            var 구매율 = (구매완료 + 비구매) / (전체건수 * 1.0);
            구매율 = 구매완료 / ((전체건수 - 비구매) * 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;
            }

            var drli = this.dsPRJ.Projects.FirstOrDefault();
            if(drli != null)
            {
                var cramount = drli.cramount;
                var jan1 = cramount - s1;
                var jan2 = cramount - s2;
                lbSum.Text = $"1대 금액 {s1:N0}(남음:{jan1:N0}원) / N대 금액 {s2:N0}(남음:{jan2:N0}원)";
            }
            else
            {
                lbSum.Text = $"1대 금액 {s1:N0}원 / N대 금액 {s2:N0}원";
            }

            
        }



        void Save()
        {
            this.Validate();
            this.bs.EndEdit();
            this.bsPart.EndEdit();
            this.Validate();
            this.bs.EndEdit();
            this.bsPart.EndEdit();
            this.Focus();

            //저장전 더미데이터 백업
            var backdup = new dsPRJ.ProjectsPartDataTable();
            backdup.Merge(dsPRJ.ProjectsPart);
            backdup.RejectChanges();
            try
            {
                var fn = System.IO.Path.Combine(util.CurrentPath, "Backup", "PartList", this.ProjectIndex.ToString("00000") + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xml");
                var fi = new System.IO.FileInfo(fn);
                if (fi.Directory.Exists == false) fi.Directory.Create();
                backdup.WriteXml(fi.FullName);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


            //모든데이터의 공백을 제거(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 (tbOrderNo.Text.Trim() != "") fn += "_" + tbOrderNo.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; //재활성 251229 윤중현

                                    //제조사추가  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 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;
            }
            if (string.IsNullOrEmpty(tbOrderNo.Text))
            {
                FCOMMON.Util.MsgE("SCR/CF 값이 없습니다. CR구매시 해당 값은 필수 입니다\n프로젝트 정보에서 값을 입력 후 다시 시도하세요");
                return;
            }

            var selcnt = this.fpSpread1.ActiveSheet.SelectionCount;
            var sels = this.fpSpread1.ActiveSheet.GetSelections();
            //var sel2 = this.fpSpread1.ActiveSheet.GetSelection(0);

            var idxColumn = this.fpSpread1.ActiveSheet.Columns["idx"].Index;
            List<int> idxlist = new List<int>();
            foreach (var sel in sels)
            {
                for (int r = sel.Row; r < (sel.Row + sel.RowCount); r++)
                {
                    var idx = (int)this.fpSpread1.ActiveSheet.Cells[r, idxColumn].Value;
                    if (idx < 0) continue;
                    if (idxlist.Contains(idx) == false) idxlist.Add(idx);
                }
            }

            if (idxlist.Any() == false)
            {
                FCOMMON.Util.MsgE("선택된 대상이 없습니다");
                return;
            }

            var f = new fProjectPartToPurchaseCR(ProjectIndex, idxlist, true);
            f.ShowDialog();
            //this.fpSpread1.ActiveSheet.ClearSelection();
        }

        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 button1_Click(object sender, EventArgs e)
        {
            RefreshData();
        }


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

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {

        }


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

        void showfolder()
        {
            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 = "/" + dr.idx.ToString();

            if (tbPath.StartsWith("\\") == false)
            {
                if (tbPath.StartsWith("/")) tbPath = tbPath.Replace("/", "\\");
                else tbPath = "\\" + tbPath;
            }
            //\\10.131.32.29\Data
            var datapath = FCOMMON.DBM.getCodeSvalue("55", "01");
            var serverpath = System.IO.Path.Combine(datapath, "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)
            {
                try
                {
                    System.IO.Directory.CreateDirectory(path);

                    string[] subdir = new string[] { "Source", "Document", "Draw", "Estimate" };
                    foreach (var dir in subdir)
                        System.IO.Directory.CreateDirectory(path + "\\" + dir);

                }
                catch (Exception eX)
                {
                    FCOMMON.Util.MsgE("프로젝트 저장소 생성실패\n" + eX.Message);
                    return;
                }
            }

            FCOMMON.Util.RunExplorer(path);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            showfolder();
        }

        private void 전체선택ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            fpSpread1.ActiveSheet.ClearSelection();
            //fpSpread1.ActiveSheet.SelectionUnit = FarPoint.Win.Spread.Model.SelectionUnit.Cell;
            fpSpread1.ActiveSheet.AddSelection(0, 0, fpSpread1.ActiveSheet.RowCount, 1);
            var list = fpSpread1.ActiveSheet.GetSelections();
            fpSpread1.ActiveSheet.SetActiveCell(0, 0, false);
            fpSpread1.ActiveSheet.SetActiveCell(1, 1, false);
            fpSpread1.ActiveSheet.SetActiveCell(2, 2, false);
            var selected = fpSpread1.ActiveSheet.GetSelections();






        }

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

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

        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            var chg = this.dsPRJ.ProjectsPart.GetChanges();
            if (chg != null)
            {
                FCOMMON.Util.MsgE("변경된 자료가 있습니다. \n 해당 자료를 먼저 저장하세요");
                return;
            }
            //if (string.IsNullOrEmpty(tbOrderNo.Text))
            //{
            //    FCOMMON.Util.MsgE("SCR/CF 값이 없습니다. CR구매시 해당 값은 필수 입니다\n프로젝트 정보에서 값을 입력 후 다시 시도하세요");
            //    return;
            //}

            var selcnt = this.fpSpread1.ActiveSheet.SelectionCount;
            var sels = this.fpSpread1.ActiveSheet.GetSelections();
            //var sel2 = this.fpSpread1.ActiveSheet.GetSelection(0);

            var idxColumn = this.fpSpread1.ActiveSheet.Columns["idx"].Index;
            List<int> idxlist = new List<int>();
            foreach (var sel in sels)
            {
                for (int r = sel.Row; r < (sel.Row + sel.RowCount); r++)
                {
                    var idx = (int)this.fpSpread1.ActiveSheet.Cells[r, idxColumn].Value;
                    if (idx < 0) continue;
                    if (idxlist.Contains(idx) == false) idxlist.Add(idx);
                }
            }

            if (idxlist.Any() == false)
            {
                FCOMMON.Util.MsgE("선택된 대상이 없습니다");
                return;
            }

            var f = new fProjectPartToPurchaseCR(ProjectIndex, idxlist, false);
            f.ShowDialog();
            //this.fpSpread1.ActiveSheet.ClearSelection();
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            using (var f = new Project.finputcurrency())
            {
                if (f.ShowDialog() == DialogResult.OK)
                {
                    var cur = (decimal)f.Value;
                    var dlg = FCOMMON.Util.MsgQ("usd 단가가 입력된 자료의 단가를 자동 계산할까요?");
                    if (dlg != DialogResult.Yes) return;

                    foreach (var dr in this.dsPRJ.ProjectsPart)
                    {
                        if (dr.RowState == DataRowState.Detached || dr.RowState == DataRowState.Deleted) continue;
                        if (dr.IspriceDNull()) continue;
                        if (dr.priceD == 0) continue;
                        dr.price = Math.Round(dr.priceD * cur, 0);
                        if (dr.IsqtyNull() == false)
                            dr.amt = dr.qty * dr.price;
                        if (dr.IsqtynNull() == false)
                            dr.amtn = dr.qtyn * dr.price;
                        dr.EndEdit();
                    }

                    this.Validate();
                }
            }
        }



        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void tbOrderNo_TextChanged(object sender, EventArgs e)
        {

        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void tbIdx_TextChanged(object sender, EventArgs e)
        {

        }

        private void nameTextBox_Click(object sender, EventArgs e)
        {
            var dr = this.dsPRJ.Projects.FirstOrDefault();
            if (dr == null)
            {
                AR.UTIL.MsgE("프로젝트정보를 찾을 수 없습니다");
                return;
            }
            using (var f = new fProjectData(dr))
                if (f.ShowDialog() == DialogResult.OK)
                {
                    dr.EndEdit();
                    var ta = new dsPRJTableAdapters.ProjectsTableAdapter();
                    var cnt = this.ta.Update(dr);//.UpdateAll(this.dsMSSQL.Projects);t
                    this.Validate();
                    
                }



        }
    }
}
