using FCOMMON;
using NetOffice.OutlookApi;
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace FCM0000
{
    public partial class fCode : FCOMMON.fBase
    {
        string defaultgubun = "";
        string defafilter = "";
        public fCode(string gubun = "", string filter = "")
        {
            InitializeComponent();
            this.defaultgubun = gubun;
            this.defafilter = filter;
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            this.dsMSSQL.Common.TableNewRow += Common_TableNewRow;
            if (FCOMMON.info.Login.level >= 9) toolStripButton1.Visible = true;
            this.KeyPreview = true;
            this.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Escape) this.Close(); };
        }

        void Common_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            string grp = "99";
            if (this.cmbList.SelectedIndex > 0)
            {
                var title = cmbList.Text.Split(']');
                grp = title[0].Substring(1);
            }
            e.Row["grp"] = grp;
        }
     

        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            tbFind.Text = string.Empty;
            if (this.defaultgubun.isEmpty() == false)
            {
                dv.AllowUserToAddRows = false;
                dv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                btAddNew.Visible = false;
            }
            else
            {
                btCancle.Visible = false;
            }


            this.Show();
            System.Windows.Forms.Application.DoEvents();

            if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
            if (this.RestoreBounds.X + this.RestoreBounds.Width < 300 && this.RestoreBounds.X < 0)
                this.Location = new Point(0, 0);


            toolStripButton1.Visible = FCOMMON.info.Login.no == "dev";
            // this.TopMost=true;
            // this.Activate();


            //자동선택해준다.
            if (defaultgubun.isEmpty() == false)
            {
                RefreshCodeList();
                var idx = -1;
                for (int i = 0; i < this.cmbList.Items.Count; i++)
                {
                    var itemname = $"[{i:00}]";
                    var item = cmbList.Items[i];
                    if (item.ToString().StartsWith($"[{defaultgubun}]"))
                    {
                        idx = i;
                        break;
                    }
                }
                if (idx > -1)
                {
                    this.cmbList.SelectedIndex = idx;
                    this.cmbList.Enabled = false;
                }
                cmbList_SelectedIndexChanged(null, null);

            }
            else cmbList_SelectedIndexChanged(null, null);
        }
        void RefreshCodeList()
        {
            //공용코드목록을 가져온다.
            cmbList.Items.Clear();
            var codelist = FCOMMON.DBM.getCodeList();
            cmbList.Items.Add("-- Code Group List --");
            foreach (var item in codelist)
            {
                cmbList.Items.Add(string.Format("[{0}] {1}", item.Key, item.Value));
            }
        }
        void RefreshCodeData()
        {
            string grp = "99";
            if (cmbList.SelectedIndex > 0)
            {
                var title = cmbList.Text.Split(']');
                grp = title[0].Substring(1);
            }
            try
            {
                this.ta.Fill(this.dsMSSQL.Common, grp, FCOMMON.info.Login.gcode);
                this.bs.Filter = this.defafilter;
                this.dsMSSQL.Common.AcceptChanges();
            }
            catch (System.Exception ex)
            {
                FCOMMON.Util.MsgE("Query Error\n\n" + ex.Message);
            }
        }

        private void commonBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();
            this.tam.UpdateAll(this.dsMSSQL);
            this.dsMSSQL.Common.AcceptChanges();
            if (this.cmbList.SelectedIndex <= 0)
            {
                cmbList_SelectedIndexChanged(null, null);
            }


        }

        private void cmbList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.dsMSSQL.HasChanges())
            {
                var dlg = FCOMMON.Util.MsgQ(
                    "변경된 자료가 손실됩니다.\n\n" +
                    "목록을 새로고침 하시겠습니까?");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }
            if (cmbList.SelectedIndex <= 0)
            {
                RefreshCodeList();
                RefreshCodeData();
            }
            else if (cmbList.SelectedIndex > 0)
                RefreshCodeData();

            dv.AutoResizeColumns();
        }

        private void 코드일괄생성ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var drows = this.dsMSSQL.Common.Select(this.bs.Filter, "memo");
            for (int i = 1; i <= drows.Length; i++)
            {
                drows[i - 1]["code"] = i.ToString("000");
            }
        }

        private void title가져오기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FCOMMON.fInputTextBox();
            if (f.ShowDialog() == DialogResult.OK)
            {
                var data = f.textBox1.Text.Trim();
                data = data.Replace("\r", "");
                var lines = data.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

                var dlg = FCOMMON.Util.MsgQ(lines.Count().ToString() + "건의 자료가 있습니다. 입력할까요?");
                if (dlg == DialogResult.Yes)
                {
                    foreach (var item in lines)
                    {
                        if (item.Trim().Equals("")) continue;

                        if (this.dsMSSQL.Common.Where(t => t.memo == item.Trim()).Any() == false)
                        {
                            var newdr = this.dsMSSQL.Common.NewCommonRow();
                            newdr.memo = item;
                            this.dsMSSQL.Common.AddCommonRow(newdr);
                        }
                    }
                }


            }
        }

        private void s가져오기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FCOMMON.fInputTextBox();
            if (f.ShowDialog() == DialogResult.OK)
            {
                var data = f.textBox1.Text.Trim();
                data = data.Replace("\r", "");
                var lines = data.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

                var dlg = FCOMMON.Util.MsgQ(lines.Count().ToString() + "건의 자료가 있습니다. 입력할까요?");
                if (dlg == DialogResult.Yes)
                {
                    int r = 0;
                    foreach (var item in lines)
                    {
                        if (r < this.dsMSSQL.Common.Count)
                            this.dsMSSQL.Common.Rows[r]["svalue"] = item;

                        r += 1;
                        //if (item.Trim().Equals("")) continue;

                        //if (this.dsMSSQL.Common.Where(t => t.memo == item.Trim()).Any() == false)
                        //{
                        //    var newdr = this.dsMSSQL.Common.NewCommonRow();
                        //    newdr.memo = item;
                        //    this.dsMSSQL.Common.AddCommonRow(newdr);
                        //}
                    }
                }


            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            //누락된 목록을 생성합니다
            var gcode = FCOMMON.info.Login.gcode;
            var uid = FCOMMON.info.Login.no;
            if (cmbList.SelectedIndex <= 0)
            {
                if (FCOMMON.Util.MsgQ("없는 목록을 기본값에서 생성 할까요?") != DialogResult.Yes) return;

                var sql = "insert into Common(gcode,grp,code,svalue,ivalue,fvalue,memo,wuid,wdate)" +
                          $" select '{gcode}',grp,code,svalue,ivalue,fvalue,memo,'{uid}',getdate() from Common where gcode = 'EET1P' and grp = '99'" +
                          $" and code not in (select code from Common where gcode = '{gcode}' and grp = '99')";
                var cnt = FCOMMON.DBM.ExecuteNonQuery(sql);
                FCOMMON.Util.MsgI($"{cnt}건의 목록이 생성 되었습니다");
                RefreshCodeList();
            }
            else
            {
                string grp = "99";
                var title = cmbList.Text.Split(']');
                grp = title[0].Substring(1);
                if (FCOMMON.Util.MsgQ($"[{cmbList.Text}] 세부항목을 기본값에서 생성 할까요?") != DialogResult.Yes) return;

                var sql = "insert into Common(gcode,grp,code,svalue,ivalue,fvalue,memo,wuid,wdate)" +
                  $" select '{gcode}',grp,code,svalue,ivalue,fvalue,memo,'{uid}',getdate() from Common where gcode = 'EET1P' and grp = '{grp}'" +
                  $" and code not in (select code from Common where gcode = '{gcode}' and grp = '{grp}')";
                var cnt = FCOMMON.DBM.ExecuteNonQuery(sql);
                FCOMMON.Util.MsgI($"{cnt}건의 목록이 생성 되었습니다");
                RefreshCodeData();
            }

        }

        private void commonDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void btAdd_Click(object sender, EventArgs e)
        {

        }

        private void commonDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            if (this.defaultgubun.isEmpty()) return;

            this.Validate();
            this.bs.EndEdit();
            if (this.dsMSSQL.Common.GetChanges() != null)
            {
                Util.MsgE("변경된 내용이 있습니다. 저장 후 다시 시도하세요");
                return;
            }

            var drv = bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMSSQL.CommonRow;
            SelectedTitle = dr.memo;

            //선택된것으로 한다.
            DialogResult = DialogResult.OK;
        }
        public string SelectedTitle { get; set; } = "";

        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            this.SelectedTitle = string.Empty;
            this.DialogResult = DialogResult.OK;
        }

        private void tbFind_TextChanged(object sender, EventArgs e)
        {

        }

        private void tbFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                search();
        }
        void search()
        {
            var text = tbFind.Text.Trim();
            if (text.isEmpty() == false)
            {
                try
                {
                    var filter = "code like '%{0}%' or memo like '%{0}%'";
                    bs.Filter = filter.Replace("{0}", text);
                    tbFind.BackColor = Color.Lime;
                }
                catch 
                {
                    tbFind.BackColor = Color.Tomato;
                }
            }
            else
            {
                bs.Filter = "";
                tbFind.BackColor = Color.White;
            }
            tbFind.SelectAll();
        }
    }
}
