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 FEQ0000
{
    public partial class fPurchase_AddS : fBase
    {
        BindingSource bsManu;
        BindingSource bsModel;
        dsPurchase.PurchaseRow dr;
        public Boolean repeatAdd = false;
        public fPurchase_AddS(dsPurchase.PurchaseRow dr_)
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            Properties.Settings.Default["EEEntities"] = 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.tbSupply.Leave += tbSupply_Leave;
            
            foreach (Control ctl in this.Controls)
            {
                if (ctl.GetType() == typeof(TextBox) || ctl.GetType() == typeof(ComboBox))
                {
                    ctl.KeyDown += ctl_KeyDown;
                }
            }
        }

   

        //Boolean advInput = false;
        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            //상태
            var stateList = FCOMMON.DBM.getCodeTable("04");
            this.cmbState.DisplayMember = "Value";
            this.cmbState.ValueMember = "Value";
            this.cmbState.DataSource = stateList;

            //보관소
            var dt_dept = FCOMMON.DBM.getCodeTable("50");
            bsManu.DataSource = dt_dept;
            this.cmbPlace.DisplayMember = "Value";
            this.cmbPlace.ValueMember = "Value";
            this.cmbPlace.DataSource = bsManu;

            //담당자목록
            var userList = FCOMMON.DBM.getUserList(); //.getGroupList("name", "Users", "[level] > 0 and [level] < 10");
            foreach (var user in userList)
            {
                this.cmbReceive.Items.Add(string.Format("[{0}] {1}", user.Key, user.Value));
                this.cmbRequest.Items.Add(string.Format("[{0}] {1}", user.Key, user.Value));
            }

            dtPdate.Value = DateTime.Parse(dr.pdate);
           
            ///입력된 데이터를 적용한다.
            dtPdate.Value = DateTime.Parse(dr.pdate);
            if(cmbRequest.Items.Count > 0)
            {
                for(int i = 0; i< cmbRequest.Items.Count ;i++)
                {
                    if (cmbRequest.Items[i].ToString().StartsWith("[" + dr.request + "]"))
                    {
                        cmbRequest.SelectedIndex = i;
                        break;
                    }   
                }
            } else cmbRequest.Text = dr.request;

            if (cmbReceive.Items.Count > 0)
            {
                for (int i = 0; i < cmbReceive.Items.Count; i++)
                {
                    if (cmbReceive.Items[i].ToString().StartsWith("[" + dr.receive + "]"))
                    {
                        cmbReceive.SelectedIndex = i;
                        break;
                    }
                }
            }
            else cmbReceive.Text = dr.receive;


            cmbPlace.Text = dr.place;
            tbSID.Text = dr.sid;
            tbSID.Tag = tbSID.Text;

            tbPumName.Text = dr.pumname;
            tbPumName.Tag = tbPumName.Text;

            tbPumModel.Text = dr.pumscale;
            tbPumQty.Text = dr.pumqty.ToString();
            tbPumStock.Text = "--";
            if (dr.IspumidxNull()) tbPumIDX.Text = "-1";
            else tbPumIDX.Text = dr.pumidx.ToString();
            tbPumPrice.Text = dr.pumprice.ToString();
            tbPumAmt.Text = dr.pumamt.ToString("N0");   //천단위 구분기호 추가 181222
            tbPumUnit.Text = dr.pumunit;

            tbSupply.Text = dr.supply;
            tbSupply.Tag = tbSupply.Text;
            tbSupplyIndex.Text = dr.supplyidx.ToString();

            cmbState.Text = dr.state;
           
            tbBigo.Text = dr.bigo;


            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.purchase));
            if (curLevel < 5)
            {

                if (dr.RowState == DataRowState.Detached || dr.RowState == DataRowState.Added)
                    cmbReceive.Enabled = false;

                cmbState.Enabled = false;
                if (cmbRequest.Text != "") cmbRequest.Enabled = false;

                //데이터가 편집 상태인데 요청자가 내가 아닌경우에도 편집 불가
                Boolean enb = true;
                if (dr.RowState == DataRowState.Unchanged && dr.request != FCOMMON.info.Login.no)
                    enb = false;

                if (enb == false) //일반 사용자는 쇼핑, 카드 잇으면 수정 불가
                {
                    btSave.Enabled = false;
                }
            }

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


            //이미지를 불러온다.
            pictureBox1.Tag = "";
            if (dr.RowState != DataRowState.Detached && dr.RowState != DataRowState.Deleted && dr.RowState != DataRowState.Added)
            {
                if (dr.IspumidxNull() == false && dr.pumidx != -1)
                {
                    var img = FCOMMON.DBM.GetImageData("Items", "image", dr.pumidx);
                    if (img != null)
                    {
                        this.pictureBox1.Image = img;
                    }
                }
            }

            

        }

        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":
                        ////요청자가 마지막으로 입력한 자료의 process 를 찾아서 기입해준다.
                        //var lastprocess = FCOMMON.DBM.getFirstValue("process", "purchase", "request like '%" + this.cmbRequest.Text + "%'", "pdate desc");
                        //if (lastprocess != "") cbProcess.Text = lastprocess;
                        tbSID.Focus();
                        break;
                    case "tbpumname":
                        Lov_Item(search, false);
                        break;
                    case "tbproject":
                        Lov_Project(search, false);
                        break;
                    case "tbsupply":
                        Lov_Supply(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.tbPumUnit.Text = f.itemUnit; //181214

                    this.tbPumModel.Enabled = false;
                    this.tbPumUnit.Enabled = false;
                    if (tbSID.Text != "") tbSID.Enabled = false;
                    else tbSID.Enabled = true;
                    
                    //제품을 찾앗다면 suppy 등을 업데이트 해준다.
                    var pcInfo = FCOMMON.DBM.getLastPurchaseInfo(f.item);
                    if (pcInfo.idx != -1)
                    {
                        tbSupply.Text = pcInfo.supply;
                        tbSupplyIndex.Text = pcInfo.supplyidx.ToString();
                       // if (pcInfo.project != "" && tbProject.Text == "")
                           // tbProject.Text = pcInfo.project;
                    }
                    else
                    {
                        tbSupply.Text = f.itemSupply;
                        tbSupplyIndex.Text = f.itemSupplyidx.ToString();
                    }

                    //display image
                    var image = FCOMMON.DBM.GetImageData("Items", "image", int.Parse(tbPumIDX.Text));
                    var oimage = this.pictureBox1.Image;
                    this.pictureBox1.Image = image;
                    if (oimage != null) oimage.Dispose();
                }
            }
            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.Title;
            //        this.tbProject.Tag = f.Title;
            //        this.tbProjectIndex.Text = f.Index.ToString();
            //        btSave.Focus();
            //    }
            //    else
            //    {
            //        tbProject.SelectAll();
            //        tbProject.Focus();
            //    }
            //}
            //else this.btSave.Focus();
        }
        void Lov_Supply(string search, Boolean allowAll)
        {
            if (search != "" || allowAll == true)
            {
                FCM0000.fLovSupply f = new FCM0000.fLovSupply(search);
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    tbSupply.Text = f.Title;
                    tbSupply.Tag = f.Title;
                    tbSupplyIndex.Text = f.Index.ToString();
                   // if (advInput)
                    //    this.tbProject.Focus();
                    //else
                        this.tbBigo.Focus();
                }
                else
                {
                    tbSupply.Focus();
                    tbSupply.SelectAll();
                }
            }
            else
            {
               // if (advInput)
               //     this.tbProject.Focus();
               // else
                    this.tbBigo.Focus();
            }
        }
        private bool saveData()
        {
            this.Validate();

            tbSID.Text = sidTrim(tbSID.Text);


            //SID값이 신규일때 업데이트되면 해당 값도 같이 업데이트를 해준다.
            //210114


            //if (cbProcess.Text.Trim() == "")
            //{
            //    FCOMMON.Util.MsgE("추가정보내의 [공정]을 선택하세요.");
            //    cbProcess.Focus();
            //    return false;
            //}

            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 ( cmbPlace.SelectedIndex < 0)
            {
                FCOMMON.Util.MsgE("저장소를 선택하세요");
                cmbPlace.Focus();
                return false;
            }

            //품목정보에 없는 데이터이므로 자료를 추가한다.
            if(tbPumIDX.Text == "-1")
            {
                var newidx = FCOMMON.DBM.addItem(tbPumName.Text, tbSID.Text, tbPumModel.Text.Trim(), decimal.Parse(tbPumPrice.Text), tbSupply.Text.Trim(), int.Parse(tbSupplyIndex.Text), 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);
            }

            //수령을 했는데. 현재 상태가 04 미만이면 04(수령)으로 변경 한다.
           

            if (tbPumQty.Text.isEmpty()) tbPumQty.Text = "0";
            if (tbPumPrice.Text.isEmpty()) tbPumPrice.Text = "0";
            dr.pumqty = int.Parse(tbPumQty.Text);
            dr.pumprice = decimal.Parse(tbPumPrice.Text);
            dr.pumamt = dr.pumqty * dr.pumprice;
            if (tbPumIDX.Text == "" || tbPumIDX.Text == "-1") dr.SetpumidxNull();
            else dr.pumidx = int.Parse(tbPumIDX.Text);
            dr.sid = tbSID.Text.Trim(); 

            dr.pdate = this.dtPdate.Value.ToString("yyyy-MM-dd");
            dr.place = cmbPlace.Text;

            dr.gcode = FCOMMON.info.Login.gcode;
            if (cmbRequest.Text.IndexOf("]") != -1)
                dr.request = cmbRequest.Text.Substring(1, cmbRequest.Text.IndexOf("]") - 1);
            else
                dr.request = cmbRequest.Text.Trim();

            dr.sid = tbSID.Text;
            dr.pumname = tbPumName.Text;
            dr.pumname = dr.pumname.Replace("*", "x");  //181031
            dr.pumscale = tbPumModel.Text;
            dr.pumscale = dr.pumscale.Replace("*", "x");  //181031
            dr.pumunit = tbPumUnit.Text;
            dr.supply = tbSupply.Text;

            if (tbSupplyIndex.Text == "") dr.SetsupplyidxNull();
            else dr.supplyidx = int.Parse(tbSupplyIndex.Text);

            dr.state = cmbState.Text.Trim();

            if (cmbReceive.Text.IndexOf("]") != -1)
                dr.receive = cmbReceive.Text.Substring(1, cmbReceive.Text.IndexOf("]") - 1);
            else
                dr.receive = cmbReceive.Text.Trim();


            dr.bigo = tbBigo.Text;

            //품정보가 업데이트 되어있으면 해당 데이터의 이미지를 업데이트 한다.(크기비교)
            //품정보가 없다면 그대로 생성을 해준다.
            if (tbPumIDX.Text == "" || tbPumIDX.Text == "-1")
            {

                //아이템을 추가해야하낟.
                byte[] pic = null;
                if (this.pictureBox1.Image != null && this.pictureBox1.Tag.ToString() == "U")
                {
                    //이미지를 변경해줘야 한다.
                    pic = FCOMMON.DBM.getImagByteArray(this.pictureBox1.Image);
                }
                var newidx = FCOMMON.DBM.addItem(dr.pumname, dr.sid, dr.pumscale, dr.pumprice, dr.supply, dr.supplyidx, pic);
                if (newidx != -1)
                {
                    dr.pumidx = newidx;
                    Console.WriteLine("new pumidx set = " + dr.pumidx.ToString());
                }
            }
            else
            {
                //아이템을 추가해야한다(변경된 이름은 
                if (this.pictureBox1.Image != null && this.pictureBox1.Tag.ToString() == "U")
                {
                    //이미지를 변경해줘야 한다.
                    FCOMMON.DBM.setImageData(this.pictureBox1.Image, "Items", "image", dr.pumidx);
                }
            }

            dr.EndEdit();

            return true;
        }

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

        private void chkInDate_CheckedChanged(object sender, EventArgs e)
        {
          //  this.dtInDate.Enabled = chkInDate.Checked;
        }

        private void chkExp_CheckedChanged(object sender, EventArgs e)
        {
           // this.dtExpDate.Enabled = chkExp.Checked;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //string code = "";
            //if (cmbState.SelectedIndex < 0) label3.Text = "--";
            //else
            //{
            //    //var value = cmbState.DataSource as BindingSource;
            //    //var list = value.DataSource as Dictionary<string, string>;
            //    //var item = list.Values
            //    if (cmbState.Text.StartsWith("[") == false) return;
            //    code = cmbState.Text.ToString().Substring(1, 2);
            //    var desc = FCOMMON.DBM.getCodeSavlue("04", code);
            //    label3.Text = desc;

            //}
            //switch (code)
            //{
            //    case "01":
            //        label3.BackColor = Color.LightBlue;
            //        break;
            //    case "02":
            //        label3.BackColor = Color.SkyBlue;
            //        break;
            //    case "03":
            //        label3.BackColor = Color.Yellow;
            //        break;
            //    case "04":
            //        label3.BackColor = Color.Green;
            //        break;
            //    case "06":
            //    case "05":
            //        label3.BackColor = Color.Red;
            //        break;
            //    case "07":
            //        label3.BackColor = Color.Magenta;
            //        break;
            //    default:
            //        label3.BackColor = Color.LightGray;
            //        break;
            //}

        }

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

        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 linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string path = "\\\\k4fs3201n\\ee1t$\\1. 장비기술1파트\\24_Project & Overhaul 예산 사용 실적\\구매 견적서\\" + DateTime.Now.Year.ToString("0000") + "년";
            FCOMMON.Util.RunExplorer(path);
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog od = new OpenFileDialog();
            if (od.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            var image = Image.FromFile(od.FileName);
            var oimage = this.pictureBox1.Image;
            this.pictureBox1.Image = image;
            this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            this.pictureBox1.Tag = "U";
            if (oimage != null) oimage.Dispose();
        }

        private void imgpase_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!Clipboard.ContainsImage())
            {
                FCOMMON.Util.MsgE("이미지를 먼저 클립보드에 복사 하세요.");
                return;
            }

            var image = Clipboard.GetImage();
            var oimage = this.pictureBox1.Image;
            this.pictureBox1.Image = image;
            this.pictureBox1.Tag = "U";
            if (oimage != null) oimage.Dispose();
        }

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //FCOMMON.fWebCamera f = new FCOMMON.fWebCamera(FCOMMON.info.camIndex);
            //if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    var bmp = f.bmp.Clone();
            //    Application.DoEvents();
            //    var oimag = this.pictureBox1.Image;
            //    this.pictureBox1.Image = (Image)bmp;
            //    if (oimag != null) oimag.Dispose();
            //}
        }

        private void cbEQManu_SelectedIndexChanged(object sender, EventArgs e)
        {
            //string 원본모델 = cbEQModel.Text;

            ////장비모델 필터를 변경해준다.
            //if (cbEQManu.SelectedIndex < 0)
            //{
            //    cbEQModel.SelectedIndex = -1;
            //    return;
            //}

            //string filter = "svalue='" + cbEQManu.Text.Replace("'", "''") + "'";
            //bsModel.Filter = filter;
            //if (원본모델 != "") cbEQModel.Text = 원본모델;
            //else cbEQModel.SelectedIndex = -1;
        }

        private void linkLabel6_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //lov 공급처
            Lov_Supply("", true);
        }

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