using FarPoint.Win.Spread;
using FCOMMON;
using NetOffice.OutlookApi;
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_excelimport : fBase
    {
        BindingSource bsModel;
        eImporttype crmode;

        public enum eImporttype
        {
            NR,
            CR,
            EB
        }
        public fPurchase_excelimport(eImporttype cr)
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            Properties.Settings.Default["EEEntities"] = FCOMMON.info.CS;
            this.FormClosed += __Closed;
            crmode = cr;
            this.Text = $"구매내역 가져오기({crmode})";

            if (cr == eImporttype.CR)
            {
                cbProcess.Enabled = false;
                cbManuProc.Enabled = false;
                cbEQManu.Enabled = false;
                cbEQModel.Enabled = false;
                assetLabel.Visible = false;
                label22.Visible = false;
                label23.Visible = false;
                processLabel.Visible = false;
            }
            else
            {
                //장비제조            
                var dt_dept = FCOMMON.DBM.getCodeTable("06");
                BindingSource bsManu = new BindingSource(dt_dept, "");
                this.cbEQManu.DisplayMember = "Value";
                this.cbEQManu.ValueMember = "Value";
                this.cbEQManu.DataSource = bsManu;

                //장비모델            
                var dt_asset = FCOMMON.DBM.getCodeTable("07");
                bsModel = new BindingSource(dt_asset, "");
                bsModel.Filter = "svalue='그런거없다'";
                this.cbEQModel.DisplayMember = "Value";
                this.cbEQModel.ValueMember = "Value";
                this.cbEQModel.DataSource = bsModel;

                //제조공정
                var dt_manuproc = FCOMMON.DBM.getCodeTable("08");
                this.cbManuProc.DisplayMember = "Value";
                this.cbManuProc.ValueMember = "Value";
                this.cbManuProc.DataSource = dt_manuproc;

                //장비기술공정
                var dt_eetproc = FCOMMON.DBM.getCodeTable("09");
                this.cbProcess.DisplayMember = "Value";
                this.cbProcess.ValueMember = "Value";
                this.cbProcess.DataSource = dt_eetproc;
            }
        }

        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;

            //dtPdate.Value = DateTime.Now;

            loadsetting(this);

            if (crmode == eImporttype.CR)
                textBox1.Text = FCOMMON.Setting.system.Xml.get_Data(this.Name, "FILE_CR");
            else if (crmode == eImporttype.EB)
                textBox1.Text = FCOMMON.Setting.system.Xml.get_Data(this.Name, "FILE_EB");
            else
                textBox1.Text = FCOMMON.Setting.system.Xml.get_Data(this.Name, "FILE_NR");


            cmbState.Text = "PO";   //po에서 변경 200423 - JBS요청

            //기준값이 없다면 기본값으로 설정한다
            if (nudPumName.Value == 0 && nudSid.Value == 0 && nudPdate.Value == 0)
                linkLabel3_LinkClicked(null, null);


            if (this.crmode == eImporttype.EB)
            {
                nudPo.Value = 0;
                nudCr.Value = 0;
                //nudInDate.Value = 0;
                nudRecv.Value = 0;
                nudCost.Value = 0;
                nudLine.Value = 0;
                nudMan.Value = 0;
                nudAdm.Value = 0;
                cbManuProc.Enabled = false;
                cbEQManu.Enabled = false;
                cbEQModel.Enabled = false;
                nudSc.Value = 0;
            }
        }

        void __Closed(object sender, FormClosedEventArgs e)
        {
            savesetting(this);
            FCOMMON.Setting.system.Xml.set_Data(this.Name, "FILE", textBox1.Text.Trim());
            FCOMMON.Setting.system.Save();
        }

        void loadsetting(Control ctrls)
        {
            if (ctrls.HasChildren)
            {
                foreach (Control item in ctrls.Controls)
                {
                    loadsetting(item);
                }
            }
            else
            {
                var typestr = ctrls.GetType().ToString();
                if (typestr.Contains("UpDownEdit"))
                {
                    var nud = ctrls.Parent as NumericUpDown;
                    var section = "input_" + this.Name + $"_{crmode}";
                    var value = FCOMMON.Setting.system.Xml.get_Data(section, "nud_" + nud.Name, "0");
                    var n = decimal.Parse(value);
                    if (n >= nud.Minimum) nud.Value = decimal.Parse(value);
                }
            }
        }
        void savesetting(Control ctrls)
        {
            if (ctrls.HasChildren)
            {
                foreach (Control item in ctrls.Controls)
                {
                    savesetting(item);
                }
            }
            else
            {
                var typestr = ctrls.GetType().ToString();
                if (typestr.Contains("UpDownEdit"))
                {
                    var nud = ctrls.Parent as NumericUpDown;
                    var section = "input_" + this.Name + $"{crmode}";
                    FCOMMON.Setting.system.Xml.set_Data(section, "nud_" + nud.Name, nud.Value.ToString());
                }
            }
            FCOMMON.Setting.system.Save();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog od = new OpenFileDialog();
            od.Filter = "excel|*.xls|all files|*.*";
            od.RestoreDirectory = true;
            od.FilterIndex = 1;
            od.RestoreDirectory = true;
            if (od.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            textBox1.Text = od.FileName;
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            var dlg = FCOMMON.Util.MsgQ("데이터의 SID를 ITEM정보와 확인하여 업데이트 합니다.");
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            var i = FCOMMON.DBM.UpdateItemIndexbySID();
            FCOMMON.Util.MsgI(i.ToString() + "건의 자료가 업데이트 되었습니다.");


        }

        private void numericUpDown6_ValueChanged(object sender, EventArgs e)
        {
            var ctl = sender as NumericUpDown;
            if (ctl.Value == 0) ctl.BackColor = Color.Gray;
            else ctl.BackColor = Color.White;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //저장버튼           
            if (this.listView1.Items.Count < 1)
            {
                FCOMMON.Util.MsgE("등록 가능한 자료가 없습니다.\n먼저 자료를 불러오세요");
                return;
            }
            if (this.listView1.CheckedItems == null || this.listView1.CheckedItems.Count < 1)
            {
                FCOMMON.Util.MsgE("선택된 자료가 없습니다. 목록에서 입력할 자료를 선택하세요\n\n메뉴를 보려면 우클릭 하세요");
                return;
            }


            //혀냊 입력된 자료를 적용한다
            var valid = checkCombo();
            if (valid == false) return;

            ////기존자료확인
            //var cnt = ta.CoutImport(dtPdate.Value.ToString("yyyy-MM-dd"), dtPdate.Value.ToString("yyyy-MM-dd"),
            //    FCOMMON.info.Login.no, FCOMMON.info.Login.gcode);
            //if (cnt > 0)
            //{
            //    var dlg = FCOMMON.Util.MsgQ("기존에 등록된 자료가 " + cnt.ToString() + "건 있습니다. 이 자료를 삭제할까요?");
            //    if (dlg == DialogResult.Yes)
            //        ta.DeleteImport(dtPdate.Value.ToString("yyyy-MM-dd"), dtPdate.Value.ToString("yyyy-MM-dd"),
            //    FCOMMON.info.Login.no, FCOMMON.info.Login.gcode);
            //}


            //요청자 번호확인
            //string userNo = this.cmbRequest.Text.Substring(cmbRequest.Text.LastIndexOf('(') + 1);
            //userNo = userNo.Substring(0, userNo.Length - 1);

            //part 목록을 조회해서 NR에 등록해줘야 함
            var dlg2 = FCOMMON.Util.MsgQ($"해당 파트리스트를 ({crmode})구매 목록에 등록 하시겠습니까?\n" +
                listView1.CheckedItems.Count.ToString() + "건");
            if (dlg2 != System.Windows.Forms.DialogResult.Yes) return;



            //체크안된 데이터를 dr에서 삭제한다.
            decimal itemAmt = 0;
            var itemCount = 0;
            var totalcnt = listView1.CheckedItems.Count;
            foreach (ListViewItem lv in this.listView1.Items)
            {
                if (crmode == eImporttype.CR)
                {
                    var dr = lv.Tag as dsPurchase.EETGW_PurchaseCRRow;
                    if (lv.Checked == false) dr.AcceptChanges();
                    else
                    {
                        itemCount += 1;
                        // dr.request = userNo;
                        dr.asset = cbEQModel.Text;
                        dr.dept = cbEQManu.Text;
                        dr.manuproc = cbManuProc.Text;
                        dr.process = cbProcess.Text.Trim();
                        dr.state = cmbState.Text.Trim();
                        // dr.pdate = dtPdate.Value.ToString("yyyy-MM-dd");
                        dr.project = tbProject.Text.Trim();
                        dr.AcceptChanges();
                        dr.SetAdded();
                        itemAmt += dr.pumamt;
                        taCR.Update(dr);
                    }
                }
                else if (crmode == eImporttype.NR)
                {
                    var dr = lv.Tag as dsPurchase.PurchaseRow;
                    if (lv.Checked == false) dr.AcceptChanges();
                    else
                    {
                        itemCount += 1;
                        // dr.request = userNo;
                        dr.asset = cbEQModel.Text;
                        dr.dept = cbEQManu.Text;
                        dr.manuproc = cbManuProc.Text;
                        dr.process = cbProcess.Text.Trim();
                        dr.state = cmbState.Text.Trim();
                        // dr.pdate = dtPdate.Value.ToString("yyyy-MM-dd");
                        dr.project = tbProject.Text.Trim();
                        dr.AcceptChanges();
                        dr.SetAdded();
                        itemAmt += dr.pumamt;

                            taNR.Update(dr);
                      
                         
                    }
                }
                else if (crmode == eImporttype.EB)
                {
                    var dr = lv.Tag as dsPurchase.EETGW_PurchaseEBRow;
                    if (lv.Checked == false) dr.AcceptChanges();
                    else
                    {
                        itemCount += 1;
                        // dr.request = userNo;
                        //dr.asset = cbEQModel.Text;    //안씀
                        //dr.dept = cbEQManu.Text;
                        //dr.manuproc = cbManuProc.Text;
                        dr.process = cbProcess.Text.Trim();
                        dr.state = cmbState.Text.Trim();
                        // dr.pdate = dtPdate.Value.ToString("yyyy-MM-dd");
                        dr.project = tbProject.Text.Trim();
                        dr.AcceptChanges();
                        dr.SetAdded();
                        itemAmt += dr.pumamt;
                        taEB.Update(dr);
                    }
                }

                this.Text = $"데이터 입력중({itemCount}/{totalcnt})";
                System.Threading.Thread.Sleep(500);
                if (itemCount % 10 == 0) System.Windows.Forms.Application.DoEvents();
            }

      

            //if (crmode == eImporttype.CR)
            //    taCR.Update(this.dsPRJ.EETGW_PurchaseCR);
            //else if (crmode == eImporttype.NR)
            //    taNR.Update(this.dsPRJ.Purchase);
            //else if (crmode == eImporttype.EB)
            //    taEB.Update(this.dsPRJ.EETGW_PurchaseEB);

            dsPRJ.AcceptChanges();
            FCOMMON.Util.MsgI("Save OK");
        }

        bool checkCombo()
        {

            if (crmode != eImporttype.CR && cbProcess.Text.isEmpty() == true)
            {
                FCOMMON.Util.MsgE("프로세스를 선택하세요.");
                cbProcess.Focus();
                return false;
            }

            if (crmode != eImporttype.EB && tbProject.Text == "")
            {
                var dlg = FCOMMON.Util.MsgQ("프로젝트가 입력되지 않았습니다. 진행할까요?");
                if (dlg != DialogResult.Yes)
                {
                    tbProject.Focus();
                    return false;
                }
            }
            if (crmode == eImporttype.NR && this.cbProcess.Text.isEmpty() == true)
            {

                {
                    FCOMMON.Util.MsgE("[공정]을 선택하세요\n\n" +
                    "선택 대상이 없는 경우  관리자 문의 바랍니다.");

                    cbProcess.Focus();
                    return false;
                }
            }
            if (crmode == eImporttype.NR && cbManuProc.Text.isEmpty() == true)
            {

                {
                    FCOMMON.Util.MsgE("제조공정을 선택하세요\n\n" +
                    "선택 대상이 없는 경우  관리자 문의 바랍니다.");

                    cbManuProc.Focus();
                    return false;
                }
            }
            if (crmode == eImporttype.NR && this.cbEQManu.Text.isEmpty() == true)
            {

                {
                    FCOMMON.Util.MsgE("장비 제조사를 선택하세요.\n\n" +
                    "선택 대상이 없는 경우  관리자 문의 바랍니다.");
                    cbEQManu.Focus();
                    return false;
                }
            }
            return true;
        }


        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {

            if (textBox1.Text == "")
            {
                FCOMMON.Util.MsgE("파일을 선택하세요");
                textBox1.Focus();
                return;
            }
            if (!System.IO.File.Exists(textBox1.Text))
            {
                FCOMMON.Util.MsgE("입력하신 파일이 존재하지 않습니다.");
                textBox1.Focus();
                textBox1.SelectAll();
                return;
            }

            if (nudPdate.Value < 1 || nudSid.Value < 1 || nudPumName.Value < 1)
            {
                Util.MsgE($"요청일/SID/품명은 반드시 설정되어야 합니다");
                return;
            }



            libxl.Book book;// = new libxl.BinBook();

            if (textBox1.Text.ToLower().EndsWith(".xlsx")) book = new libxl.XmlBook();
            else book = new libxl.BinBook();

            book.setKey(FCOMMON.info.libxlCompany, FCOMMON.info.libxlKey);
            try
            {
                book.load(textBox1.Text);
            }
            catch (System.Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
                return;
            }

            int sheetNum = (int)numericUpDown1.Value;
            if (sheetNum > book.sheetCount())
            {
                FCOMMON.Util.MsgE("입력한 시트 번호는 존재하지 않습니다.");
                book = null;
                return;
            }
            var sheet = book.getSheet(sheetNum - 1);
            var MaxRow = sheet.lastRow();
            var MinRow = sheet.firstRow();

            MaxRow = (int)Math.Min(MaxRow, nudE.Value - 1);
            MinRow = (int)Math.Max(MinRow, nudS.Value - 1);




            this.progressBar1.Value = 0;
            this.progressBar1.Maximum = MaxRow - MinRow + 1;
            this.listView1.Items.Clear();
            this.listView1.Visible = false;

            this.dsPRJ.Clear();
            this.dsPRJ.AcceptChanges();

            var db = new DataClasses1DataContext();
            decimal sumamt = 0;
            try
            {


                System.Text.StringBuilder sb = new StringBuilder();
                for (int r = MinRow; r <= MaxRow; r++)
                {
                    progressBar1.Value += 1;

                    string SID = string.Empty;
                    string SC = string.Empty;
                    string CRCF = string.Empty;
                    string 품명 = string.Empty;
                    string 규격 = string.Empty;
                    string 수량 = string.Empty;
                    string 단위 = string.Empty;
                    string 단가 = string.Empty;
                    string 공급처 = string.Empty;
                    string PO = string.Empty;
                    string 비고 = string.Empty;

                    string 요청일 = string.Empty;
                    string 입고일 = string.Empty;

                    string 요청인 = string.Empty;
                    string 수령인 = string.Empty;
                    string CostCode = string.Empty;
                    string LIneCode = string.Empty;
                    string 구매담당 = string.Empty;
                    string 구매승인 = string.Empty;

                    var cf_qty = sheet.cellType(r, (int)nudQty.Value - 1);
                    var cf_price = sheet.cellType(r, (int)nudPrice.Value - 1);
                    var cf_sid = sheet.cellType(r, (int)nudSid.Value - 1);

                    //필수값을 먼저 확인한다.
                    if (nudSid.Value > 0)
                    {
                        if (cf_sid == libxl.CellType.CELLTYPE_NUMBER)
                            SID = sheet.readNum(r, (int)nudSid.Value - 1).ToString();
                        else if (cf_sid == libxl.CellType.CELLTYPE_STRING)
                            SID = sheet.readStr(r, (int)nudSid.Value - 1).Replace(",", "").Trim();
                    }
                    if (nudSc.Value > 0) SC = sheet.readStr(r, (int)this.nudSc.Value - 1).Trim();
                    if (nudCr.Value > 0) CRCF = sheet.readStr(r, (int)this.nudCr.Value - 1).Trim();
                    //if (nudRecev.Value > 0) 수령 = sheet.readStr(r, (int)nudRecev.Value - 1).Trim();
                    if (nudPumName.Value > 0) 품명 = sheet.readStr(r, (int)this.nudPumName.Value - 1).Replace(",", "").Trim();
                    if (nudScale.Value > 0) 규격 = sheet.readStr(r, (int)nudScale.Value - 1).Trim();

                    var cf_요청일 = sheet.cellType(r, (int)nudPdate.Value - 1);
                    var cf_입고일 = sheet.cellType(r, (int)nudInDate.Value - 1);


                    if (nudPdate.Value > 0)
                    {
                        if (cf_요청일 == libxl.CellType.CELLTYPE_STRING)
                        {
                            int yy, mm, dd;
                            yy = DateTime.Now.Year;
                            mm = dd = 0;

                            요청일 = sheet.readStr(r, (int)nudPdate.Value - 1).Trim().Replace(" ", "");
                            var orgstr = 요청일;
                            if (요청일.Contains("월"))
                            {
                                var daybuf = 요청일.Split('월');
                                if (daybuf[0].Contains("년"))
                                {
                                    var daybuf2 = daybuf[0].Split('년');
                                    if (int.TryParse(daybuf2[0], out yy) == false) yy = 0;
                                    else
                                    {
                                        if (yy < 2000) yy += 2000;
                                    }
                                    if (int.TryParse(daybuf2[1], out mm) == false) mm = 0;
                                }
                                else
                                {
                                    if (int.TryParse(daybuf[0], out mm) == false) mm = 0;
                                    if (int.TryParse(daybuf[1].Replace("일", ""), out dd) == false) dd = 0;
                                }
                                if (mm == 0 || dd == 0 || yy == 0)
                                    요청일 = orgstr;
                                else 요청일 = string.Format("{0:0000}-{1:00}-{2:00}", yy, mm, dd);

                            }
                        }
                        else if (cf_요청일 == libxl.CellType.CELLTYPE_NUMBER)
                        {
                            요청일 = sheet.readNum(r, (int)nudPdate.Value - 1).ToString();
                            int y, m, d;
                            y = m = d = 0;
                            book.dateUnpack(double.Parse(요청일), ref y, ref m, ref d);
                            요청일 = string.Format("{0:0000}-{1:00}-{2:00}", y, m, d);
                        }
                    }

                    if (nudInDate.Value > 0)
                    {
                        if (cf_입고일 == libxl.CellType.CELLTYPE_STRING)
                        {
                            입고일 = sheet.readStr(r, (int)nudInDate.Value - 1).Trim();
                            if (DateTime.TryParse(입고일, out DateTime indatevalue) == false)
                            {
                                sb.AppendLine("입고일을 확인할 수 없어 입력하지 않습니다\n" +
                                    $"줄번호:{r},입고일자료:{입고일}");
                                continue;
                            }
                            else
                            {
                                입고일 = indatevalue.ToString("yyyy-MM-dd");
                            }
                        }
                        else if (cf_입고일 == libxl.CellType.CELLTYPE_NUMBER)
                        {
                            입고일 = sheet.readNum(r, (int)nudInDate.Value - 1).ToString();
                            int y, m, d;
                            y = m = d = 0;
                            book.dateUnpack(double.Parse(입고일), ref y, ref m, ref d);
                            입고일 = string.Format("{0:0000}-{1:00}-{2:00}", y, m, d);
                        }
                    }

                    요청인 = sheet.readStr(r, (int)nudReq.Value - 1).Trim();
                    수령인 = sheet.readStr(r, (int)nudRecv.Value - 1).Trim();

                    if (요청인.isEmpty() == false)
                    {
                        var requser = db.vGroupUser.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.name == 요청인).FirstOrDefault();
                        if (requser != null) 요청인 = requser.id;
                    }
                    if (수령인.isEmpty() == false)
                    {
                        var requser = db.vGroupUser.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.name == 수령인).FirstOrDefault();
                        if (requser != null) 수령인 = requser.id;
                    }
                    //먼저 숫자로 읽어보낟                    
                    if (nudQty.Value > 0)
                    {
                        if (cf_qty == libxl.CellType.CELLTYPE_NUMBER)
                            수량 = sheet.readNum(r, (int)nudQty.Value - 1).ToString("N0").Replace(",", "").Trim();
                        else if (cf_qty == libxl.CellType.CELLTYPE_STRING)
                            수량 = sheet.readStr(r, (int)nudQty.Value - 1).Replace(",", "").Trim();
                    }
                    if (nudUnit.Value > 0) 단위 = sheet.readStr(r, (int)nudUnit.Value - 1).Trim();
                    if (nudPrice.Value > 0)
                    {
                        if (cf_price == libxl.CellType.CELLTYPE_NUMBER)
                            단가 = sheet.readNum(r, (int)nudPrice.Value - 1).ToString("N0");
                        else if (cf_price == libxl.CellType.CELLTYPE_STRING)
                            단가 = sheet.readStr(r, (int)nudPrice.Value - 1).Replace(",", "").Trim();
                    }
                    if (nudSupplty.Value > 0) 공급처 = sheet.readStr(r, (int)nudSupplty.Value - 1).Trim();
                    if (nudPo.Value > 0) PO = sheet.readStr(r, (int)nudPo.Value - 1).Trim();
                    if (nudMemo.Value > 0) 비고 = sheet.readStr(r, (int)nudMemo.Value - 1).Trim();


                    if (nudCost.Value > 0) CostCode = sheet.readStr(r, (int)nudCost.Value - 1).Trim();
                    if (nudLine.Value > 0) LIneCode = sheet.readStr(r, (int)nudLine.Value - 1).Trim();

                    if (nudMan.Value > 0) 구매담당 = sheet.readStr(r, (int)nudMan.Value - 1).Trim();
                    if (nudAdm.Value > 0) 구매승인 = sheet.readStr(r, (int)nudAdm.Value - 1).Trim();


                    //sid 공백과 - _ 제거  200506
                    SID = SID.Replace(" ", "").Replace("-", "").Replace("_", "").Trim();

                    //필수자료갸ㅏ 없는 경우처리하지 않음
                    if (품명.Trim() == "") continue;

                    int d_qty = 0;
                    decimal d_price = 0;
                    decimal d_amt = 0;

                    if (단가 != "") d_price = decimal.Parse(단가);
                    if (수량 != "") d_qty = int.Parse(수량);
                    d_amt = d_price * d_qty;

                    var v_공급처 = string.Empty;
                    var v_공급처코드 = -1;
                    if (공급처 != "")
                    {
                        int idx;
                        string nameK, nameE;
                        if (FCOMMON.DBM.getFindSupply(공급처, out idx, out nameK, out nameE))
                        {
                            v_공급처 = nameK;
                            v_공급처코드 = idx;
                        }
                        else v_공급처 = 공급처;
                    }

                    if (품명.Length >= 200) 품명 = 품명.Substring(0, 200 - 4) + "...";
                    if (비고.Length >= 500) 비고 = 비고.Substring(0, 500 - 4) + "...";
                    if (규격.Length >= 200) 규격 = 규격.Substring(0, 200 - 4) + "...";

                    요청일 = (요청일.Replace(" ", ""));
                    요청인 = (요청인.Replace(" ", ""));
                    SID = (SID.Replace(" ", ""));
                    단위 = (단위.Replace(" ", ""));
                    v_공급처 = (v_공급처.Replace(" ", ""));
                    PO = (PO.Replace(" ", ""));
                    SC = (SC.Replace(" ", ""));
                    CRCF = (CRCF.Replace(" ", ""));
                    입고일 = (입고일.Replace(" ", ""));
                    수령인 = (수령인.Replace(" ", ""));
                    CostCode = (CostCode.Replace(" ", ""));
                    LIneCode = (LIneCode.Replace(" ", ""));
                    구매담당 = (구매담당.Replace(" ", ""));
                    구매승인 = (구매승인.Replace(" ", ""));

                    //리스트뷰에 추가
                    var newitem = this.listView1.Items.Add(요청일);
                    newitem.Checked = false;

                    newitem.SubItems.Add(요청인);
                    newitem.SubItems.Add(SID);
                    newitem.SubItems.Add(품명);
                    newitem.SubItems.Add(규격);
                    newitem.SubItems.Add(d_qty.ToString());
                    newitem.SubItems.Add(단위);
                    newitem.SubItems.Add(d_price.ToString());
                    newitem.SubItems.Add(d_amt.ToString());
                    newitem.SubItems.Add(v_공급처);
                    newitem.SubItems.Add(비고);

                    newitem.SubItems.Add(PO);
                    newitem.SubItems.Add(SC);
                    newitem.SubItems.Add(CRCF);

                    newitem.SubItems.Add(입고일);
                    newitem.SubItems.Add(수령인);
                    newitem.SubItems.Add(CostCode);
                    newitem.SubItems.Add(LIneCode);

                    newitem.SubItems.Add(구매담당);
                    newitem.SubItems.Add(구매승인);

                    //데이터도 추가를 해준다
                    if (crmode == eImporttype.CR)
                    {
                        var newdr = this.dsPRJ.EETGW_PurchaseCR.NewEETGW_PurchaseCRRow();
                        newdr.wuid = FCOMMON.info.Login.no;
                        newdr.wdate = DateTime.Now;
                        newdr.gcode = FCOMMON.info.Login.gcode;
                        newdr.sc = SC;
                        newdr.orderno = CRCF;
                        newdr.sid = SID;
                        newdr.pumname = 품명;
                        newdr.pumscale = 규격;
                        newdr.pumqty = d_qty;
                        newdr.pumprice = d_price;
                        newdr.pumamt = d_amt;
                        newdr.supply = v_공급처;
                        newdr.supplyidx = v_공급처코드;
                        newdr.po = PO;
                        newdr.bigo = 비고;
                        newdr.indate = 입고일;
                        newdr.pdate = 요청일;
                        newdr.request = 요청인;
                        newdr.receive = 수령인;
                        newdr.import = true;
                        newdr.costcenter = CostCode;
                        newdr.linecode = LIneCode;
                        newdr.purchase_manager = 구매담당;
                        newdr.purchase_admin = 구매승인;
                        newitem.Tag = newdr;
                        this.dsPRJ.EETGW_PurchaseCR.AddEETGW_PurchaseCRRow(newdr);
                    }
                    else if (crmode == eImporttype.NR)
                    {
                        var newdr = this.dsPRJ.Purchase.NewPurchaseRow();
                        newdr.wuid = FCOMMON.info.Login.no;
                        newdr.wdate = DateTime.Now;
                        newdr.gcode = FCOMMON.info.Login.gcode;
                        newdr.sc = SC;
                        newdr.orderno = CRCF;
                        newdr.sid = SID;
                        newdr.pumname = 품명;
                        newdr.pumscale = 규격;
                        newdr.pumqty = d_qty;
                        newdr.pumprice = d_price;
                        newdr.pumamt = d_amt;
                        newdr.supply = v_공급처;
                        newdr.supplyidx = v_공급처코드;
                        newdr.po = PO;
                        newdr.bigo = 비고;
                        newdr.indate = 입고일;
                        newdr.pdate = 요청일;
                        newdr.request = 요청인;
                        newdr.receive = 수령인;
                        newdr.import = true;
                        newdr.costcenter = CostCode;
                        newdr.linecode = LIneCode;
                        newdr.purchase_manager = 구매담당;
                        newdr.purchase_admin = 구매승인;
                        newitem.Tag = newdr;
                        this.dsPRJ.Purchase.AddPurchaseRow(newdr);
                    }
                    else if (crmode == eImporttype.EB)
                    {
                        var newdr = this.dsPRJ.EETGW_PurchaseEB.NewEETGW_PurchaseEBRow();
                        newdr.wuid = FCOMMON.info.Login.no;
                        newdr.wdate = DateTime.Now;
                        newdr.gcode = FCOMMON.info.Login.gcode;
                        newdr.sc = SC;
                        newdr.orderno = CRCF;
                        newdr.sid = SID;
                        newdr.pumname = 품명;
                        newdr.pumscale = 규격;
                        newdr.pumqty = d_qty;
                        newdr.pumprice = d_price;
                        newdr.pumamt = d_amt;
                        newdr.supply = v_공급처;
                        newdr.supplyidx = v_공급처코드;
                        newdr.po = PO;
                        newdr.bigo = 비고;
                        newdr.indate = 입고일;
                        newdr.pdate = 요청일;
                        newdr.request = 요청인;
                        newdr.receive = 수령인;
                        newdr.import = true;
                        newdr.costcenter = CostCode;
                        newdr.linecode = LIneCode;
                        newdr.purchase_manager = 구매담당;
                        newdr.purchase_admin = 구매승인;
                        newitem.Tag = newdr;
                        this.dsPRJ.EETGW_PurchaseEB.AddEETGW_PurchaseEBRow(newdr);
                    }
                    sumamt += d_amt;

                }
                //this.dsPRJ.ProjectsPart.AcceptChanges();
                if (sb.Length > 0)
                {
                    Util.MsgE(sb.ToString());
                }
            }
            catch (System.Exception ex)
            {
                FCOMMON.Util.MsgE("불러오는 중 오류 발생\n" + ex.Message);
            }
            //
            book = null;

            sbSum.Text = $"합계:{sumamt:N0}원,{this.dsPRJ.EETGW_PurchaseEB.Rows.Count}건";
            //this.bs.DataSource = dt;
            //this.bn.BindingSource = this.bs;
            //this.dataGridView1.AutoGenerateColumns = true;
            //this.dataGridView1.DataSource = this.bs;
            this.listView1.Visible = true;
            //this.listView1.AutoResizeColumns();

            if (this.listView1.Items.Count < 1)
            {
                FCOMMON.Util.MsgE("입력된 자료가 없습니다.\n\n지정된 엑셀의 1번째 칸에 값이 없다면 입력되지 않습니다.");
            }

        }

        private void 전체선택ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in this.listView1.Items)
                item.Checked = true;
        }

        private void 모두해제ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in this.listView1.Items)
                item.Checked = false;
        }

        private void 선택반전ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in this.listView1.Items)
                item.Checked = !item.Checked;
        }

        private void cbEQManu_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (bsModel == null) return;
            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 linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var file = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sample_purchase.xls");
            if (System.IO.File.Exists(file) == false)
            {
                FCOMMON.Util.MsgE("샘플파일이 없습니다. 개발자 문의 바람");
                return;
            }
            this.textBox1.Text = file;
            FCOMMON.Util.RunExplorer(file);
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void nudSc_TabIndexChanged(object sender, EventArgs e)
        {

        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var idx = 1;
            nudPdate.Value = idx++;
            nudReq.Value = idx++;
            nudSid.Value = idx++;
            nudPumName.Value = idx++;
            nudScale.Value = idx++;
            nudQty.Value = idx++;
            nudUnit.Value = idx++;
            nudPrice.Value = idx++;
            idx++;//nudAmkt.Value = 6;
            nudSupplty.Value = idx++;
            nudMemo.Value = idx++;
            nudPo.Value = idx++;
            nudSc.Value = idx++;
            nudCr.Value = idx++;
            nudInDate.Value = idx++;
            nudRecv.Value = idx++;
            nudCost.Value = idx++;
            nudLine.Value = idx++;
            nudMan.Value = idx++;
            nudAdm.Value = idx++;

            if (this.crmode == eImporttype.EB)
            {
                nudPo.Value = 0;
                nudCr.Value = 0;
                //nudInDate.Value = 0;
                nudRecv.Value = 0;
                nudCost.Value = 0;
                nudLine.Value = 0;
                nudMan.Value = 0;
                nudAdm.Value = 0;
                cbManuProc.Enabled = false;
                cbEQManu.Enabled = false;
                cbEQModel.Enabled = false;
                nudSc.Value = 0;
            }

        }

        private void label25_Click(object sender, EventArgs e)
        {

        }
    }
}
