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 fImpEquipment : fBase
    {
        DataTable dt = null;
        DataTable dtExcel = new DataTable();
        // fEquipment.eTabletype imptype = fEquipment.eTabletype.MOLD;
        public fImpEquipment(fEquipment.eTabletype type_)
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            Properties.Settings.Default["EEEntities"] = FCOMMON.info.CS;

            this.FormClosed += __Closed;
            dt = new dsEQ.EETGW_EquipmentDataTable();
        }
        
        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize ();
            this.Text = string.Format("Data Import({0})", "ALL");
            var form = this as Form;
            FCOMMON.Util.SetFormStatus(ref form, this.Name, true);
            this.Show();
            Application.DoEvents();

            //권하니없으면 button3을 막는다
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.equipment));
            if (curLevel >= 5)
            {
                button3.Enabled = true;
            }
            else
            {
                button3.Enabled = false;
            }

        }

        void __Closed(object sender, FormClosedEventArgs e)
        {
            var form = this as Form;
            FCOMMON.Util.SetFormStatus(ref form, this.Name, false);
        }

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

        private string[] getCSVFormat(string line)
        {
            List<string> datas = new List<string>();
            var charlist = line.ToCharArray();
            // int c = 0;
            System.Text.StringBuilder sb = new StringBuilder();
            Boolean findCom = false;
            foreach (var ch in charlist)
            {
                if (ch == '"')
                {
                    if (findCom == false)
                        findCom = true;
                    else findCom = false;
                }
                else if (ch == ',')
                {
                    if (findCom)
                    {
                        sb.Append(ch);
                    }
                    else
                    {
                        datas.Add(sb.ToString());
                        sb.Clear();
                        findCom = false;
                    }

                }
                else sb.Append(ch);
            }
            return datas.ToArray();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            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();

            libxl.Book book;// = new libxl.BinBook();
            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)numericUpDown1.Value;
            if (sheetNum >= book.sheetCount())
            {
                FCOMMON.Util.MsgE("입력한 시트 번호는 존재하지 않습니다.");
                book = null;
                return;
            }
            var sheet = book.getSheet(sheetNum);
            var MaxRow = sheet.lastRow();
            var MinRow = sheet.firstRow();
            var MaxCol = sheet.lastCol();
            var MinCol = sheet.firstCol();
            List<string> cols = new List<string>();
            bool firstRow = true;
            try
            {
                for (int r = MinRow; r <= MaxRow; r++)
                {
                    DataRow dr = null;
                    if (firstRow == false) dr = dtExcel.NewRow();

                    Boolean nullColumn = false;
                    for (int c = MinCol; c <= MaxCol; c++)
                    {
                        var strVallue = sheet.readStr(r, c);
                        if (strVallue.isEmpty() && c == MinCol)
                        {
                            //첫줄 첫행이 빈값이면 처리하지 않는다.
                            nullColumn = true;
                            break;
                        }
                        if (firstRow)
                        {
                            cols.Add(strVallue);
                            this.dtExcel.Columns.Add(strVallue);
                        }
                        else
                        {
                            if (!cols[c].isEmpty())
                                dr[cols[c]] = strVallue;
                        }
                    }
                    if (nullColumn) continue; //줄처리를 못한 경우 넘어감
                    if (firstRow) firstRow = false;
                    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 button2_Click(object sender, EventArgs e)
        {
            var ta = new dsEQTableAdapters.LineCodeTableAdapter();
            var lineTd = ta.GetData(FCOMMON.info.Login.gcode);
            lineTd.AcceptChanges();
            //12,13
            foreach (DataRow dr in dt.Rows)
            {
                var linecode = dr[12].ToString();
                var linedesc = dr[13].ToString();
                var codeDrows = lineTd.Select("code='" + linecode + "'");
                if (codeDrows.Length == 0)
                {
                    var newdr = lineTd.NewLineCodeRow();
                    newdr.code = linecode;
                    newdr.memo = linedesc;
                    var linebuf = linedesc.Split('-');
                    if (linebuf.Length > 1)
                    {
                        newdr.team = linebuf[0];
                        newdr.part = linebuf[1];
                    }
                    else
                    {
                        newdr.team = linedesc;
                    }

                    newdr.wuid = FCOMMON.info.Login.no;
                    newdr.wdate = DateTime.Now;
                    lineTd.AddLineCodeRow(newdr);
                }
            }
            ta.Update(lineTd);
            lineTd.AcceptChanges();
            FCOMMON.Util.MsgE("test");

        }

        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("등록일 : " + dateTimePicker1.Value.ToString("yyyy-MM-dd"));
            sb.AppendLine();
            sb.AppendLine("'저장 완료' 메세지가 나올때 까지 기다려 주세요.");
            sb.AppendLine();
            sb.AppendLine("실행 하려면 '예' 를 누르세요");
            var dlg = FCOMMON.Util.MsgQ(sb.ToString());
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;



            //라인코드를 읽어서 값을 기록해준다.
            var taLine = new dsEQTableAdapters.LineCodeTableAdapter();
            var lineTd = taLine.GetData(FCOMMON.info.Login.gcode);
            lineTd.AcceptChanges();

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

            var dateStr = this.dateTimePicker1.Value.ToString("yyyy-MM-dd");
            this.progressBar1.Value = 0;
            this.progressBar1.Maximum = dtExcel.Rows.Count;

            //기존자료삭제코드
            dlg = FCOMMON.Util.MsgQ("기존에 등록된 자료를 삭제할까요?\n자료를 추가하려면 아니오를 클릭하세요");
            if (dlg == DialogResult.Yes)
            {
                var taE = new dsEQTableAdapters.EETGW_EquipmentTableAdapter();
                taE.DeleteData(dateStr, FCOMMON.info.Login.gcode);
            }

            //12,13
            var i = 0;
            foreach (DataRow dr in dtExcel.Rows)
            {
                this.progressBar1.Value += 1;
                i += 1;
                if (i % 1000 == 0) Application.DoEvents();

                var version = dr[11].ToString();
                var linecode = dr[12 + 1].ToString();
                var linedesc = dr[13 + 1].ToString();
                var lineT = string.Empty;
                var lineP = string.Empty;
                var grp2 = string.Empty;
                var rcsflag = dr[1].ToString();
                //if (rcsflag != "M") continue;

                //if (linecode.StartsWith("AJ900T")) continue;    //해외장비 제거
                //if (linecode.StartsWith("AJ9000E")) continue;    //해외장비 제거
                //if (linecode.StartsWith("AJ9000S")) continue;    //해외장비 제거

                //if (linecode.StartsWith("AF900T")) continue;    //해외장비 제거
                //if (linecode.StartsWith("AF9000E")) continue;    //해외장비 제거
                //if (linecode.StartsWith("AF9000S")) continue;    //해외장비 제거

                //if (linecode.StartsWith("AS900T")) continue;    //해외장비 제거
                //if (linecode.StartsWith("AS9000E")) continue;    //해외장비 제거
                //if (linecode.StartsWith("AS9000S")) continue;    //해외장비 제거


                //팀파트정보는 이걸로 쓴다  210412 - 진재훈
                //파일의 정보를 기준으로 생성하게한다.
                var linebuf = linedesc.Split('-');
                if (linebuf.Length > 1)
                {
                    lineT = linebuf[0];
                    lineP = linebuf[1];
                }
                else
                {
                    lineT = linedesc;
                    lineP = string.Empty;
                }

                //없는 라인코드는 추가
                var lineDrows = lineTd.Select("code='" + linecode + "'");
                if (lineDrows.Length == 0)  //라인코드가 없다.
                {
                    //var linebuf = linedesc.Split('-');


                    //신규추가한다.
                    var newli = lineTd.NewLineCodeRow();
                    newli.code = linecode;
                    newli.gcode = FCOMMON.info.Login.gcode;
                    newli.team = lineT;
                    newli.part = lineP;
                    newli.memo = linedesc;
                    newli.except = false;
                    newli.wuid = FCOMMON.info.Login.no;
                    newli.wdate = DateTime.Now;
                    lineTd.AddLineCodeRow(newli);
                }
                else
                {
                    var lineDr = lineDrows[0] as dsEQ.LineCodeRow;
                    //lineT = lineT;// lineDr.team;
                    //lineP = lineDr.part;
                    grp2 = lineDr.grp2;

                }

                //데이터추가
                var newdr = dt.NewRow();
                newdr["pdate"] = dateTimePicker1.Value.ToString("yyyy-MM-dd");
                newdr["asset"] = dr[6].ToString();
                newdr["grp"] = dr[0].ToString();
                newdr["type"] = dr[2].ToString();
                newdr["model"] = dr[3].ToString();
                newdr["linecode"] = linecode;
                newdr["lineT"] = lineT;
                newdr["lineP"] = lineP;
                newdr["grp2"] = grp2;
                newdr["serial"] = dr[7].ToString();
                newdr["manu"] = dr[9].ToString();
                newdr["primary"] = true;
                newdr["wuid"] = FCOMMON.info.Login.no;
                newdr["wdate"] = DateTime.Now;
                newdr["except"] = false;
                newdr["memo"] = string.Empty;
                newdr["flag"] = rcsflag;  //rcs flag  210325
                newdr["version"] = version; //210810
                newdr["gcode"] = FCOMMON.info.Login.gcode;

                if (grp2.ToUpper() == "BUMP") newdr["param1"] = "8\"";
                else newdr["param1"] = string.Empty;
                dt.Rows.Add(newdr);
            }

            taLine.Update(lineTd);
            lineTd.AcceptChanges();

            var taO = new dsEQTableAdapters.EETGW_EquipmentTableAdapter();
            //taI.DeleteData(dateStr);
            taO.Update((dsEQ.EETGW_EquipmentDataTable)dt);


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