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 fInventoryJagoList : fBase
    {
        string fn_fpcolsize = "";
        public fInventoryJagoList()
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            this.FormClosed += __Closed;
            this.dtSD.KeyDown += dtSD_KeyDown;
            fn_fpcolsize = System.IO.Path.Combine(FCOMMON.Util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.tbFind.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Enter) btFind.PerformClick(); };
        }

        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)
        {
            EnsureVisibleAndUsableSize();
            var form = this as Form;
            FCOMMON.Util.SetFormStatus(ref form, this.Name, true);
            this.Show();            
            Application.DoEvents();

            updateplace();

            dtSD.Text = DateTime.Now.ToString("yyyy-MM-dd");
            RefreshData();

        }
        private void btSearch_Click(object sender, EventArgs e)
        {
            RefreshData();
        }
        void RefreshData()
        {
            try
            {
                string sd = dtSD.Text;
                var place = "%";
                if (cmbPlace.SelectedIndex > 0) place = cmbPlace.Text.Trim();
                this.ta.Fill(this.dSReport.jagosummaryPlace, FCOMMON.info.Login.gcode, sd,place);
                this.dSReport.jagosummaryPlace.AcceptChanges();
           //     FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
                arDatagridView1.AutoResizeColumns();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }
        }
     
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            findData();
        }
        void findData()
        {
            var search = tbFind.Text.Trim();
            search = search.Replace("*", "x");
            if (tbFind.Text != search) tbFind.Text = search;
            try
            {
                if (search.Trim() == "")
                {
                    this.bs.Filter = "";
                    tbFind.BackColor = Color.White;
                }
                else
                {
                    var collist = new string[] { "place", "name", "placebox","box","sid", "model", "supply" };
                    search = search.Replace("'", "''");
                    string filter = ""; // "itemna like ? or package like ? or projectname like ? or process like ? or [type] like ? or description like ?";
                    foreach (var col in collist)
                    {
                        if (filter != "") filter += " or ";
                        filter += col + " like ?";
                    }
                    filter = filter.Replace("?", "'%" + search + "%'");
                    this.bs.Filter = filter;
                    tbFind.BackColor = Color.Lime;
                }
                tbFind.SelectAll();
                tbFind.Focus();
            }
            catch (Exception ex)
            {
                this.tbFind.BackColor = Color.Tomato;
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

        private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                findData();
            }
        }

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


        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            var f = new Inventory.RepInvStock();
            f.ShowDialog();
        }

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


        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 exportListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            sd.FileName = "inventoryjagolist.xls";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                arDatagridView1.ExportData(sd.FileName);
                var dlg = FCOMMON.Util.MsgQ("다음 파일이 생성 되었습니다.\n파일을 확인할까요?\n" + sd.FileName);
                if (dlg == DialogResult.Yes) FCOMMON.Util.RunExplorer(sd.FileName);
            }
        }

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

        private void 보관소별재고확인ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSInventory.vInventoryRow;
            var f = new Inventory.fInventoryJagoPlace(dr.item,dr.itemName);
            f.ShowDialog();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            
        }

        private void 인쇄ToolStripMenuItem_Click(object sender, EventArgs e)
        {
          //  FPUtil.printsheet(this.fpSpread1, "재고현황");
        }

        private void 입고등록ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //입고
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSReport.jagosummaryPlaceRow;
          
            var taInventory = new DSInventoryTableAdapters.vInventoryTableAdapter();
            var vinventory = new DSInventory.vInventoryDataTable();
            var newdr = vinventory.NewvInventoryRow();

            newdr.item = dr.item;
            newdr.invtype = "입고";
            newdr.itemModel = dr.model;
            newdr.itemName = dr.name;
            newdr.place = dr.place;
            newdr.box = dr.box;
            newdr.sid = dr.sid;

            newdr.gcode = FCOMMON.info.Login.gcode;
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.uid = FCOMMON.info.Login.no;
            newdr.wdate = DateTime.Now;
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.cr_qty = 0;
            newdr.cr_amt = 0;
            newdr.dr_qty = 0;
            newdr.dr_amt = 0;
            //newdr.item = -1;


            var f = new finventoryAdd(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                vinventory.AddvInventoryRow(newdr);
                int cnt = taInventory.Update(newdr);
                newdr.AcceptChanges();
                if (cnt != 1)
                    FCOMMON.Util.MsgE("자료가 추가되지 않았습니다.\n\n잠시 후 다시 시도하세요");
            }
            else newdr.Delete();

            this.RefreshData();
        }

        private void 출고등록ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //입고
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSReport.jagosummaryPlaceRow;

            var taInventory = new DSInventoryTableAdapters.vInventoryTableAdapter();
            var vinventory = new DSInventory.vInventoryDataTable();
            var newdr = vinventory.NewvInventoryRow();

            newdr.item = dr.item;
            newdr.invtype = "출고";
            newdr.itemModel = dr.model;
            newdr.itemName = dr.name;
            newdr.place = dr.place;
            newdr.sid = dr.sid;
            newdr.box = dr.box;

            newdr.gcode = FCOMMON.info.Login.gcode;
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.uid = FCOMMON.info.Login.no;
            newdr.wdate = DateTime.Now;
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.cr_qty = 0;
            newdr.cr_amt = 0;
            newdr.dr_qty = 0;
            newdr.dr_amt = 0;
           // newdr.item = -1;


            var f = new finventoryAdd(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                vinventory.AddvInventoryRow(newdr);
                int cnt = taInventory.Update(newdr);
                newdr.AcceptChanges();
                if (cnt != 1)
                    FCOMMON.Util.MsgE("자료가 추가되지 않았습니다.\n\n잠시 후 다시 시도하세요");
            }
            else newdr.Delete();

            this.RefreshData();
        }

        private void 초기화ToolStripMenuItem_Click(object sender, EventArgs e)
        {
          //  FPUtil.ColsizeSave(this.fpSpread1, fn_fpcolsize);
        }
        void updateplace()
        {
            var pretex = cmbPlace.Text;
            var PlaceList = FCOMMON.DBM.GetItemStorageList();
            cmbPlace.Items.Clear();
            cmbPlace.Items.Add("--전체--");
            foreach (var item in PlaceList)
                cmbPlace.Items.Add(item);
            cmbPlace.SelectedIndex = 0;
        }
        private void toolStripLabel2_Click(object sender, EventArgs e)
        {
            updateplace();
        }
    }
}
