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

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

        public fPurchase()
        {
            InitializeComponent();
            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.dsPurchase.Purchase.TableNewRow += Purchase_TableNewRow;
            this.FormClosed += __Closed;
            dtSD.KeyDown += dtSD_KeyDown;
            dtED.KeyDown += dtSD_KeyDown;
            //this.dv1.CellFormatting += dv1_CellFormatting;
        }

        void dtSD_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;
            var tb = sender as ToolStripTextBox;
            var input = tb.Text.Trim();
            if (input == "") tb.Text = DateTime.Now.ToShortDateString();
            else
            {
                string dt = string.Empty;
                if (!util.MakeDateString(input, out dt))
                {
                    FCOMMON.Util.MsgE("입력값이 올바르지 않습니다.");
                    tb.SelectAll();
                    tb.Focus();
                    return;
                }
                else
                {
                    tb.Text = dt;
                }
            }
            if (tb == dtSD)
            {
                dtED.Focus();
                dtED.SelectAll();
            }
            else
            {
                btSearch.PerformClick();
                tb.SelectAll();
            }
        }

        void __Closed(object sender, FormClosedEventArgs e)
        {

        }

        void Purchase_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            e.Row["pdate"] = DateTime.Now.ToShortDateString();
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["pumunit"] = "EA";
            e.Row["state"] = "---";
            e.Row["pumqty"] = 1;
            e.Row["pumprice"] = 0;
            e.Row["pumamt"] = 0;
            e.Row["request"] = FCOMMON.info.Login.nameK;
            e.Row["receive"] = "";// FCOMMON.info.Login.nameK;
        }

        private void __Load(object sender, EventArgs e)
        {
            this.cmDate.SelectedIndex = 0;
            this.tbRequest.Text = string.Empty; //양진원 FCOMMON.info.Login.nameK;
            this.cmbSort.SelectedIndex = 0;
            this.dtSD.Text = DateTime.Now.AddDays(-30).ToShortDateString();
            this.dtED.Text = DateTime.Now.AddDays(10).ToShortDateString();

            //state list
            var stList = FCOMMON.DBM.getCodeList("04");
            this.cmbState.Items.Clear();
            cmbState.Items.Add("-- 전체 --");
            foreach (var item in stList)
                cmbState.Items.Add(item.Value);
            cmbState.Items.Add("<=Received");
            this.cmbState.SelectedIndex = 0;    //all기본 - 양진원
            //this.cmbCr.SelectedIndex = 1;

            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.purchase));
            if (curLevel >= 5)
            {
                btSave.Visible = true;
            }
            else
            {
                btSave.Visible = false;
                btViewDel.Visible = false;
                fpSpread1.EditMode = false;
                fpSpread1.Sheets[0].SelectionUnit = FarPoint.Win.Spread.Model.SelectionUnit.Row;
                fpSpread1.EditModePermanent = false;
                fpSpread1.EditModeReplace = false;

                foreach (FarPoint.Win.Spread.Column col in fpSpread1.ActiveSheet.Columns)
                    col.Locked = true;
            }

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

            refreshData();

            //열표시여부를 설정
            var adv = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.purchase_adv);
            if (adv == false)
            {
                var hidecols = new string[] { "receivename", "receive", "asset", "dept", "manuproc", "process", "cr", "orderno", "manuproc", "project", "projectidx", "edate", "po" };
                foreach (FarPoint.Win.Spread.Column col in fpSpread1_Sheet1.Columns)
                {
                    if (hidecols.Contains(col.DataField.ToLower())) col.Visible = false;
                }
            }
        }


        private void refreshData()
        {

            try
            {
                string state = "%";
                if (cmbState.SelectedIndex > 0) state = cmbState.Text.Split(',')[0];

                string request = "%";
                if (tbRequest.Text.Trim() != "")
                    request = "%" + tbRequest.Text.Trim() + "%";// tbRequest.Text.Substring(1, tbRequest.Text.IndexOf("]") - 1);


                string dateField = "pdate";
                if (cmDate.SelectedIndex == 1) dateField = "indate";
                else if (cmDate.SelectedIndex == 2) dateField = "expdate";
                

                System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                cmd.CommandText = " select *,dbo.getusername(request) as requestName,dbo.getusername(receive) as receiveName" +
                                   " from purchase " +
                                   " where gcode='" + FCOMMON.info.Login.gcode + "' and  isnull(" + dateField + ",'') between @sd and @ed ";



                if (btViewDel.Checked == false)
                    cmd.CommandText += " and isnull(isdel,0) = 0";


                if (tbRequest.Text.Trim() != "")
                {
                    cmd.CommandText += " and (isnull(dbo.getusername(request),'') like @req or isnull(dbo.getusername(receive),'') like @req)";
                }


                if (cmbState.SelectedIndex != 0)
                {
                    if (cmbState.Text.ToUpper() == "<=RECEIVED")
                    {
                        cmd.CommandText += " and isnull([state],'') in ('','---','Approving','PR','PO')";
                    }
                    else
                    {
                        cmd.CommandText += " and isnull([state],'') like @st";
                    }
                }
                // else cmd.CommandText += " and (state < '04' or state > '07')";


                if (cmbSort.SelectedIndex == 1) dateField = "edate";
                else if (cmbSort.SelectedIndex == 2) dateField = "sc";

                cmd.CommandText += " ORDER BY " + dateField + " DESC, idx DESC";

                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@sd", dtSD.Text));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ed", dtED.Text));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@req", request));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@st", state));
                cmd.Connection = this.ta.Connection;
                da.SelectCommand = cmd;

                //read adata
                this.dsPurchase.Purchase.Clear();
                da.Fill(this.dsPurchase.Purchase);
                this.dsPurchase.AcceptChanges();
                showSummary();
                FCOMMON.Util.FPColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

            FormattingData();
        }
        void FormattingData()
        {
            //삭제컬럼인덱스
            this.fpSpread1.SuspendLayout();
            var delindex = this.fpSpread1.ActiveSheet.Columns["isdel"].Index;
            var statindex = this.fpSpread1.ActiveSheet.Columns["state"].Index;
            var crcfindex = this.fpSpread1.ActiveSheet.Columns["crcf"].Index;
            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var state = this.fpSpread1.ActiveSheet.GetValue(i, statindex);
                string stateStr = string.Empty;
                if (state != null) stateStr = state.ToString();

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

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


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


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

                }

            }
            this.fpSpread1.ResumeLayout();
        }

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


        }
        void showSummary()
        {
            decimal sum = 0;
            var list = this.dsPurchase.Purchase.Select(this.bs.Filter, "") as dsPurchase.PurchaseRow[];
            sum = list.Sum(t => t.pumamt);
            //foreach (dsPurchase.PurchaseRow dr in this.dsPurchase.Purchase.Rows)
            //if (!dr.IspumamtNull()) sum += dr.pumamt;
            lbSum.Text = sum.ToString("N0");
        }

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

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            func_add();
        }

        private void tbRequest_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btSearch.PerformClick();
        }

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


        private void lbEnd_Click(object sender, EventArgs e)
        {
            //end date
            var list = FCOMMON.DBM.getGroupList("pdate", "purchase", "pdate >= '" + dtSD.Text + "'", true);
            FCM0000.fLovOneItem f = new FCM0000.fLovOneItem(list);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                dtED.Text = f.Title;
                btSearch.PerformClick();
            }
        }

        private void toolStripLabel3_Click(object sender, EventArgs e)
        {
            //사용자목록처리
            if (tbRequest.Text.Trim() == "")
            {
                tbRequest.Text = FCOMMON.info.Login.nameK;
            }
            else
            {
                tbRequest.Text = string.Empty;
            }

            refreshData();
        }

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

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            func_delete();
        }
        void func_add()
        {
            var newdr = this.dsPurchase.Purchase.NewPurchaseRow();

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

        repeat:

            bool repeat = false;
            DialogResult dlg;
            if (getAdminInput == false)
            {
                repeat = false;
                var f = new fPurchase_AddS(newdr);
                dlg = f.ShowDialog();
            }
            else
            {
                var f = new fPurchase_Add(newdr);
                dlg = f.ShowDialog();
                repeat = f.repeatAdd;
            }

            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                //존재하지 않는 sid 는 추가를 해준다.
                var newidx = AddItemInfoGetIndex(newdr);
                if (newidx != -1)
                {
                    newdr.pumidx = newidx;
                    newdr.EndEdit();
                }

                this.dsPurchase.Purchase.AddPurchaseRow(newdr);

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

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


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

            

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

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

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

            if (curLevel < 5)
            {
                var dlg = FCOMMON.Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }

            bs.RemoveCurrent();

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

        private int AddItemInfoGetIndex(dsPurchase.PurchaseRow newdr)
        {
            //이 시드가 아이템목록에 없다면 추가 하고 idx를 조회한 후 설정해준다.
            if (newdr.sid == "신규") return -1;
            int retval = -1;
            var sid = newdr.sid;
            var iteminfo = FCOMMON.DBM.getItemInfo(sid);
            if (iteminfo.idx < 0)
            {
                FCOMMON.DBM.sItemInfo newitem = new FCOMMON.DBM.sItemInfo();
                newitem.sid = newdr.sid;
                newitem.name = newdr.pumname;
                newitem.price = newdr.pumprice.ToString();
                newitem.model = newdr.pumscale;
                newitem.unit = newdr.pumunit;
                newitem.scale = 1f;
                newitem.supply = newdr.supply;
                newitem.supplyidx = newdr.supplyidx;
                retval = FCOMMON.DBM.addItemInfo(newitem);
            }
            return retval;
        }

        private void copyDataToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void btFind_Click(object sender, EventArgs e)
        {
            var search = tbFind.Text.Trim();
            search = search.Replace("*", "x");
            if (tbFind.Text != search) tbFind.Text = search;
            try
            {
                if (search.isEmpty())
                {
                    this.bs.Filter = "";
                    tbFind.BackColor = Color.White;
                }
                else
                {
                    search = search.Replace("'", "''");
                    string filter = "supply like ? or sid like ? or process like ? or orderno like ? or sc like ? or pumname like ? or pumscale like ? or project like ?";
                    filter = filter.Replace("?", "'%" + search + "%'");
                    this.bs.Filter = filter;
                    tbFind.BackColor = Color.Lime;
                }
                tbFind.SelectAll();
                tbFind.Focus();
                showSummary();
            }
            catch (Exception ex)
            {
                this.tbFind.BackColor = Color.Tomato;
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

        private void tbFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) btFind.PerformClick();
        }

        private void editDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Func_Edit();
        }
        void Func_Edit()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var newdr = drv.Row as dsPurchase.PurchaseRow;

            bool repeat = false;
            DialogResult dlg;
            if (getAdminInput == false)
            {
                repeat = false;
                var f = new fPurchase_AddS(newdr);
                dlg = f.ShowDialog();
            }
            else
            {
                var f = new fPurchase_Add(newdr);
                dlg = f.ShowDialog();
                repeat = f.repeatAdd;
            }

            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                //존재하지 않는 sid 는 추가를 해준다.
                var newidx = AddItemInfoGetIndex(newdr);
                if (newidx != -1)
                {
                    newdr.pumidx = newidx;
                    newdr.EndEdit();
                }
                if (newdr.RowState != DataRowState.Unchanged)
                {
                    this.ta.Update(newdr);
                    newdr.AcceptChanges();
                }
            }
            else newdr.RejectChanges();

        }

        private void autoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FCOMMON.Util.FPColSizeAuto(this.fpSpread1);
            //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)
        {
            FCOMMON.Util.FPColsizeSave(this.fpSpread1, fn_fpcolsize);
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FCOMMON.Util.FPColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Func_Edit();
        }


        void dv1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            //if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
            //var state = this.dv1.Rows[e.RowIndex].Cells["dvc_state"].Value.ToString();
            //switch (state)
            //{
            //    case "00":  //입력대기(미확인)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightGray;
            //        break;
            //    case "01":  //파트장 승인 기다림
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.DarkBlue;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        break;
            //    case "03":  //PO (협력업체 전달)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.DarkMagenta;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        break;
            //    case "04":  //자재 수령
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Green;
            //        break;
            //    case "05": //canceld (취소)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightGray;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Red;
            //        break;
            //    case "06":  //cancel (취소됨)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.HotPink;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
            //        break;
            //    case "08":  //문의
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Green;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.White;
            //        break;
            //    default:
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
            //        break;
            //}
        }

        private void updateSCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dlg = FCOMMON.Util.MsgQ("#SC가 없는 자료에 한하여 일괄 기록을 실행 합니다.");
            if (dlg == System.Windows.Forms.DialogResult.Yes)
            {

            }
        }

        private void exportDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            sd.FileName = "nrplist.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);
                FCOMMON.Util.MsgI("다음 파일이 생성 되었습니다.\n\n" + sd.FileName);
            }

        }

        private void 내가등록한자료ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cmDate.SelectedIndex = 0;
            dtSD.Text = DateTime.Now.AddMonths(-1).ToShortDateString();
            dtED.Text = DateTime.Now.ToShortDateString();
            cmbState.SelectedIndex = 0;
            tbRequest.Text = FCOMMON.info.Login.nameK;
            refreshData();
        }

        private void 금일입고품목ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cmDate.SelectedIndex = 1; //입고일
            dtSD.Text = DateTime.Now.ToShortDateString();   //당일
            dtED.Text = DateTime.Now.ToShortDateString();
            tbRequest.Text = string.Empty;
            refreshData();
        }

        private void 이번달자료ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dtSD.Text = DateTime.Now.ToString("yyyy-MM") + "-01";
            dtED.Text = DateTime.Now.ToShortDateString();
            tbRequest.Text = string.Empty;
            refreshData();
        }

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


        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //선택된 줄의 데이터를 생성하낟.
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPurchase.PurchaseRow;
            string buffer = string.Format("{0}_{1}_{2}_{3}_{4}", dr.pumname.Replace("_", "-"), dr.pumscale.Replace("_", "-"), dr.dept.Replace("_", "-"), dr.manuproc.Replace("_", "-"), dr.asset.Replace("_", "-"));
            Clipboard.SetText(buffer);
            //FCOMMON.Util.MsgI("다음 데이터가 클립보드에 저장됨\n\n" + buffer);  190131
        }

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

            //현재 데이터를 입력하여 신규 추가를 한다.
            var newdr = this.dsPurchase.Purchase.NewPurchaseRow();
            FCOMMON.Util.CopyData((System.Data.DataRow)dr, (System.Data.DataRow)newdr);
            newdr.pdate = DateTime.Now.ToShortDateString();
            newdr.wdate = DateTime.Now;
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.state = "---";
            newdr.request = FCOMMON.info.Login.no;
            newdr.receive = "";// FCOMMON.info.Login.nameK;
            newdr.sc = string.Empty;
            newdr.po = string.Empty;
            newdr.indate = string.Empty;
            newdr.edate = string.Empty;
            newdr.idx = -1;
            newdr.EndEdit();

        repeat:

            bool repeat = false;
            DialogResult dlg;
            if (getAdminInput == false)
            {
                var f = new fPurchase_AddS(newdr);
                dlg = f.ShowDialog();
            }
            else
            {
                var f = new fPurchase_Add(newdr);
                dlg = f.ShowDialog();
                repeat = f.repeatAdd;
            }

            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                //존재하지 않는 sid 는 추가를 해준다.
                var newidx = AddItemInfoGetIndex(newdr);
                if (newidx != -1)
                {
                    newdr.pumidx = newidx;
                    newdr.EndEdit();
                }

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

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

            }
            else newdr.Delete();
        }


        private void toolStripButton1_Click_2(object sender, EventArgs e)
        {
            func_copy();
        }

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

        private void makeRepeatToolStripMenuItem_Click(object sender, EventArgs e)
        {
            func_copy();
        }

        private void 편집ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Func_Edit();
        }

        private void 삭제ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            func_delete();
        }

        private void 추가ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            func_add();
        }

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

        private void sC검색ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //sc
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var newdr = drv.Row as dsPurchase.PurchaseRow;
            if(newdr.sc.Trim() == "")
            {
                FCOMMON.Util.MsgE("SC값이 없습니다");
                return;
            }
            tbFind.Text = newdr.sc;
            btFind.PerformClick();
        }

        private void cRCF검색ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //crcf
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var newdr = drv.Row as dsPurchase.PurchaseRow;
            if (newdr.orderno.Trim() == "")
            {
                FCOMMON.Util.MsgE("CR/CF값이 없습니다");
                return;
            }
            tbFind.Text = newdr.orderno;
            btFind.PerformClick();
        }

        private void toolStripLabel2_Click(object sender, EventArgs e)
        {
            if (tbFind.Text != "")
            {
                tbFind.Text = "";
                btFind.PerformClick();
            }
                
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            string path = "\\\\k4fs3201n\\ee1t$\\1. 장비기술1파트\\24_Project & Overhaul 예산 사용 실적\\구매 견적서\\" + DateTime.Now.Year.ToString("0000") + "년";
            FCOMMON.Util.RunExplorer(path);
        }

        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null)
            {
                this.label1.Text = "데이터가 선택되지 않았습니다";
                return;
            }
            var dr = drv.Row as dsPurchase.PurchaseRow;
            this.label1.Text = string.Format("{0}",dr.bigo.Replace("\r","").Replace("\n",""));
        }
    }
}
