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 util = FCOMMON.Util;

namespace FPJ0000.Note
{
    public partial class fNote : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        public fNote()
        {
            InitializeComponent();
            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.ds1.EETGW_Note.TableNewRow += Projects_TableNewRow;
            this.FormClosed += __Closed;

            dtSD.KeyDown += dtSD_KeyDown;
            dtED.KeyDown += dtSD_KeyDown;

        }

        void __Closed(object sender, FormClosedEventArgs e)
        {

        }

        Boolean binit = false;

      
        private void __Load(object sender, EventArgs e)
        {
            this.dtSD.Text = DateTime.Now.AddYears(-1).ToString("yyyy-MM-01");
            this.dtED.Text = DateTime.Now.ToShortDateString();

            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.jobreport));
            if (curLevel >= 5)
            {
                btSave.Visible = true;
            }
            else
            {
                btSave.Visible = false;
                //btViewDel.Visible = false;
                fpSpread1.EditMode = false;
                fpSpread1.Sheets[0].SelectionUnit = FarPoint.Win.Spread.Model.SelectionUnit.Row;
                fpSpread1.EditModePermanent = false;
                fpSpread1.EditModeReplace = false;

                foreach (FarPoint.Win.Spread.Column col in fpSpread1.ActiveSheet.Columns)
                    col.Locked = true;
            }
                        
            refreshData();
            binit = true;


        }

        private void cmbProcess_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (binit == false) return;
        }
        private void cmbProcess_Click(object sender, EventArgs e)
        {

        }
      
        void dtSD_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;
            var tb = sender as ToolStripTextBox;
            var input = tb.Text.Trim();
            if (input == "") tb.Text = DateTime.Now.ToShortDateString();
            else
            {
                string dt = string.Empty;
                if (!util.MakeDateString(input, out dt))
                {
                    FCOMMON.Util.MsgE("입력값이 올바르지 않습니다.");
                    tb.SelectAll();
                    tb.Focus();
                    return;
                }
                else
                {
                    tb.Text = dt;
                }
            }
            if (tb == dtSD)
            {
                dtED.Focus();
                dtED.SelectAll();
            }
            else
            {
                btSearch.PerformClick();
                tb.SelectAll();
            }
        }

        void refreshData()
        {
            // string state = "%";
            // if (cmbState.SelectedIndex > 0) state = cmbState.Text.Split(',')[0].Substring(1);
            
            //var cmd = new System.Data.SqlClient.SqlCommand("select idx,gcode,pdate,uid,'' as description,'' as description2,share,wuid,wdate from eetgw_note where gcode = @gcode and pdate between @sd and @ed and (uid=@uid or isnull(share,0) = 1)",ta.Connection);
            //cmd.Parameters.Add("gcode", SqlDbType.VarChar).Value = FCOMMON.info.Login.gcode;
            //cmd.Parameters.Add("sd", SqlDbType.VarChar).Value = dtSD.Text;
            //cmd.Parameters.Add("ed", SqlDbType.VarChar).Value = dtED.Text;
            //cmd.Parameters.Add("uid", SqlDbType.VarChar).Value = FCOMMON.info.Login.no;
            //var da = new System.Data.SqlClient.SqlDataAdapter(cmd);
            //da.Fill(this.ds1.EETGW_Note);
            //cmd.Dispose();
            //da.Dispose();

            //설명을 가져오지 않는다.
            this.ta.FillByNoDesc(this.ds1.EETGW_Note, FCOMMON.info.Login.gcode, dtSD.Text, dtED.Text, FCOMMON.info.Login.no);
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            FormattingData();
        }

        void FormattingData()
        {
            //삭제컬럼인덱스
            this.fpSpread1.SuspendLayout();
            var delindex = this.fpSpread1.ActiveSheet.Columns["share"].Index;
            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var state = this.fpSpread1.ActiveSheet.GetValue(i, delindex);
                var stateStr = false;
                if (state != null) stateStr = (bool)state;

                if(stateStr == true)
                    this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.WhiteSmoke;
                else
                    this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.SkyBlue;
            }
            this.fpSpread1.ResumeLayout();
        }
        void funcSave()
        {
            this.Validate();
            this.bs.EndEdit();
            try
            {
                this.ta.Update(ds1.EETGW_Note);
                FormattingData();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("저장 실패\n" + ex.Message);
            }
        }

        private void projectsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            funcSave();

        }
        void Projects_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            e.Row["pdate"] = DateTime.Now.ToShortDateString();
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["uid"] = FCOMMON.info.Login.no; //이름을 직접 기록
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            refreshData();
        }

        private void partListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectsRow;
            var f = new fPartList(dr.idx);
            f.MdiParent = this.MdiParent;
            f.Show();
        }


        private void autoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.fpSpread1.ActiveSheet.DataAutoSizeColumns = true;

            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
                this.fpSpread1.ActiveSheet.SetRowHeight(i, 25);
            //dv1.AutoResizeColumns();
        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (FarPoint.Win.Spread.Column col in this.fpSpread1.ActiveSheet.Columns)
            {
                col.Width = 100;
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FPUtil.ColsizeSave(this.fpSpread1, fn_fpcolsize);
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
        }

        private void btSearch_Click(object sender, EventArgs e)
        {
            refreshData();
        }

        private void toolStripLabel3_Click(object sender, EventArgs e)
        {
            //사용자목록처리
            var namestr = string.Format("{0}({1})", FCOMMON.info.Login.nameK, FCOMMON.info.Login.no); ;
            if (FCOMMON.info.Login.no == "dev") namestr = "김치균(395552)";
            refreshData();
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            var f = new Note.fNote_Add(-1);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                refreshData();
            }
        }

        private void btFind_Click(object sender, EventArgs e)
        {
            var search = tbFind.Text.Trim();
            search = search.Replace("*", "x");
            if (tbFind.Text != search) tbFind.Text = search;
            try
            {
                if (search.Trim() == "")
                {
                    this.bs.Filter = "";
                    tbFind.BackColor = Color.White;
                }
                else
                {
                    search = search.Replace("'", "''");
                    var collist = new string[] { "description" };
                    string filter = ""; // "itemna like ? or package like ? or projectname like ? or process like ? or [type] like ? or description like ?";
                    foreach (var col in collist)
                    {
                        if (filter != "") filter += " or ";
                        filter += col + " like ?";
                    } 
                    filter = filter.Replace("?", "'%" + search + "%'");
                    this.bs.Filter = filter;
                    tbFind.BackColor = Color.Lime;
                }
                tbFind.SelectAll();
                tbFind.Focus();
            }
            catch (Exception ex)
            {
                this.tbFind.BackColor = Color.Tomato;
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

        private void tbFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) btFind.PerformClick();
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            funcEdit();
        }
        void funcEdit()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSNote.EETGW_NoteRow;
            //if(dr.uid != FCOMMON.info.Login.no && FCOMMON.info.Login.level<5)
            //{
            //    FCOMMON.Util.MsgE("타인의 자료는 추가/변경/삭제 할 수 없습니다.");
            //    return;
            //}

            var f = new Note.fNote_Add(dr.idx);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                refreshData();
            }
        }

        private void exportListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            sd.FileName = "jobreport.xls";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fpSpread1.SaveExcel(sd.FileName,
                    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
                FCOMMON.Util.MsgI("다음 파일이 생성 되었습니다.\n\n" + sd.FileName);
            }
        }

        private void btCopy_Click(object sender, EventArgs e)
        {
           // funcCopy(); //190509
        }
        //void funcCopy()
        //{
        //    var drv = this.bs.Current as DataRowView;
        //    if (drv == null) return;
        //    var dr = drv.Row as dsPRJ.JobReportRow;

        //    //현재 데이터를 입력하여 신규 추가를 한다.
        //    var newdr = this.ds1.JobReport.NewJobReportRow();
        //    FCOMMON.Util.CopyData((System.Data.DataRow)dr, (System.Data.DataRow)newdr);
        //    newdr.wdate = DateTime.Now;
        //    newdr.wuid = FCOMMON.info.Login.no;
        //    newdr.uid = FCOMMON.info.Login.no;
        //    //newdr.description = "";
        //    newdr.pdate = DateTime.Now.ToShortDateString(); //190509
        //    newdr.idx = -1;
        //    newdr.hrs = 8.0;
        //    newdr.ot = 0.0;
        //    newdr.EndEdit();

        //    //var newdr = this.dsMSSQL.JobReport.NewJobReportRow();
        //    JobReport.fJobReport_Add f = new JobReport.fJobReport_Add(newdr);
        //    if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //    {
        //        this.ds1.JobReport.AddJobReportRow(newdr);
        //        this.ta.Update(newdr);
        //        newdr.AcceptChanges();
        //    }
        //    else newdr.Delete();
        //}

        private void btDel_Click(object sender, EventArgs e)
        {
            funcDelete();
        }
        void funcDelete()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSNote.EETGW_NoteRow;
            if (dr.uid != FCOMMON.info.Login.no && FCOMMON.info.Login.level < 5)
            {
                FCOMMON.Util.MsgE("타인의 자료는 추가/변경/삭제 할 수 없습니다.");
                return;
            }

            var dlg = FCOMMON.Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?");
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            dr.Delete();
            try
            {
                this.ta.Update(dr);
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("삭제실패\n\n" + ex.Message);
            }
        }
        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");
            dtSD.Text = sdDate.ToShortDateString();
            dtED.Text = sdDate.AddMonths(1).AddDays(-1).ToShortDateString();
            refreshData();
        }

        private void btReport_Click(object sender, EventArgs e)
        {
            var f = new JobReport_.rJobReport();
            f.Show();
        }


        private void 복사ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //funcCopy();
        }

        private void 편집ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            funcEdit();
        }

        private void 삭제ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            funcDelete();
        }

        private void btReportDay_Click(object sender, EventArgs e)
        {
            var f = new JobReport_.rJobReportDay();
            f.Show();
        }

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

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSNote.EETGW_NoteRow;
            //if (string.IsNullOrEmpty(dr.description2)) richTextBoxEx1.Text = dr.description;
            //else richTextBoxEx1.Rtf = dr.description2;
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSNote.EETGW_NoteRow;


            var serverpath = Properties.Settings.Default.SharePath; // @"\\10.131.32.29\Data\Project";
            if (System.IO.Directory.Exists(serverpath) == false)
            {
                FCOMMON.Util.MsgE("프로젝트 기본경로가 존재하지 않아 진행할 수 없습니다\n\n" +
                    serverpath);
                return;
            }

            var path = serverpath + "\\Note\\" + dr.guid;
            if (System.IO.Directory.Exists(path) == false)
            {
                try
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                catch (Exception eX)
                {
                    FCOMMON.Util.MsgE("프로젝트 저장소 생성실패\n" + eX.Message);
                    return;
                }
            }
            FCOMMON.Util.RunExplorer(path);
        }
    }
}
