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 FPJ0000.JobReport_
{
    public partial class fJobReportImport : fBase
    {
        DataTable dt = new dsPRJ.JobReportDataTable();
        DataTable dtExcel = new DataTable();
        public fJobReportImport()
        {
            InitializeComponent();
            this.FormClosed += __Closed;
        }

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

            //담당자목록

            var dt_users = FCOMMON.DBM.getActiveUserTable();// getGroupList("name + '(' + id + ')'", "Users", "[level] > 0 and [level] <
                                                      //10", false, false);

            var newdr = dt_users.NewRow();
            newdr["id"] = "--";
            newdr["name"] = "전체";
            newdr["dispName"] = "--전체--";
            dt_users.Rows.Add(newdr);
            dt_users.AcceptChanges();

            this.cmbUser.DisplayMember = "dispName";
            this.cmbUser.ValueMember = "id";
            this.cmbUser.DataSource = dt_users;
            this.cmbUser.SelectedValue = "--";
        }

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

        /// sd = "";
       // string ed = "";
        private void button1_Click(object sender, EventArgs e)
        {

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



            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();

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


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



            //현재 자료 모두 삭제
            this.dsPRJ.JobReport.Clear();
            this.dsPRJ.JobReport.AcceptChanges();
            var dt_users = FCOMMON.DBM.getActiveUserTable();
            var unknownlist = new List<string>();
            try
            {
                for (int r = MinRow; r <= MaxRow; r++)
                {
                    var dr = this.dsPRJ.JobReport.NewJobReportRow();
                    dr.wdate = DateTime.Now;
                    dr.import = true;
                    dr.wuid = "dev";
                    dr.gcode = FCOMMON.info.Login.gcode;
                    dr.pidx = -1;

                    //날짜읽기
                    var colidx = 0;//
                    if (nudMon.Value > 0 && nuddate.Value > 0)   //월이 지정되 ㄴ경우
                    {
                        var colidxm = (int)(nudMon.Value - 1);
                        colidx = (int)(nuddate.Value - 1);

                        var monstr = sheet.readStr(r, colidxm);
                        var dayval = sheet.readNum(r, colidx);
                        var daystr = string.Format("{0}-{1}-{2}", DateTime.Now.Year, monstr, dayval);
                        var dt = DateTime.Parse(daystr);
                        dr.pdate = dt.ToString("yyyy-MM-dd");
                    }
                    else if (nuddate.Value > 0)
                    {
                        colidx = (int)(nuddate.Value - 1);
                        if (sheet.isDate(r, colidx))
                        {
                            var datevalue = sheet.readNum(r, colidx);
                            int y, m, d;
                            y = m = d = 0;
                            book.dateUnpack(datevalue, ref y, ref m, ref d);
                            dr.pdate = string.Format("{0:0000}-{1:00}-{2:00}", y, m, d);
                        }
                        else
                        {
                            dr.pdate = sheet.readStr(r, colidx);
                            var spldat = dr.pdate.Split('/');
                            if (spldat.Length == 2)
                            {
                                dr.pdate = DateTime.Now.Year.ToString("0000") + "-" + spldat[0].PadLeft(2, '0') + "-" + spldat[1].PadLeft(2, '0');
                            }
                        }
                    }

                    //요청
                    if (nudreq.Value > 0)
                    {
                        colidx = (int)(nudreq.Value - 1);
                        dr.requestpart = sheet.readStr(r, colidx);
                    }

                    //패키지
                    if (nudpack.Value > 0)
                    {
                        colidx = (int)(nudpack.Value - 1);
                        dr.package = sheet.readStr(r, colidx);
                    }

                    //상태
                    if (nudst.Value > 0)
                    {
                        colidx = (int)(nudst.Value - 1);
                        dr.status = sheet.readStr(r, colidx);
                    }

                    //형태
                    if (nudtype.Value > 0)
                    {
                        colidx = (int)(nudtype.Value - 1);
                        dr.type = sheet.readStr(r, colidx);
                    }

                    //분류
                    if (nudbunru.Value > 0)
                    {
                        colidx = (int)(nudbunru.Value - 1);
                        dr.process = sheet.readStr(r, colidx);
                    }

                    //프로젝트/아이템                    
                    if (nuditem.Value > 0)
                    {
                        colidx = (int)(nuditem.Value - 1);
                        dr.projectName = sheet.readStr(r, colidx);
                    }

                    //비고
                    if (nudbio.Value > 0)
                    {
                        colidx = (int)(nudbio.Value - 1);
                        dr.description = sheet.readStr(r, colidx);
                    }

                    //시간
                    if (nudhrd.Value > 0)
                    {
                        colidx = (int)(nudhrd.Value - 1);
                        try
                        {
                            dr.hrs = sheet.readNum(r, colidx);
                        }
                        catch { dr.hrs = 0; }

                    }
                    //OT
                    if (nudot.Value > 0)
                    {
                        colidx = (int)(nudot.Value - 1);
                        try
                        {
                            dr.ot = sheet.readNum(r, colidx);
                        }
                        catch { dr.ot = 0; }

                    }
                    //uid
                    if (nuduid.Value > 0)
                    {
                        colidx = (int)(nuduid.Value - 1);
                        dr.uid = sheet.readStr(r, colidx);
                    }

                    //susername
                    if (nudname.Value > 0)
                    {
                        colidx = (int)(nudname.Value - 1);
                        if (string.IsNullOrEmpty(dr.uid) == true)
                        {
                            dr.username = sheet.readStr(r, colidx);
                            var users = dt_users.Select("name='" + dr.username + "'");
                            if (users.Length == 1)
                            {
                                dr.uid = users[0]["id"].ToString();
                            }
                            else
                            {
                                if (unknownlist.Contains(dr.username) == false)
                                    unknownlist.Add(dr.username);
                            }
                        }

                    }

                    this.dsPRJ.JobReport.AddJobReportRow(dr);
                }
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("불러오는 중 오류 발생\n" + ex.Message);
            }
            //
            book = null;


            this.bn.BindingSource = this.bs;

            //기간을 정하낟.
            var minDate = this.dsPRJ.JobReport.Min(t => t.pdate);
            var maxDate = this.dsPRJ.JobReport.Max(t => t.pdate);
            this.dateTimePicker2.Value = DateTime.Parse(minDate);
            this.dateTimePicker1.Value = DateTime.Parse(maxDate);

            if (this.bs.Count < 1)
            {
                FCOMMON.Util.MsgE("입력된 자료가 없습니다.\n\n지정된 엑셀의 1번째 칸에 값이 없다면 입력되지 않습니다.");
            }
            if (unknownlist.Count > 0)
            {
                FCOMMON.Util.MsgE("다음 사용자명의 계정이 확인되지 않습니다\n사용자를 먼저 등록하고 사용하세요\n" +
                    string.Join("m",unknownlist) );
                button3.Enabled = false;
            }
            else button3.Enabled = true;
        }


        private void button3_Click(object sender, EventArgs e)
        {
            if (dsPRJ.JobReport == null || dsPRJ.JobReport.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;



            var taE = new dsPRJTableAdapters.JobReportTableAdapter();
            //if (checkBox1.Checked) taE.DeleteImport(sd, ed, FCOMMON.info.Login.no, FCOMMON.info.Login.gcode);
            taE.Update(dsPRJ.JobReport);

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

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            var sd = dateTimePicker2.Value;
            var ed = dateTimePicker1.Value;

            var dlg = FCOMMON.Util.MsgQ($"{sd.ToString("yyyy-MM-dd")}~{ed.ToString("yyyy-MM-dd")} 사이의 업로드된 자료를 삭제 할까요?");
            if (dlg != DialogResult.Yes) return;


            var ta = new dsPRJTableAdapters.JobReportTableAdapter();
            if (this.cmbUser.SelectedValue == null || this.cmbUser.SelectedValue.ToString() == "--")
            {
                var cnt = ta.DeleteImportAll(sd.ToString("yyyy-MM-dd"), ed.ToString("yyyy-MM-dd"), FCOMMON.info.Login.gcode);
                FCOMMON.Util.MsgI($"{cnt}건의 자료가 삭제 되었습니다");
            }
            else
            {
                var uid = this.cmbUser.SelectedItem.ToString();
                var cnt = ta.DeleteImport(sd.ToString("yyyy-MM-dd"), ed.ToString("yyyy-MM-dd"), uid, FCOMMON.info.Login.gcode);
                FCOMMON.Util.MsgI($"{cnt}건의 자료가 삭제 되었습니다");
            }

        }
    }
}
