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 fMaterial_Import : fBase
    {
        DataTable dt = new dsMSSQL.ItemsDataTable();// dsPurchase.PurchaseDataTable();
        DataTable dtExcel = new DataTable();
        public fMaterial_Import()
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            this.FormClosed += __Closed;
        }

        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();

        }
      
        void __Closed(object sender, FormClosedEventArgs e)
        {

        }

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

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

        private void button1_Click(object sender, EventArgs e)
        {
            int ColumnNameNo = (int)numericUpDown2.Value;
            if (textBox1.Text.isEmpty())
            {
                FCOMMON.Util.MsgE("파일을 선택하세요");
                textBox1.Focus();
                return;
            }
            if (!System.IO.File.Exists(textBox1.Text))
            {
                FCOMMON.Util.MsgE("입력하신 파일이 존재하지 않습니다.");
                textBox1.Focus();
                textBox1.SelectAll();
                return;
            }

            dtExcel.Columns.Clear();
            dtExcel.Rows.Clear();
            dtExcel.AcceptChanges();



            dtExcel.Columns.Add("Cate");
            dtExcel.Columns.Add("SID");
            dtExcel.Columns.Add("Name");
            //dtExcel.Columns.Add("Model");
            dtExcel.Columns.Add("Unit");
            dtExcel.Columns.Add("Disable");


            if (book == null)
            {
                book = new libxl.XmlBook();
                book.setKey(FCOMMON.info.libxlCompany, FCOMMON.info.libxlKey);
            }

            try
            {
                book.load(textBox1.Text);
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
                return;
            }

            int sheetNum = (int)nudSheetNo.Value;
            if (sheetNum >= book.sheetCount())
            {
                FCOMMON.Util.MsgE("입력한 시트 번호는 존재하지 않습니다.");
                book = null;
                return;
            }
            var sheet = book.getSheet(sheetNum);
            var MaxRow = sheet.lastRow();
            var MinRow = sheet.firstRow();
            if (MaxRow > nudE.Maximum)
            {
                nudE.Maximum = MaxRow;
                nudS.Maximum = MaxRow;
            }
            nudE.Value = MaxRow; //엑셀에서읽어지는 최대값을 설정

            MinRow = (int)Math.Max(MinRow, this.nudDispRowMin.Value - 1);
            MaxRow = (int)Math.Min(MaxRow, this.nudDispRowMax.Value - 1);

            if (MinRow <= (ColumnNameNo - 1))
            {
                FCOMMON.Util.MsgI("시작줄을 제목줄 보다 커야 합니다. 자동으로 +1 증가합니다.");
                MinRow = ColumnNameNo;
                nudS.Value = MinRow;
            }


            var MaxCol = sheet.lastCol();
            var MinCol = sheet.firstCol();

            MaxCol = (int)Math.Min(MaxCol, nudCE.Value - 1);
            MinCol = (int)Math.Max(MinCol, nudCS.Value - 1);

            //제목줄을 처리한다.  181029
            List<string> cols = new List<string>();

            try
            {
                for (int r = MinRow; r <= MaxRow; r++)
                {

                    var v_sid = sheet.readStr(r, 0);
                    var v_name = sheet.readStr(r, 1);
                    var v_cate = sheet.readStr(r, 2);
                    var v_del = sheet.readStr(r, 3);
                    var v_unit = sheet.readStr(r, 4);
      

                    //이름이나 sid가없으면 처리하지 않음
                    if (v_name.Trim() == "") continue; //품명과 sid 없는 건 제외
                    if (v_sid.Trim() == "") continue;

                    DataRow dr = dtExcel.NewRow();
                    dr["sid"] = v_sid;
                    dr["name"] = v_name;
                    dr["cate"] = v_cate;
                    dr["disable"] = v_del;
                    dr["unit"] = v_unit;
 

                    //dr["memo"] = v_memo;

                    if (dr != null)
                    {
                        dtExcel.Rows.Add(dr);
                    }
                }
                dtExcel.AcceptChanges();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("불러오는 중 오류 발생\n" + ex.Message);
            }
            //
            // book = null;

            this.bs.DataSource = dtExcel;
            this.dataGridView1.DataSource = dtExcel;
            this.bn.BindingSource = this.bs;

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


        private void button3_Click(object sender, EventArgs e)
        {
            //if (dtExcel == null || dtExcel.Rows.Count < 1)
            //{
            //    FCOMMON.Util.MsgE("등록 가능한 자료가 없습니다.");
            //    return;
            //}

            System.Text.StringBuilder sb = new StringBuilder();
            sb.AppendLine("다음 자료를 추가하시겠습니까?");
            sb.AppendLine();
            sb.AppendLine("'저장 완료' 메세지가 나올때 까지 기다려 주세요.");
            sb.AppendLine();
            sb.AppendLine("실행 하려면 '예' 를 누르세요");
            var dlg = FCOMMON.Util.MsgQ(sb.ToString());
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;


            dt.Clear();
            dt.AcceptChanges();

            this.progressBar1.Value = 0;
            this.progressBar1.Maximum = (int)nudE.Value; // dtExcel.Rows.Count;
            if (checkBox1.Checked) ta.DeleteImport(textBox2.Text, FCOMMON.info.Login.gcode);

            int cnt = 0;
            int err = 0;
      

            try
            {
                var sheet = book.getSheet((int)nudSheetNo.Value);
                var MinRow = (int)nudS.Value;
                var MaxRow = (int)nudE.Value;
                for (int r = MinRow; r <= MaxRow; r++)
                {

                    cnt += 1;
                    if (this.progressBar1.Value < this.progressBar1.Maximum)
                        this.progressBar1.Value += 1;

                    //화면 업데이트
                    this.Text = string.Format("{0}/{1} : {2:N2}% ", 
                        r, MaxRow,
                        ((progressBar1.Value * 1.0) / progressBar1.Maximum) * 100.0);

                    //if(cnt % 2 == 0)
                    Application.DoEvents();

                    var v_sid = sheet.readStr(r, 0).Trim();
                    var v_name = sheet.readStr(r, 1).Trim();
                    var v_cate = sheet.readStr(r, 2).Trim();
                    var v_del = sheet.readStr(r, 3).Trim() == "X";
                    var v_unit = sheet.readStr(r, 4).Trim();
                    //var v_model = sheet.readStr(r, 5).Trim();

                    //이름이나 sid가없으면 처리하지 않음
                    if (v_name.Trim() == "") continue; //품명과 sid 없는 건 제외
                    if (v_sid.Trim() == "") continue;
          
                    try
                    {
                        cnt += this.ta.UpdateItem(FCOMMON.info.Login.gcode, v_sid, v_name, v_cate, v_del, v_unit);
                    }
                    catch
                    {
                        err += 1;
                    }


                    //Application.DoEvents();
                    //DataRow dr = dtExcel.NewRow();
                    //dr["sid"] = v_sid;
                    //dr["delete"] = v_del;
                    //dr["name"] = v_name;
                    //dr["model"] = v_model;
                    //dr["unit"] = v_cate;
                    //dr["memo"] = v_memo;

                    //실제 추가한다
                }
                FCOMMON.Util.MsgI("Save OK\n전체:" + cnt.ToString() + "\n에러:" + err.ToString());

            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("불러오는 중 오류 발생\n" + ex.Message);
            }

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

    }
}
