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 fPartConfirm : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        public int qty = 0;

        string search = string.Empty;
        int idx = -1;
        public fPartConfirm(dsPRJ.ProjectsPartDataTable dt,string sortkey)
        {
            InitializeComponent();

            this.bs.DataSource = dt;
            this.bs.Sort = sortkey;
            this.bs.Filter = "isnull(qtybuy,0) < 1";

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

            this.WindowState = FormWindowState.Normal;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
                else if (e1.KeyCode == Keys.F1) btPrev.PerformClick();
                else if (e1.KeyCode == Keys.F9) btNext.PerformClick();
                else if (e1.KeyCode == Keys.F5) btConf.PerformClick();
            };
        }

        private void __Load(object sender, EventArgs e)
        {
            this.Show();
            Application.DoEvents();
            if (string.IsNullOrEmpty(tbFind.Text) == false)
                btFind.PerformClick();
        }
        void refreshData(string div)
        {
            this.taPMP.Fill(this.dsMSSQL.SPMaster, "%" + div + "%");
            dvPMP.AutoResizeColumns();
            //FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);

            tbFind.Focus();
                 //tbFind.SelectAll();
        }


        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            idx = -1;
            var drv = bsPMP.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.SPMasterRow;//.minutesRow;
            idx = dr.ID;
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            try
            {
                var cnt = this.taPMP.Update(this.dsMSSQL.SPMaster);
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

        private void 목록새로고침ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.refreshData(this.search);
        }

        //void Find()
        //{
        //    var txt = tbFind.Text.Trim();
        //    if (txt == "")
        //    {
        //        if(bs.Filter != "")
        //        {
        //            bs.Filter = "";
        //            tbFind.BackColor = Color.WhiteSmoke;
        //        }
        //        tbFind.Focus();
        //        return;
        //    }

        //    //검색어가 잇으므로 검색을 수행한다
        //    var cols = new string[] { "SIDNo","Storage","Location",
        //    "PartName","PartNo","Memo","CostCenter","Enrollee"};
        //    string filter = "";
        //    foreach(var col in cols)
        //    {
        //        if (filter != "") filter += " or ";
        //        filter += col + " like '%"+ txt.Replace("'","''") +"%' ";
        //    }
        //    try
        //    {
        //        this.bs.Filter = filter;
        //        tbFind.BackColor = Color.Lime;
        //        tbFind.SelectAll();
        //    }catch (Exception ex)
        //    {
        //        this.bs.Filter = "";
        //        tbFind.BackColor = Color.Red;
        //        FCOMMON.Util.MsgE(ex.Message);
        //    }
        //}

        private void button1_Click(object sender, EventArgs e)
        {
            refreshData(tbFind.Text.Trim());
        }

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

        private void exportListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            var fn = "pmplist";
            sd.FileName = fn + ".xls";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                dvPMP.SaveExcelXML(sd.FileName);
                //fpSpread1.SaveExcel(sd.FileName,
                //    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                //    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                //    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                //    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
            }
        }

        //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 btConf_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectsPartRow;

            var str_qty = textBox9.Text;
            if (string.IsNullOrEmpty(str_qty) || str_qty == "-1")
            {
                var result = FCOMMON.Util.MsgQ("구매 수량이 입력되지 않았습니다.\n\n자동으로 '0' 을 입력하시겠습니까?\n\n수량 '0'은 비 구매 항목으로 설정 됩니다");
                if(result == DialogResult.Yes)
                {
                    dr.qtybuy = 0;
                    if (dr.memo.IndexOf("비구매설정") == -1) dr.memo += "(비구매설정:" + DateTime.Now.ToString("MM-dd hh:mm:ss") + ")";
                    textBox9.Text = "0";                    
                }
                else
                {
                    textBox9.Focus();
                    return;
                }
            }
            
            this.Validate();
            this.bs.EndEdit();
            this.bsPMP.EndEdit();

  
            //if (dr.qtybuy == 0 && dr.bbuy==false) dr.bbuy = true; //구매수량이0인것은 자동 확정한다
            //dr.bconfirm = true;
            dr.EndEdit();

            if (bs.Count < 1)
            {
                FCOMMON.Util.MsgE("미 확정 데이터가 없습니다.\n화면이 닫힙니다.");
                this.Close();
            }
            else
            {
                textBox9.Focus();
                this.textBox9.SelectAll();//
            }
        }

        private void btNext_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();
            this.bsPMP.EndEdit();
                
               if (bs.Position < bs.Count - 1) bs.Position += 1;
            textBox9.Focus();
            this.textBox9.SelectAll();//
        }

        private void btPrev_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();
            this.bsPMP.EndEdit();

            if (bs.Position > 0) bs.Position -= 1;
            textBox9.Focus();
            this.textBox9.SelectAll();//
        }

        private void bs_CurrentChanged_1(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null)
            {
                tbFind.Text = string.Empty;
            }
            else
            {
                var dr = drv.Row as dsPRJ.ProjectsPartRow;

                if (dr.ItemSid.Length == 9) tbFind.Text = dr.ItemSid;
                else if (dr.ItemName.Length > 4) tbFind.Text = dr.ItemName.Substring(0, 4);
                else if (dr.ItemName.Length > 0) tbFind.Text = dr.ItemName;
                else tbFind.Text = string.Empty;
            }
            

            if (string.IsNullOrEmpty(tbFind.Text) == true)
            {
                dsMSSQL.SPMaster.Clear();
            }
            else btFind.PerformClick();
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            finedata(textBox4.Text);
        }
        void finedata(string key)
        {
            tbFind.Text = key;
            if (string.IsNullOrEmpty(key) == false)
                btFind.PerformClick();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            finedata(textBox3.Text);
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            finedata(textBox5.Text);
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        void aplyjago()
        {
            var drv = this.bsPMP.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.SPMasterRow;
            var qty = dr.CurrentQty;
            if (qty < 1)
            {
                FCOMMON.Util.MsgE("현 재고가 없습니다");
                return;
            }
            else
            {
                var drv2 = this.bs.Current as DataRowView;
                if (drv2 == null)
                {
                    FCOMMON.Util.MsgE("미 확장 자료를 확인할 수 없습니다");
                    return;
                }

                var dr2 = drv2.Row as dsPRJ.ProjectsPartRow;
                var jagoqty = (int)Math.Min(dr2.qtyn, qty);
                dr2.qtyjago = jagoqty.ToString();
                dr2.jago = jagoqty;
                dr2.qtybuy = dr2.qtyn - jagoqty;
                var msg = "PMP재고 사용(" + jagoqty.ToString() + ")";
                if(dr2.memo.IndexOf(msg) == -1) dr2.memo += msg;
                dr2.EndEdit();
            }
        }
        private void 재고에적용합니다ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            aplyjago();
        }

        private void dvPMP_DoubleClick(object sender, EventArgs e)
        {
            aplyjago();
        }
    }
}
