using FarPoint.Excel.EntityClassLibrary.DrawingEx;
using FCM0000.Mail;
using FCOMMON;
using FEQ0000.Purchase;
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 fPurchaseEB_Add : fBase
    {
        BindingSource bsManu;
        BindingSource bsModel;
        dsPurchase.EETGW_PurchaseEBRow dr;
        public Boolean repeatAdd = false;
        Boolean binit = false;
       
        string dbchk1 = string.Empty;

        public fPurchaseEB_Add(dsPurchase.EETGW_PurchaseEBRow 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;
           // this.tbProject.Leave += tbProject_Leave;

            foreach (Control ctl in groupBox1.Controls)
            {
                if (ctl.GetType() == typeof(TextBox) || ctl.GetType() == typeof(ComboBox))
                {
                    ctl.KeyDown += ctl_KeyDown;
                }
            }

            this.tbPumPrice.Validated += (s1, e1) => {

                if (tbPumPrice.Tag != null && tbPumPrice.Tag.ToString().Equals(tbPumPrice.Text))
                {

                }
                else
                {
                    tbPumPrice.Tag = tbPumPrice.Text;
                    if (decimal.TryParse(tbPumPrice.Text.Replace(",", ""), out decimal value))
                    {
                        tbPumPrice.Text = value.ToString("N0");

                    }
                }
            };
            this.tbPumPriceD.Validated += (s1, e1) => {

                if (tbPumPriceD.Tag != null && tbPumPriceD.Tag.ToString().Equals(tbPumPriceD.Text))
                {

                }
                else
                {
                    tbPumPriceD.Tag = tbPumPriceD.Text;
                    if (decimal.TryParse(tbPumPriceD.Text.Replace(",", ""), out decimal value))
                    {
                        tbPumPriceD.Text = value.ToString("N0");

                    }
                }


            };
        }

        //Boolean advInput = false;
        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            tbPumName.ImeMode = ImeMode.Alpha;

            //상태
            var stateList = FCOMMON.DBM.getCodeTable("04");
            this.cmbState.DisplayMember = "Value";
            this.cmbState.ValueMember = "Value";
            this.cmbState.DataSource = stateList;

            //전자실분류
            var LstCost = FCOMMON.DBM.getCodeTable("71");
            this.cmbDept.DisplayMember = "Value";
            this.cmbDept.ValueMember = "Value";
            this.cmbDept.DataSource = LstCost;

            //SITE
            var LstLine = FCOMMON.DBM.getCodeTable("23","code");
            this.cmbSite.DisplayMember = "Value";
            this.cmbSite.ValueMember = "Value";
            this.cmbSite.DataSource = LstLine;


            //통화
            var LstCur = FCOMMON.DBM.getCodeTable("69");
            this.cmbCurrency.DisplayMember = "Value";
            this.cmbCurrency.ValueMember = "Value";
            this.cmbCurrency.DataSource = LstCur;

            //oversea
            var LstOverSea = FCOMMON.DBM.getCodeTable("30");
            this.cmbOverSeas.DisplayMember = "Value";
            this.cmbOverSeas.ValueMember = "Value";
            this.cmbOverSeas.DataSource = LstOverSea;


            //구매자비고
            var LstRemark = FCOMMON.DBM.getCodeList("70");
            this.cmbRemark.Items.Clear();
            this.cmbRemark.Items.Add("-- 선택 안함 --");
            foreach (var item in LstRemark)
            {
                cmbRemark.Items.Add(item.Value);
            }
            this.cmbRemark.SelectedIndexChanged += (s1, e1) =>
            {
                if (cmbRemark.SelectedIndex > 0)
                {
                    tbBigo.Text = cmbRemark.Text.Trim() + tbBigo.Text.Trim();
                }
            };
            cmbRemark.SelectedIndex = 0;


            //담당자목록
            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);
            if (dr.IsindateNull() || dr.indate.isEmpty())
            {
                this.chkInDate.Checked = false;
            }
            else
            {
                this.chkInDate.Checked = true;
                dtInDate.Value = DateTime.Parse(dr.indate);
            }

            //예정일추가 231106 - 양진원
            if (dr.IsedateNull() || dr.edate.isEmpty())
            {
                this.chkExp.Checked = false;
            }
            else
            {
                this.chkExp.Checked = true;
                dtExpDate.Value = DateTime.Parse(dr.edate);
            }


            //if (dr.IsedateNull() || dr.edate.isEmpty())
            //{
            //    this.chkExp.Checked = false;
            //}
            //else
            //{
            //    this.chkExp.Checked = true;
            //    dtExpDate.Value = DateTime.Parse(dr.edate);
            //}

            ///입력된 데이터를 적용한다.
            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;

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

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

            tbPumModel.Text = dr.pumscale;

            if (dr.IspumqtyNull()) tbQtyReal.Text = "0";   //230817
            else tbQtyReal.Text = dr.pumqty.ToString();

            if (dr.IspumqtyReqNull()) tbQtyReq.Text = "0";   //230817
            else tbQtyReq.Text = dr.pumqtyReq.ToString();

            if (dr.IspumidxNull()) tbPumIDX.Text = "-1";
            else tbPumIDX.Text = dr.pumidx.ToString();
            tbPumPrice.Text = dr.pumprice.ToString("N0");
            tbPumPriceD.Text = dr.pumpriceD.ToString("N0");
            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;
            cmbSite.Text = dr.site;
            cmbDept.Text = dr.dept;
            cmbOverSeas.Text = dr.oversea;

            tbSC.Text = dr.sc;
            tbPO.Text = dr.po;
      
            tbBigo.Text = dr.bigo;
            if (dr.IschkremarkNull()) tbBigoChk.Text = string.Empty;
            else tbBigoChk.Text = dr.chkremark;

            dtInDate.Text = dr.indate;
            dtExpDate.Text = dr.edate;

            if (dr.IsinqtyNull() == false)
                tbInQty.Text = dr.inqty.ToString();

            this.dtExpDate.Enabled = chkExp.Checked;
            this.dtInDate.Enabled = chkInDate.Checked;

            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.purchaseEB));
            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 (tbSC.Text.Trim() != "") enb = false;

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

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

            //이미지를 불러온다.
            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;
                    }
                }
            }
            binit = true;


            if (dr.RowState == DataRowState.Detached || dr.RowState == DataRowState.Added)
            {
           
                dbchk1 = string.Empty;

                //복사된 자료는 isd가 잇으면 sid가 잇다면 자동 처리해준다.
                if (tbSID.Text.StartsWith("10") && tbSID.TextLength == 9)
                {
                    //sidchk1 = tbSID.Text;
                    dbchk1 = tbPumName.Text.Trim();
                }
            }
            else
            {
            
                dbchk1 = tbPumName.Text.Trim();
            }

            timer1.Start();

        }

        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 != "") btProcess.Text = lastprocess;
                        tbSID.Focus();
                        break;
                    case "tbpumname":
                        Lov_Item(search, false);
                        break;
            
                    case "tbsupply":
                        Lov_Supply(search, false);
                        break;
                    case "tbbigo":
                        e.Handled = true;
                        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)
            {
                dbchk1 = string.Empty;
                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)
                {
                    dbchk1 = f.itemName;

                    //인덱스값이 다르면 모델 및 가격을 업데이트 한다.
                    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("N0");
                    this.tbPumPriceD.Text = f.itempriceD.ToString("N0");
                    this.tbSID.Text = f.SID;
                    this.tbSID.Tag = f.SID;
                    this.tbPumUnit.Text = f.itemUnit; //181214
                    //''this.tbSite.Text = f.tbsi;
                    this.tbPumModel.Enabled = this.tbPumModel.Text.isEmpty();
                    
                    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();
                    }
                    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();
                }
            }
            if (tbPumModel.Enabled) tbPumModel.Focus();
            else this.tbQtyReq.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();
                   
                        this.tbBigo.Focus();
                }
                else
                {
                    tbSupply.Focus();
                    tbSupply.SelectAll();
                }
            }
            else
            {
             
                    this.tbBigo.Focus();
            }
        }
        private bool saveData()
        {
            this.Validate();

            tbSID.Text = sidTrim(tbSID.Text);

            if (dbchk1.isEmpty())
            {
                Util.MsgE("품목 검사가 진행되지 않았습니다\n품명을 입력한 후 엔터를 누르거나 [품명] 버튼을 눌러서 검색을 수행한 후 다시 시도하세요");
                tbPumName.Focus();
                Lov_Item(tbPumName.Text, true);
                return false;
            }

            //시드검사한 자료와 현재 입력된 시드가 다르면 검사를 다시 하게 한다
            if (this.tbPumName.Text.Trim().Equals(this.dbchk1.Trim()) == false)
            {
                Util.MsgE("품명검사 자료가 변경되었습니다. 다시 검사 하세요");
                Lov_Item("", true);
                dbchk1 = string.Empty;
                return false;
            }


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

            if (tbQtyReq.Text == "")
            {
                FCOMMON.Util.MsgE("수량(요청)을 입력하세요.");
                tbQtyReq.Focus();
                return false;
            }

            //실수량은 구매담당자만 입력한다
            if (tbBigoChk.Enabled && (cmbState.Text == "PO" || cmbState.Text == "PR"))
            {
                var qtycnv = int.TryParse(tbQtyReal.Text, out int qtyreq);
                if (qtycnv == false || qtyreq < 1)
                {
                    FCOMMON.Util.MsgE("수량(실 구매)을 입력하세요.");
                    tbQtyReal.Focus();
                    return false;
                }
            }

            
            //if (tbSite.Text.Equals("SPR"))
            //{
            //    if (FCOMMON.Util.MsgQ("SPR 항목입니다. 저장할까요?") != DialogResult.Yes)
            //        return false;
            //}

            if (chkInDate.Checked)
            {
                if (int.TryParse(tbInQty.Text.Replace(",", ""), out int qty) == false)
                {
                    if (FCOMMON.Util.MsgQ("입고 정보가 설정되어 있지만 입고 수량값이 없습니다") != DialogResult.Yes)
                    {
                        tbInQty.Focus();
                        tbInQty.SelectAll();
                        return false;
                    }
                }
            }


            //프로젝트명이 업다면 사유가 반드시 입력되어ㅑㅇ 하낟.
            if ( tbBigo.Text.isEmpty())
            {
                Util.MsgE("구매자 비고(=구매사유)를 입력하세요\n프로젝트가 없다면 사유가 입력되어야 합니다");
                tbBigo.Focus();
                return false;
            }

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

            //수령을 했는데. 현재 상태가 04 미만이면 04(수령)으로 변경 한다.
            if (chkInDate.Checked)
            {
                var curState = this.cmbState.Text.Trim();
                if (curState.ToLower() == "po" || curState.ToLower() == "pr" ||
                    curState.ToLower() == "approving")
                {
                    this.cmbState.SelectedValue = "Received";
                }

            }

            //단가가없는경우 생성한다.
            if (decimal.TryParse(tbPumPrice.Text.Replace(",", ""), out decimal vprice) == false)
            {
                if (decimal.TryParse(tbPumPriceD.Text.Replace(",", ""), out decimal vpriced) == true)
                {
                    applyDollerToWon();
                }
            }

            if (int.TryParse(tbQtyReq.Text.Replace(",", ""), out int vqtyreq) == false)
                tbQtyReq.Text = "0";
            if (int.TryParse(tbQtyReal.Text.Replace(",", ""), out int vqtyreal) == false)
                tbQtyReal.Text = "0";
            if (decimal.TryParse(tbPumPrice.Text.Replace(",", ""), out decimal vpumprice) == false)
                tbPumPrice.Text = "0";

            //요청 구매 수량이 다를경우 비고 입력이 필요함
            if (vqtyreal > 0 && vqtyreq > 0 && vqtyreq != vqtyreal)
            {
                if (tbBigoChk.Text.isEmpty())
                {
                    Util.MsgE("구매 요청/실 수량이 서로 다릅니다\n구매자 비고에 해당 사유를 입력하세요");
                    tbBigoChk.Focus();
                    return false;
                }
            }

            if (dr.RowState == DataRowState.Detached && vqtyreq < 1)
            {
                Util.MsgE($"요청수량을 입력하세요");
                tbQtyReq.Focus();
                return false;
            }

            dr.pumqty = vqtyreal;// int.Parse(tbPumQty.Text);
            dr.pumqtyReq = vqtyreq;// int.Parse(tbpumqtyReq.Text);
            dr.pumprice = vpumprice;// decimal.Parse(tbPumPrice.Text);
            dr.currency = cmbCurrency.Text.Trim();
            dr.place = "전자실";
            dr.oversea = cmbOverSeas.Text.Trim();

            if (decimal.TryParse(tbPumPriceD.Text.Replace(",", ""), out decimal priced))
            {
                dr.pumpriceD = priced;
            }
            else
            {
                dr.SetpumpriceDNull();
                dr.currency = "KRW";
            }

            if (vqtyreal > 0) dr.pumamt = dr.pumqty * dr.pumprice;
            else dr.pumamt = dr.pumqtyReq * dr.pumprice;

            if (dr.pumamt < 1)
            {
                FCOMMON.Util.MsgE($"금액이 없습니다. 단가 및 수량을 확인하세요\n해외 통화를 사용할 경우 환율을 고려한 국내단가를 입력해주세요\n환율을 자동으로 입력하려면 공용코드(69)의 FValue 에 값을 입력하세요");
                return false;
            }

            if (tbPumIDX.Text == "" || tbPumIDX.Text == "-1") dr.SetpumidxNull();
            else dr.pumidx = int.Parse(tbPumIDX.Text);
            dr.sid = tbSID.Text.Trim();

            if (chkExp.Checked) dr.edate = this.dtExpDate.Value.ToString("yyyy-MM-dd");
            else dr.SetedateNull();
            if (chkInDate.Checked) dr.indate = this.dtInDate.Value.ToString("yyyy-MM-dd");
            else dr.SetindateNull();
            dr.pdate = this.dtPdate.Value.ToString("yyyy-MM-dd");

            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;
            dr.site = cmbSite.Text;
            dr.dept = cmbDept.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.sc = tbSC.Text;
            dr.po = tbPO.Text;
          
            dr.bigo = tbBigo.Text;
            dr.chkremark = tbBigoChk.Text;

            if (chkInDate.Checked)
                dr.inqty = int.Parse(tbInQty.Text.Replace(",", ""));
            else dr.SetinqtyNull();

            //품정보가 업데이트 되어있으면 해당 데이터의 이미지를 업데이트 한다.(크기비교)
            //품정보가 없다면 그대로 생성을 해준다.
            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 comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            

        }

        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 b1 = int.TryParse(tbQtyReal.Text.Replace(",", ""), out int qtyreal);
            var b2 = int.TryParse(tbQtyReq.Text.Replace(",", ""), out int qtyreq);
            var b3 = double.TryParse(tbPumPrice.Text.Replace(",", ""), out double price);
            double amt = 0;

            //실구매수량이 잇으면 그걸로한다
            if (qtyreal > 0) amt = qtyreal * price;
            else amt = qtyreq * price;

            tbPumAmt.Text = amt.ToString("N0");
        }

     

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

        private void tbPumName_Click(object sender, EventArgs e)
        {
            //Lov_Item("", true);
        }

        private void tbPumName_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            Lov_Item(tbPumName.Text, true);
        }

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

       
        private void button4_Click(object sender, EventArgs 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 button5_Click(object sender, EventArgs e)
        {
         
        }

        private void button6_Click(object sender, EventArgs 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 button7_Click(object sender, EventArgs e)
        {
            var datapath = FCOMMON.DBM.getCodeSvalue("55", "02");
            if (datapath.isEmpty())
            {
                FCOMMON.Util.MsgE("견적서 기본폴더 공용코드 55-02 값을 입력하세요");
                return;
            }
            string path = System.IO.Path.Combine(datapath, DateTime.Now.Year.ToString("0000") + "년");// "\\\\k4fs3201n\\ee1t$\\1. 장비기술1파트\\24_Project & Overhaul 예산 사용 실적\\구매 견적서\\" + DateTime.Now.Year.ToString("0000") + "년";
            if (System.IO.Directory.Exists(path) == false)
                FCOMMON.Util.RunExplorer(datapath);
            else
                FCOMMON.Util.RunExplorer(path);
        }

        private void tbDolloerPrice_TextChanged(object sender, EventArgs e)
        {
            //단가에 금액이 없는경우에는 환율을 곱해준다.
            //if ( decimal.TryParse(tbPumPrice.Text, out decimal result) == false || result == 0)
            if (binit)
            {
                if (decimal.TryParse(tbPumPriceD.Text.Replace(",", ""), out decimal priced) == true)
                {
                    applyDollerToWon();
                }
                else
                {
                    //달러입력값도 이상하니 처리 못함
                    tbPumPrice.Text = "0";
                }
            }
        }
        void applyDollerToWon()
        {
            if (decimal.TryParse(tbPumPriceD.Text.Replace(",", ""), out decimal priced))
            {
                var curr = lbcurrentwon.Tag != null ? (float)lbcurrentwon.Tag : 0;
                var price = curr * (double)priced;
                tbPumPrice.Text = (Math.Ceiling(price)).ToString("N0");
            }
            else tbPumPrice.Text = "0";
        }

        private void tbStorage_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

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

        private void cmbCurrency_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (cmbCurrency.SelectedIndex >= 0)
            {
                var val = cmbCurrency.SelectedValue.ToString();
                var dt = cmbCurrency.DataSource as DataTable;
                var v = dt.AsEnumerable().Where(t => t.Field<String>("Value") == val).FirstOrDefault();
                if (v != null)
                {
                    var price = v.Field<float>("FValue");
                    lbcurrentwon.Text = $"환율:{price}원";
                    lbcurrentwon.Tag = price;
                    //if (binit)
                    //{

                    //    if (decimal.TryParse(tbPumPriceD.Text,out decimal priced))
                    //    {
                    //        if (priced > 0)
                    //            dr.pumamt = priced * (decimal)price;
                    //    }


                    //}
                }
                else
                {
                    lbcurrentwon.Text = $"환율이 입력되지 않았습니다";
                    lbcurrentwon.Tag = 0;
                }
            }
            else
            {
                lbcurrentwon.Text = "통화기호를 선택하세요";
                lbcurrentwon.Tag = 0;
            }
        }
    }
}
