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;
using NetOffice;
using Outlook = NetOffice.OutlookApi;
using NetOffice.OutlookApi.Enums;

namespace FBS0000
{
    public partial class WorkTable : FCOMMON.fBase
    {
        public WorkTable(string sd, string ed, string grp)
        {
            InitializeComponent();
            tbSD.Text = sd;
            tbED.Text = ed;
            tbGrp.Text = grp;
            //this.dv1.CellFormatting += dv1_CellFormatting;
        }

        private void __Load(object sender, EventArgs e)
        {

            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.holyday));
            if (curLevel >= 5)
            {
                //권한이 잇으므로 모든 사용자로 한다.
            }
            else
            {
                // this.cmbUser.Enabled = false;   //사용자를 고칠수 없게 한다.
            }

            RefreshData();
        }



        void RefreshData()
        {
            fpSpread1_Sheet1.Rows.Count = 0;
            

            //열제목
            var cols = new List<string>();
            cols.AddRange(new string[] { "번호", "사번", "직급", "성명" });

            var sd = DateTime.Parse(tbSD.Text);
            var ed = DateTime.Parse(tbED.Text);
            var idx = 0; ;
            while (true)
            {
                var curDate = sd.AddDays(idx++);
                cols.Add(curDate.Day.ToString("00"));
                if (curDate.ToShortDateString() == ed.ToShortDateString()) break;
            }
            cols.AddRange(new string[] { "발생", "사용", "잔여" });

            //열제목 설정
            fpSpread1_Sheet1.Columns.Count = cols.Count;
            for (int c = 0; c < cols.Count; c++)
            {
                fpSpread1_Sheet1.Columns[c].Label = cols[c];
                if (c < 4) fpSpread1_Sheet1.Columns[c].BackColor = Color.WhiteSmoke;
                else if (c > cols.Count - 4) fpSpread1_Sheet1.Columns[c].BackColor = Color.WhiteSmoke;
                else fpSpread1_Sheet1.Columns[c].BackColor = Color.White;
            }
            //fpSpread1_Sheet1.Cells[0, c].Value = cols[c];

            //해당 기간내의 사용
            var taUser = new dsMSSQLTableAdapters.EETGW_WorkTableUserTableAdapter();
            var dtUser = taUser.GetData(FCOMMON.info.Login.gcode, tbGrp.Text);
            var users = new List<userinfo>();
            foreach (var item in dtUser)
            {
                if (string.IsNullOrEmpty(item.indate))
                {
                    //입사일자를 체크해서. 이 날짜가 입사일 이전이면 넘어간다
                }
                users.Add(new userinfo { grade = item.grade, name = item.name, empno = item.empno, seq = item.seq.ToString() });
            }

            //휴가테이블에서 데이터를 가져온다
            var taHoly = new dsMSSQLTableAdapters.HolydayTableAdapter();
            var dtHoly = taHoly.GetByGrp(tbSD.Text, tbED.Text, FCOMMON.info.Login.gcode, this.tbGrp.Text);

            var qta = new dsMSSQLTableAdapters.QueriesTableAdapter();



            //사용자 목록을 1번열에 나열한다.
            var rowindex = 0;
            foreach (var item in users)
            {
                fpSpread1_Sheet1.Rows.Count += 1;
                fpSpread1_Sheet1.Cells[rowindex, 0].Value = item.seq;
                fpSpread1_Sheet1.Cells[rowindex, 1].Value = item.empno;
                fpSpread1_Sheet1.Cells[rowindex, 2].Value = item.grade;
                fpSpread1_Sheet1.Cells[rowindex, 3].Value = item.name;

                //이월잔액
                var jand = qta.WorkUserJan_Yesterday_Day(FCOMMON.info.Login.gcode, item.empno,sd.ToString("yyyy-01-01"), sd.ToShortDateString(),"999999");
                var used = 0.0;

                fpSpread1_Sheet1.Rows[rowindex].ResetBorder();
                fpSpread1_Sheet1.Rows[rowindex].Border = new FarPoint.Win.LineBorder(Color.Gainsboro, 1,false, false,true, true);

                //각 일자별로 특이사항을 찾는다
                int c = 0;
                for (c = 4; c < cols.Count - 3; c++)
                {
                    var curDate = sd.AddDays(c - 4);
                    var dr = dtHoly.Where(t => t.uid == item.empno && t.sdate.ToShortDateString() == curDate.ToShortDateString()).FirstOrDefault();
                    if (dr != null)
                    {
                        if (dr.term > 0)
                            used += dr.term;

                        //자료가있다.
                        if (string.IsNullOrEmpty(dr.tag) == false) fpSpread1_Sheet1.Cells[rowindex, c].Value = dr.tag;
                        else if (dr.term > 0)
                        {
                            fpSpread1_Sheet1.Cells[rowindex, c].BackColor = Color.Lime;
                            fpSpread1_Sheet1.Cells[rowindex, c].Value = "Y";
                        }
                        else if (dr.term != 0) fpSpread1_Sheet1.Cells[rowindex, c].Value = dr.term.ToString() + "Y";

                        if (dr.CrTime != 0)
                        {
                            fpSpread1_Sheet1.Cells[rowindex, c].Value = dr.CrTime.ToString();
                            fpSpread1_Sheet1.Cells[rowindex, c].BackColor = Color.DeepSkyBlue;
                        }

                        if (string.IsNullOrEmpty(dr.contents) == false) fpSpread1_Sheet1.Cells[rowindex, c].Note = dr.contents;
                        else fpSpread1_Sheet1.Cells[rowindex, c].Note = string.Empty;
                    }
                    else
                    {
                        fpSpread1_Sheet1.Cells[rowindex, c].Value = string.Empty;
                        fpSpread1_Sheet1.Cells[rowindex, c].BackColor = Color.White;
                        fpSpread1_Sheet1.Cells[rowindex, c].Note = string.Empty;
                    }


                }

                var jan = jand - used;
                fpSpread1_Sheet1.Cells[rowindex, c++].Value = jand > 0 ? jand.ToString() : string.Empty;
                fpSpread1_Sheet1.Cells[rowindex, c++].Value = used > 0 ? used.ToString() : string.Empty;
                fpSpread1_Sheet1.Cells[rowindex, c++].Value = jan > 0 ? jan.ToString() : string.Empty;


                rowindex += 1;
            }



        }
        private void boardBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            //  this.bs.EndEdit();
            var dlg = FCOMMON.Util.MsgQ("변경된 내용을 저장하시겠습니까?");
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            try
            {

            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

        class userinfo
        {
            public string seq { get; set; }
            public string empno { get; set; }
            public string name { get; set; }
            public string grade { get; set; }
            public userinfo()
            {

            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void tbSD_KeyDown(object sender, KeyEventArgs e)
        {
            var tb = sender as ToolStripTextBox;
            if (e.KeyCode == Keys.Enter)
            {
                string datestring;
                if (FCOMMON.Util.MakeDateString(tb.Text, out datestring))
                {
                    tb.Text = datestring;
                    SendKeys.Send("{TAB}");
                }
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            var sd = new SaveFileDialog();
            sd.Filter = "Excel|*.xls";
            sd.FileName = string.Format("Worktable_{0}_{1}", tbSD.Text.Replace("-", ""), tbED.Text.Replace("-", ""));
            if (sd.ShowDialog() != DialogResult.OK) return;
            fpSpread1.SaveExcel(sd.FileName,
                    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
        }

        private void lbStt_Click(object sender, EventArgs e)
        {
            var f = new FCOMMON.fSelectMonth();
            if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            var sdDate = DateTime.Parse(DateTime.Now.ToString("yyyy-") + f.selectmon.ToString() + "-01");
            tbSD.Text = sdDate.ToShortDateString();
            tbED.Text = sdDate.AddMonths(1).AddDays(-1).ToShortDateString();
            this.RefreshData();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {

            var FileName = FCOMMON.Util.CurrentPath + string.Format("Worktable_{0}_{1}", tbSD.Text.Replace("-", ""), tbED.Text.Replace("-", "")) + ".xls";
            fpSpread1.SaveExcel(FileName,
                    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders
                    | FarPoint.Excel.ExcelSaveFlags.SaveAlternatingRowStyles
                    | FarPoint.Excel.ExcelSaveFlags.UseDefaultColorPalette
                     );


            Outlook.Application outlookApplication = new Outlook.Application();
            Outlook.MailItem newTask = outlookApplication.CreateItem(OlItemType.olMailItem) as Outlook.MailItem;
            newTask.Subject = tbSD.Text.Substring(0,7) +"월 출근부";            
            //newTask.To = "Chikyun.Kim@amkor.co.kr";
            //newTask.HTMLBody = "<i><b>this is test mail</b></i>";
            newTask.BodyFormat = OlBodyFormat.olFormatHTML;
            newTask.Attachments.Add(FileName);
            newTask.Display();
        }
    }
}
