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 fInventory : fBase
    {
        string fn_fpcolsize = "";
        public fInventory()
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            this.FormClosed += __Closed;
            this.dSInventory.vInventory.TableNewRow += Inventory_TableNewRow;
            this.dtSD.KeyDown += dtSD_KeyDown;
            this.dtED.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(); };
            this.cmbInvType.SelectedIndex = 0;
        }

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

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

            //보관소 목록업데이트
            updateplace();
         


            //담당자목록 - 사용자목록으로 처리한다.    
            string namestr = string.Format("[{1}] {0}", FCOMMON.info.Login.nameK, FCOMMON.info.Login.no);
            if (FCOMMON.info.Login.no == "dev") namestr = "[395552] 김치균";
            this.cmbUser.Items.Clear();
            this.cmbUser.Items.Add("--전체--");
            this.cmbUser.Items.Add(namestr);
            try
            {
                var cn = FCOMMON.DBM.getCn();
                cn.Open();
                string sql = "select uid,dbo.getUserName(uid) as uname " +
                            " from Inventory" +
                            " where gcode='{1}' and uid <> '{0}' and isnull(uid,'') <> ''" +
                            " group by uid " +
                            " order by uname";
                sql = string.Format(sql, FCOMMON.info.Login.no,FCOMMON.info.Login.gcode);
                var cmd = new System.Data.SqlClient.SqlCommand(sql, cn);
                var rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    string cmbdata = string.Format("[{0}] {1}", rdr["uid"].ToString(), rdr["uname"].ToString());
                    this.cmbUser.Items.Add(cmbdata);
                }
                cmd.Dispose();
                cn.Close();
                cn.Dispose();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("User List Error\n\n" + ex.Message);
            }
            cmbUser.SelectedIndex = 0;//전체

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

        }
        private void btSearch_Click(object sender, EventArgs e)
        {
            RefreshData();
        }
        void RefreshData()
        {
            try
            {
                string sd = dtSD.Text;
                string ed = dtED.Text;

                //사용자번호추적
                string userNo = "%";
                if (cmbUser.SelectedIndex > 0)
                {
                    userNo = cmbUser.Text.Substring(1,cmbUser.Text.LastIndexOf(']') - 1);
                 //   userNo = userNo.Substring(0, userNo.Length - 1);
                }

                var place = "%";
                if (cmbPlace.SelectedIndex > 0) place =  cmbPlace.Text.Trim() ;
                var invtype = "%";
                if (cmbInvType.SelectedIndex > 0) invtype =  cmbInvType.Text.Trim();
                this.ta.Fill(this.dSInventory.vInventory, FCOMMON.info.Login.gcode, sd, ed, invtype, userNo, place);

                this.dSInventory.vInventory.AcceptChanges();
                //FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);

                arDatagridView1.AutoResizeColumns();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }
        }
       
        void Inventory_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            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["cr_qty"] = 0;
            e.Row["cr_amt"] = 0;
            e.Row["dr_qty"] = 0;
            e.Row["dr_amt"] = 0;
            e.Row["item"] = -1;
            e.Row["invtype"] = "입고";
        }

        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[] { "item", "itemmodel", "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 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 toolStripLabel2_Click(object sender, EventArgs e)
        {
            var dataList = FCOMMON.DBM.getDateList("inventory", "", 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.RepInvStock();
            f.ShowDialog();
        }

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

        private void exportListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            sd.FileName = "inventory.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 bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
           
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {

        }

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

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

            try
            {
                var cnt = this.ta.Update(this.dSInventory.vInventory);
                FCOMMON.Util.MsgI($"{cnt}건의 자료가 저장 되었습니다");
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }
        }


        private void btAdd_Click(object sender, EventArgs e)
        {
            var newdr = this.dSInventory.vInventory.NewvInventoryRow();
            var f = new finventoryAdd(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                newdr.EndEdit();
                this.dSInventory.vInventory.AddvInventoryRow(newdr);
                var cnt = ta.Update(newdr);
                if (cnt != 1)
                {
                    FCOMMON.Util.MsgE("저장이 완료되지 않았습니다");
                }
                else
                {
                    //방금입력한 자료의 idx를 찾아서 업데이트해아한다.
                    var taq = new DSInventoryTableAdapters.QueriesTableAdapter();
                    var idx = taq.GetLastIdx(newdr.gcode, newdr.uid, newdr.invtype, newdr.wuid, newdr.wdate, newdr.item);
                    newdr.idx = (int)idx;
                    newdr.EndEdit();
                    newdr.AcceptChanges();
                }
            }
            else
            {
                newdr.Delete();
                //newdr.AcceptChanges();
            }
            
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            funcEdit();
        }
        void funcEdit()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSInventory.vInventoryRow;
            var f = new finventoryAdd(dr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                dr.EndEdit();
                var cnt = ta.Update(dr);
                if (cnt != 1)
                {
                    FCOMMON.Util.MsgE("저장이 완료되지 않았습니다");
                }
                else dr.AcceptChanges();
            }
            else dr.RejectChanges();
        }

        private void btDel_Click(object sender, EventArgs e)
        {
            funcDelete();
        }
        void funcDelete()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSInventory.vInventoryRow;
          
            var dlg = FCOMMON.Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?");
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            dr.Delete();
            var cnt = ta.Update(dr);
            if(cnt != 1)
            {
                FCOMMON.Util.MsgE("저장 실패");
            }else
            {
                //dr.AcceptChanges();
            }

        }


        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            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[] { "username","box","uid","place","itemName","itemModel","serial","placebox","memo" };
                    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 편집ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            funcEdit();
        }

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

        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 입고등록ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //입고
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSInventory.vInventoryRow;
            if(dr.item == -1)
            {
                FCOMMON.Util.MsgE("입력된 품목이 없습니다");
                return;
            }

            var newdr = this.dSInventory.vInventory.NewvInventoryRow();
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.invtype = "입고";
            newdr.item = dr.item;
            //newdr.ItemArray = dr.ItemArray;
            newdr.itemModel = dr.itemModel;
            newdr.itemName = dr.itemName;
            newdr.place = dr.place;
            newdr.box = dr.box;
            newdr.sid = dr.sid;
            

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

        }

        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;
            if (dr.item == -1)
            {
                FCOMMON.Util.MsgE("입력된 품목이 없습니다");
                return;
            }

            var newdr = this.dSInventory.vInventory.NewvInventoryRow();
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.invtype = "출고";
            newdr.item = dr.item;
            //newdr.ItemArray = dr.ItemArray;
            newdr.sid = dr.sid;
            newdr.itemModel = dr.itemModel;
            newdr.itemName = dr.itemName;
            newdr.place = dr.place;
            newdr.box = dr.box;

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

        private void toolStripLabel7_Click(object sender, EventArgs e)
        {
            updateplace();
        }

        private void arDatagridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }
    }
}
