using FCOMMON;
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 FCM0000
{
    public partial class fInventoryUser : fBase
    {
        public fInventoryUser()
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            this.FormClosed += __Closed;
            this.dsMSSQL.InventoryUser.TableNewRow += Inventory_TableNewRow;

            var invtypeList = new FCOMMON.keyValuedataTable();
            invtypeList.Add("I1", "입고");
            invtypeList.Add("I2", "입고(대여)");
            invtypeList.Add("O1", "출고");
            invtypeList.Add("O2", "출고(대여)");
            invtypeList.Add("ET", "기타");
            dvc_iffnvtype.DataSource = invtypeList.DataTable;
            dvc_iffnvtype.ValueMember = "key";
            dvc_iffnvtype.DisplayMember = "Value";
            this.dtSD.KeyDown += dtSD_KeyDown;
            this.dtED.KeyDown += dtSD_KeyDown;
        }

        void dtSD_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ToolStripTextBox tb = sender as ToolStripTextBox;
                var vale = tb.Text.Trim();
                var datestring = string.Empty;
                if (FCOMMON.Util.MakeDateString(vale, out datestring))
                {
                    tb.Text = datestring;
                    if (e.KeyCode == Keys.Enter)
                        SendKeys.Send("{TAB}");
                }
                else
                {
                    FCOMMON.Util.MsgE("날짜형식으로 입력하세요.\n\n18-01-01");
                    tb.SelectAll();
                    tb.Focus();
                }
            }

        }

        void __Closed(object sender, FormClosedEventArgs e)
        {
            var form = this as Form;
            FCOMMON.Util.SetFormStatus(ref form, this.Name, false);
        }

        private void __Load(object sender, EventArgs e)
        {
            // TODO: 이 코드는 데이터를 'dsMSSQL.InventoryUser' 테이블에 로드합니다. 필요한 경우 이 코드를 이동하거나 제거할 수 있습니다.
            EnsureVisibleAndUsableSize();
            var form = this as Form;
            FCOMMON.Util.SetFormStatus(ref form, this.Name, true);
            this.Show();            
            Application.DoEvents();

            //사용자이름  181030
            this.tbName.Text = FCOMMON.info.Login.nameK;

            //마지막 자료를 가져온날을 찾는다.
            var dateList = FCOMMON.DBM.getDateList("InventoryUser", "uid='" + FCOMMON.info.Login.no + "'");
            dtED.Text = DateTime.Now.ToString("yyyy-MM-dd");

            if (dateList.Count > 0) dtSD.Text = dateList[dateList.Count - 1];
            else dtSD.Text = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");

            btSearch.PerformClick();

        }
        private void btSearch_Click(object sender, EventArgs e)
        {
            try
            {
                string sd = dtSD.Text;
                string ed = dtED.Text;
                string name = "%";
                if (tbName.Text != "") name = tbName.Text.Trim();
                this.ta.FillByName(this.dsMSSQL.InventoryUser, sd, ed, name);
                this.dsMSSQL.InventoryUser.AcceptChanges();
                dv1.AutoResizeColumns();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }

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

            var dlg = FCOMMON.Util.MsgQ("변경된 사항을 저장 하시겠습니까?");
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            try
            {
                this.tam.UpdateAll(this.dsMSSQL);
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }


        }
        void Inventory_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {

            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["uid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["pdate"] = DateTime.Now.ToString("yyyy-MM-dd");
            e.Row["dr_qty"] = 0;
            e.Row["dr_amt"] = 0;
            e.Row["invtype"] = "I1";
        }

        private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string inputstr = tbFind.Text.Trim();
                if (inputstr == "")
                {
                    bs.Filter = "";
                    tbFind.BackColor = Color.White;
                }
                else
                {
                    string[] collist = new string[] { "projectName", "itemName", "memo", "serial" };
                    System.Text.StringBuilder filter = new StringBuilder();
                    foreach (var col in collist)
                    {
                        if (filter.Length > 0) filter.Append(" or ");
                        filter.Append(col + " like '%" + inputstr + "%'");
                    }
                    try
                    {
                        bs.Filter = filter.ToString();
                        tbFind.BackColor = Color.Lime;
                        tbFind.SelectAll();
                        tbFind.Focus();
                    }
                    catch 
                    {
                        tbFind.BackColor = Color.Red;
                    }
                }
            }
        }

        private void autoColumnsSizeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dv1.AutoResizeColumns();
        }

        private void dv1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
            var col = dv1.Columns[e.ColumnIndex];
            switch (col.DataPropertyName)
            {
                case "itemName":
                    var valuen = dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                    if (valuen != null)
                    {
                        string inputtext = valuen.ToString().Trim();
                        if (inputtext.isEmpty())
                        {
                            dv1.Rows[e.RowIndex].Cells["dvc_itemName"].Value = inputtext;
                        }
                        else
                        {
                            //검색을 실행해서 보여준다.
                            var SearchDT = taItem.GetSearch("%" + inputtext + "%", FCOMMON.info.Login.gcode);
                            if (SearchDT == null || SearchDT.Rows.Count < 1)
                            {
                                FCOMMON.Util.MsgE("검색 결과가 없습니다.");
                                return;
                            }
                            else
                            {
                                //검색된 결과를 표시해서 보여준다.
                                var f = new fLovItem("%" + inputtext + "%");
                                if(f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                                {
                                    dv1.Rows[e.RowIndex].Cells["dvc_item"].Value = f.item;
                                    dv1.Rows[e.RowIndex].Cells["dvc_itemName"].Value = f.itemName;
                                }
                            }
                        }
                    }
                    break;
                case "item":
                    var value = dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                    if (value != null)
                    {
                        int idx = (int)value;
                        if (idx != -1)
                        {
                            var item = this.taItem.GetbyIDX(idx);
                            if (item.Count == 1)
                            {
                                //1개만 찾았다면 그것을 사용한다.
                                var itemnameValue = item[0]["name"];
                                if (itemnameValue != null)
                                    dv1.Rows[e.RowIndex].Cells["dvc_itemName"].Value = itemnameValue.ToString();
                            }
                            else
                            {
                                FCOMMON.Util.MsgE("해당 아이템이 존재하지 않습니다.");
                                dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = DBNull.Value;
                            }
                        }
                    }
                    break;
                case "project":
                    var valuep = dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                    if (valuep != null)
                    {
                        int idx = (int)valuep;
                        if (idx != -1)
                        {
                            var item = this.taPrj.GetData(idx);
                            if (item.Count == 1)
                            {
                                //1개만 찾았다면 그것을 사용한다.
                                var itemnameValue = item[0]["name"];
                                if (itemnameValue != null)
                                    dv1.Rows[e.RowIndex].Cells["dvc_projectName"].Value = itemnameValue.ToString();
                            }
                            else
                            {
                                FCOMMON.Util.MsgE("해당 프로젝트가 존재하지 않습니다.");
                                dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = DBNull.Value;
                            }
                        }
                    }
                    break;
                case "projectName":
                     var valuepn = dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                     if (valuepn != null)
                    {
                        string inputtext = valuepn.ToString().Trim();
                        if (inputtext.isEmpty())
                        {
                            dv1.Rows[e.RowIndex].Cells["dvc_projectname"].Value = inputtext;
                        }
                        else
                        {
                            //검색을 실행해서 보여준다.
                            var SearchDT = this.taPrj.GetSearch("%" + inputtext + "%",FCOMMON.info.Login.gcode,"%");
                            if (SearchDT == null || SearchDT.Rows.Count < 1)
                            {
                                FCOMMON.Util.MsgE("검색 결과가 없습니다.");
                                return;
                            }
                            else
                            {
                                //검색된 결과를 표시해서 보여준다.
                                var f = new fLovProject("%" + inputtext + "%","%");
                                if(f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                                {
                                    dv1.Rows[e.RowIndex].Cells["dvc_project"].Value = f.val_Index;
                                    dv1.Rows[e.RowIndex].Cells["dvc_projectname"].Value = f.val_Title;
                                }
                            }
                        }
                    }
                    break;
            }
        }

        private void toolStripLabel1_Click(object sender, EventArgs e)
        {
            //시작일(inventory 에 uid 가 내것인 데이터)
            var dataList = FCOMMON.DBM.getDateList("inventoryUser", "uid='" + FCOMMON.info.Login.no + "'", true);
            var f = new FCOMMON.fLovDateList(dataList);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                dtSD.Text = f.selectedDate;
            }
        }

        private void toolStripLabel2_Click(object sender, EventArgs e)
        {
            var dataList = FCOMMON.DBM.getDateList("inventoryUser", "uid='" + FCOMMON.info.Login.no + "'", true);
            var f = new FCOMMON.fLovDateList(dataList);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                dtED.Text = f.selectedDate;
                btSearch.PerformClick();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            var f = new Inventory.RepInvStockUser(this.tbName.Text.Trim());
            f.MdiParent = this.MdiParent;
            f.Show();
        }

        private void toolStripLabel3_Click(object sender, EventArgs e)
        {
            tbFind.Text = string.Empty;
            btFind.PerformClick();
        }


    }
}
