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 finventoryAdd : fBase
    {
        BindingSource bsManu;
        BindingSource bsModel;
        DSInventory.vInventoryRow dr;
        public Boolean repeatAdd = false;

        public finventoryAdd(DSInventory.vInventoryRow dr_)
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            bsManu = new BindingSource();
            bsModel = new BindingSource();
            this.dr = dr_;
            this.KeyPreview = true;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };
            this.tbPumName.Leave += tbPumName_Leave;
            this.tbProject.Leave += tbProject_Leave;
            foreach (Control ctl in groupBox1.Controls)
            {
                if (ctl.GetType() == typeof(TextBox) || ctl.GetType() == typeof(ComboBox))
                {
                    ctl.KeyDown += ctl_KeyDown;
                }
            }
        }
       
        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            //담당자목록
            var userList = FCOMMON.DBM.getUserList();//.getGroupList("name", "Users", "[level] > 0 and [level] < 10");
            foreach (var user in userList)
            {
                this.cmbRequest.Items.Add(string.Format("[{0}] {1}",user.Key,user.Value));
            }

            //보관소 목록업데이트
            var ListStorage = FCOMMON.DBM.getCodeList("60");
            cmbStorage.Items.Clear();
            foreach (var item in ListStorage)
                cmbStorage.Items.Add(item.Value);

            //박스 목록업데이트
            var ListBox = FCOMMON.DBM.getCodeList("61");
            cmbBox.Items.Clear();
            foreach (var item in ListBox)
                cmbBox.Items.Add(item.Value);

            //사현재사용자의 데이터를 찾는다.
            if (cmbRequest.Items.Count > 0)
            {
                for (int i = 0; i < cmbRequest.Items.Count; i++)
                {
                    if (cmbRequest.Items[i].ToString().StartsWith("[" + dr.uid + "]"))
                    {
                        cmbRequest.SelectedIndex = i;
                        break;
                    }
                }
            }
            else cmbRequest.Text = dr.uid;


            ///입력된 데이터를 적용한다.
            if (dr.pdate == "") dr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            dtPdate.Value = DateTime.Parse(dr.pdate);            
            dtPdate.Value = DateTime.Parse(dr.pdate);
            // cmbRequest.Text = dr.userName;
            tbPumIDX.Text = dr.item.ToString();
            tbSID.Text = dr.sid;
            tbSID.Tag = tbSID.Text;
            tbPumIDX.Text = dr.item.ToString();
            tbPumName.Text = dr.itemName;
            tbPumName.Tag = tbPumName.Text;
            tbPumModel.Text = dr.itemModel;
            tbPumQty.Text = dr.dr_qty.ToString("N0");
            if (dr.dr_qty == 0 || dr.dr_amt == 0) tbPumPrice.Text = "0";
            else tbPumPrice.Text = string.Format("{0}",dr.dr_amt / dr.dr_qty);
            tbPumAmt.Text = dr.dr_amt.ToString("N0");

            tbSN.Text = dr.serial;
            cmbStorage.Text = dr.place;
            cmbBox.Text = dr.box;
            tbProject.Text = dr.projectName;
            tbProject.Tag = tbProject.Text;
            tbProjectIndex.Text = dr.project.ToString();

            cmbState.Text = dr.invtype; //입고/출고/정정
            tbBigo.Text = dr.memo;

            //프로젝트 비활성화
            if(FCOMMON.info.Login.gcode == "ENV")
            {
                tbProject.Enabled = false;
                tbProjectIndex.Enabled = false;
                linkLabel7.Enabled = false;
            }

            this.Show();
            Application.DoEvents();
            tbPumName.Focus();
        }

        string sidTrim(string sid)
        {
            return sid.Replace(" ", "").Replace("-", "").Replace("_", "").Trim();
        }

        void ctl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Control ctl = sender as Control;
                string nm = ctl.Name.ToLower();
                string search = ctl.Text.Trim();

                Console.WriteLine("inner keydown " + nm + ":" + search);

                switch (nm)
                {
                    case "cmbrequest":
                        tbSID.Focus();
                        break;
                    case "tbpumname":
                        Lov_Item(search, false);
                        break;
                    case "tbproject":
                        Lov_Project(search, false);
                        break;
                    default:
                        SendKeys.Send("{TAB}");
                        break;
                }
            }
        }
        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Lov_Item("",true);
        }

        void Lov_Item( string search,Boolean allowAll)
        {
            if (search == "" && allowAll==false)
            {
                FCOMMON.Util.MsgE("품명은 필수 값 입니다");
                tbPumName.Focus();
                return;
            }
            else if (search.ToLower() != tbPumName.Tag.ToString().ToLower() || tbPumIDX.Text == "-1" || tbPumIDX.Text == "") //값이 바뀌엇다면 검색을 해준다.
            {
                var f = new FCM0000.fLovItem(search);
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    //인덱스값이 다르면 모델 및 가격을 업데이트 한다.
                    tbPumName.Text = f.itemName;
                    tbPumName.Tag = f.itemName;

                    this.tbPumIDX.Text = f.item.ToString();
                    this.tbPumModel.Text = f.itemmodel;
                    this.tbPumPrice.Text = f.itemprice.ToString();
                    this.tbSID.Text = f.SID;
                    this.tbSID.Tag = f.SID;
                    this.tbPumModel.Enabled = false;
                    if (tbSID.Text != "") tbSID.Enabled = false;
                    else tbSID.Enabled = true;
                }
            }
            this.tbPumQty.Focus();
        }
        void Lov_Project(string search, Boolean allowAll)
        {
            if (search != "" || allowAll == true)
            {
                var f = new FCM0000.fLovProject(search,"%");
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    this.tbProject.Text = f.val_Title;
                    this.tbProject.Tag = f.val_Title;
                    
                    this.tbProjectIndex.Text = f.val_Index.ToString();
                    btSave.Focus();
                }
                else
                {
                    tbProject.SelectAll();
                    tbProject.Focus();
                }
            }
            else this.btSave.Focus();
        }
   
        private Boolean saveData()
        {
            this.Validate();

            tbSID.Text = sidTrim(tbSID.Text);

            if (tbPumName.Text.isEmpty())
            {
                FCOMMON.Util.MsgE("품명이 없습니다.");
                tbPumName.Focus();
                return false;
            }

            //비활성화된 상태에서는 입력하지 않아도 동작하게 함
            if ( tbPumModel.Enabled=true && tbPumModel.Text == "")
            {
                FCOMMON.Util.MsgE("제품 규격을 입력하세요.");
                tbPumModel.Focus();
                return false;
            }
            if (tbPumQty.Text == "")
            {
                FCOMMON.Util.MsgE("수량을 입력하세요.");
                tbPumQty.Focus();
                return false;
            }
           
            //품목정보에 없는 데이터이므로 자료를 추가한다.
            if(tbPumIDX.Text == "-1")
            {
                var newidx = FCOMMON.DBM.addItem(tbPumName.Text, tbSID.Text, tbPumModel.Text.Trim(), decimal.Parse(tbPumPrice.Text), "", -1, null);
                if (newidx > 0) tbPumIDX.Text = newidx.ToString();
            }
            else if(tbSID.Text != "" && tbSID.Text != tbSID.Tag.ToString())
            {
                //SID가 변경되었으므로 업데이트 해주낟.
                FCOMMON.DBM.UpdateItemSID(int.Parse(tbPumIDX.Text), tbSID.Text);
            }

            if(cmbStorage.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("보관소를 입력하세요");
                cmbStorage.Focus();
                return false;
            }

            dr.itemName = tbPumName.Text;
            dr.itemModel = tbPumModel.Text;
            dr.item = int.Parse( tbPumIDX.Text   );
            dr.place = cmbStorage.Text;
            dr.box = cmbBox.Text;
            dr.serial = tbSN.Text;
            if (tbPumQty.Text.isEmpty()) tbPumQty.Text = "0";
            if (tbPumPrice.Text.isEmpty()) tbPumPrice.Text = "0";
            dr.dr_qty = int.Parse(tbPumQty.Text);
            dr.dr_amt = dr.dr_qty * int.Parse(tbPumPrice.Text);
            if (tbPumIDX.Text == "" || tbPumIDX.Text == "-1") dr.SetitemNull();
            else dr.item = int.Parse(tbPumIDX.Text);
            dr.sid = tbSID.Text.Trim(); 
            dr.pdate = this.dtPdate.Value.ToString("yyyy-MM-dd");
            dr.gcode = FCOMMON.info.Login.gcode;
            if (cmbRequest.Text.IndexOf("]") != -1)
            {
                dr.uid = cmbRequest.Text.Substring(1, cmbRequest.Text.IndexOf("]") - 1);
                dr.userName = cmbRequest.Text.Substring(cmbRequest.Text.IndexOf("]") + 2);
            }   
            else
            {
                dr.uid = cmbRequest.Text;
                dr.userName = string.Empty;
            }
            dr.sid = tbSID.Text;
            dr.projectName = tbProject.Text;
            if (tbProjectIndex.Text == "") dr.SetprojectNull();
            else dr.project = int.Parse(tbProjectIndex.Text);
            dr.invtype = cmbState.Text.Trim();
            dr.memo = tbBigo.Text.Trim();
            if(cmbState.Text == "입고")
            {
                if (dr.dr_qty < 0) dr.dr_qty *= -1;
                if (dr.dr_amt < 0) dr.dr_amt *= -1;
            } else  if(cmbState.Text =="출고")
            {
                if (dr.dr_qty > 0) dr.dr_qty *= -1;
                if (dr.dr_amt > 0) dr.dr_amt *= -1;
            }
            dr.EndEdit();
            return true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!saveData()) return;
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

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

        private void tbPumQty_TextChanged(object sender, EventArgs e)
        {
            var strQty = this.tbPumQty.Text;
            var strPrice = this.tbPumPrice.Text;

            int qty = 0;
            double price = 0;
            if (strQty.IsNumeric()) qty = int.Parse(strQty);
            if (strPrice.IsNumeric()) price = double.Parse(strPrice);
            double amt = price * qty;
            tbPumAmt.Text = amt.ToString("N0");
        }


        private void linkLabel7_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //lov 프로젝트
            Lov_Project("", true);
        }

        void tbProject_Leave(object sender, EventArgs e)
        {
            //커서를 빠져나갈떄 사용자가 이름만 변경했다면 선택 idx를 제거해준다.
            var tb = sender as TextBox;
            if (tb.Text == "") tbProjectIndex.Text = "-1";
            else if (tb.Text != tb.Tag.ToString()) tbProjectIndex.Text = "-1";
        }

        void tbPumName_Leave(object sender, EventArgs e)
        {
            //커서를 빠져나갈떄 사용자가 이름만 변경했다면 선택 idx를 제거해준다.
            var tb = sender as TextBox;
            if (tb.Text == "") tbPumIDX.Text = "-1";
            else if (tb.Text != tb.Tag.ToString()) tbPumIDX.Text = "-1";
            if(tbPumIDX.Text =="-1")
            {
                tbPumModel.Enabled = true;
              //  tbPumUnit.Enabled = true;
            }
        }
    }
}
