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
{
    public partial class fSaveCostList : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        public fSaveCostList()
        {
            InitializeComponent();
            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.dsMSSQL.EETGW_SaveCost.TableNewRow += Projects_TableNewRow;
            this.FormClosed += __Closed;

        }

        void __Closed(object sender, FormClosedEventArgs e)
        {

        }

        private void __Load(object sender, EventArgs e)
        {
            //프로젝트 목록을 처리함
            //this.tbRequest.Text = FCOMMON.info.Login.nameK;
            cmbDateType.SelectedIndex = 0;  //기본시작일 기준으로 한다

            //일단 나만 보이게 함
            tbRequest.Text = string.Empty;// FCOMMON.info.Login.nameK;


            this.dtSD.Text = DateTime.Now.ToString("yyyy-01-01");   //1년치로 본다 210405
            var sdate = DateTime.Parse(dtSD.Text);
            this.dtED.Text = DateTime.Now.ToShortDateString();// sdate.AddMonths(1).AddDays(-1).ToShortDateString();

            refreshData();

            ////일반사용자의경우에는 상태를 변경하지 못한다.
            //int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.savecost));
            //if (curLevel >= 5)
            //{
            //    btSave.Visible = true;
            //}
            //else
            //{
            //    btSave.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;
            //}
        }

        void refreshData()
        {

            if (this.dsMSSQL.EETGW_SaveCost.GetChanges() != null)
            {
                var dlg = util.MsgQ("변경된 내용이 있습니다. 지금 새로고침 하면 해당 자료는 손실 됩니다. 진행 할까요?");
                if (dlg != DialogResult.Yes) return;
            }


            string state = "";
            string State_Select = " SELECT  * FROM  EETGW_SaveCost";
            string State_where = " WHERE gcode=@gcode and ";

            var dateField = "pdate";
            if (cmbDateType.SelectedIndex == 1) dateField = "edate";

            State_where += " " + dateField + " between '" + dtSD.Text + "' and '" + dtED.Text + "' AND (ISNULL(userManager, '') LIKE @username OR " +
               "ISNULL(usermain, '') LIKE @username OR " +
               "ISNULL(reqstaff, '') LIKE @username) ";

            if (state != "") State_where += " AND " + state;
            //if (cmbCate.SelectedIndex > 0) State_where += " AND isnull(category,'') = '" + cmbCate.Text + "'";
            //if (cmbProcess.SelectedIndex > 0) State_where += " and isnull(userprocess,'') = '" + cmbProcess.Text.Trim() + "'";
            string State_order = " ORDER BY pdate";

            string request = "%";
            if (tbRequest.Text.Trim() != "") request = "%" + this.tbRequest.Text.Trim() + "%";

            System.Data.SqlClient.SqlCommand selCmd = new System.Data.SqlClient.SqlCommand();
            selCmd.Connection = ta.Connection;
            selCmd.CommandText = State_Select + State_where + State_order;
            selCmd.Parameters.Add("gcode", SqlDbType.VarChar).Value = FCOMMON.info.Login.gcode;
            selCmd.Parameters.Add("username", SqlDbType.VarChar);
            selCmd.Parameters["username"].Value = request;

            System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter();
            sda.SelectCommand = selCmd;

            this.dsMSSQL.EETGW_SaveCost.Clear();
            sda.Fill(this.dsMSSQL.EETGW_SaveCost);


            this.dsMSSQL.EETGW_SaveCost.AcceptChanges();

            sbSumE.Text = this.dsMSSQL.EETGW_SaveCost.Sum(t => t.coste).ToString("N2");
            sbSumO.Text = this.dsMSSQL.EETGW_SaveCost.Sum(t => t.costo).ToString("N2");
            sbSumI.Text = this.dsMSSQL.EETGW_SaveCost.Sum(t => t.costn).ToString("N2");

            FormattingData();
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
        }

        void FormattingData()
        {

            ////삭제컬럼인덱스
            this.fpSpread1.SuspendLayout();
            var col_fanout = this.fpSpread1.ActiveSheet.Columns["fanout"].Index;
            var col_weekly = this.fpSpread1.ActiveSheet.Columns["weekly"].Index;
            var col_effect = this.fpSpread1.ActiveSheet.Columns["effect"].Index;
            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var o_fanout = this.fpSpread1.ActiveSheet.GetValue(i, col_fanout);
                var o_weekly = this.fpSpread1.ActiveSheet.GetValue(i, col_weekly);
                bool b_fanout = false;
                bool b_weekly = false;
                if (o_fanout != null) b_fanout = (bool)o_fanout;
                if (o_weekly != null) b_weekly = (bool)o_weekly;

                if (b_weekly) this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.Lime;
                else this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.White;

                this.fpSpread1.ActiveSheet.Cells[i, col_effect].BackColor = Color.FromArgb(200, 200, 200);


                //    this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.White;
                //    switch (stateStr.ToLower())
                //    {
                //        case "검토":
                //            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Blue;
                //            break;
                //        case "취소":
                //            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Red;
                //            break;
                //        case "진행":
                //            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Green;
                //            break;
                //        case "보류":
                //            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Tomato;
                //            break;
                //        case "완료(보고)":
                //            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Gray;
                //            break;
                //        case "완료":
                //            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Magenta;
                //            break;
                //        default:
                //            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Black;
                //            break;
                //    }

            }
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            this.fpSpread1.ResumeLayout();
        }

        void funcSave(Boolean pmt)
        {
            this.Validate();
            this.bs.EndEdit();

            if (pmt)
            {
                var dlg = FCOMMON.Util.MsgQ("변경 사항을 저장하시겠습니까?");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }

            try
            {
                this.ta.Update(this.dsMSSQL.EETGW_SaveCost);
                dsMSSQL.EETGW_SaveCost.AcceptChanges();
                FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
                FormattingData();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

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

        }
        void Projects_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
        }





        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.ResetVisible();
                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 toolStripLabel3_Click(object sender, EventArgs e)
        {
            //사용자목록처리
            if (tbRequest.Text != "")
            {
                tbRequest.Text = string.Empty;
            }
            else tbRequest.Text = FCOMMON.info.Login.nameK;

            refreshData();
        }




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

        private void btFind_Click(object sender, EventArgs e)
        {

            string search = tbFind.Text.Trim();
            if (search == "")
            {

                bs.Filter = "";
                tbFind.BackColor = SystemColors.Control;
                FormattingData();
            }
            else
            {
                try
                {
                    var cols = new string[] {
                        "name","process","reqstaff","usermain",
                        "orderno","usersub","userManager",
                        "remark_req"};
                    bs.Filter = FCOMMON.Util.MakeFilterString(cols, search);
                    tbFind.BackColor = Color.Lime;
                    tbFind.SelectAll();
                    tbFind.Focus();
                    FormattingData();
                }
                catch (Exception ex)
                {
                    bs.Filter = "";
                    FCOMMON.Util.MsgE(ex.Message);
                    tbFind.BackColor = Color.Red;
                    FormattingData();
                }
            }
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            funcDelete();
        }
        void funcDelete()
        {
            var dlg = FCOMMON.Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?");
            if (dlg == System.Windows.Forms.DialogResult.Yes)
            {
                bs.RemoveCurrent();

                //일반사용자는 바로 저장되도록 함
                int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.savecost));
                if (curLevel < 5)
                {
                    funcSave(false); //자동저장
                }
            }
        }
        private void 엑셀파일로저장ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = ("excel|*.xls");
            var dlg = sd.ShowDialog();
            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                this.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 bs_CurrentChanged(object sender, EventArgs e)
        {
            //히스토리 데이터를 업데이트하고 첫번재 자료를 표시한다.
            var drv = this.bs.Current as DataRowView;
            if (drv == null)
            {
                this.label1.Text = "프로젝트가 선택되지 않았습니다";
                return;
            }
            var dr = drv.Row as dsPRJ.EETGW_SaveCostRow;
            this.label1.Text = string.Format("[{0}] {1}", dr.name, dr.memo);
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            var newdr = this.dsMSSQL.EETGW_SaveCost.NewEETGW_SaveCostRow();
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.wdate = DateTime.Now;
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.edate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.userManager = FCOMMON.info.Login.nameK;
            newdr.userprocess = FCOMMON.info.Login.process;
            newdr.costn = 0;
            newdr.costo = 0;
            newdr.cnt = 1;
            newdr.name = "Project Title";
            var f = new fSaveCostData(newdr);
            f.StartPosition = FormStartPosition.CenterScreen;
            var dlg = f.ShowDialog();
            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                this.dsMSSQL.EETGW_SaveCost.AddEETGW_SaveCostRow(newdr);
                try
                {

                    ta.Update(newdr);
                }
                catch (Exception ex)
                {
                    FCOMMON.Util.MsgE("Save Error\n" + ex.Message);
                }

            }
            else newdr.Delete();
        }

        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 dsPRJ.EETGW_SaveCostRow;
            var f = new fSaveCostData(dr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.savecost));
                if (curLevel < 5)
                {
                    funcSave(false); //자동저장
                }
            }
        }

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


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



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

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

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

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            var f = new SaveCost.fSaveCostReport();
            f.Show();
                
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            var newdr = this.dsMSSQL.EETGW_SaveCost.NewEETGW_SaveCostRow();
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.wdate = DateTime.Now;
            newdr.pdate = DateTime.Now.ToShortDateString();
            newdr.gcode = FCOMMON.info.Login.gcode;
            this.dsMSSQL.EETGW_SaveCost.AddEETGW_SaveCostRow(newdr);
        }
    }
}