using AR;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UniMarc.ListOfValue
{
    public partial class fSelectDT : Form
    {
        public DataRow SelectedRow = null;
        public fSelectDT(DataTable dt)
        {
            InitializeComponent();
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) Close();
            };
            this.bs.DataSource = dt;
            this.bn.BindingSource = this.bs;
            this.dv1.DataSource = this.bs;
            this.dv1.MultiSelect = false;
            this.dv1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.dv1.EditMode = DataGridViewEditMode.EditProgrammatically;
            this.dv1.CellDoubleClick += Dv1_CellDoubleClick;
            this.dv1.KeyDown += Dv1_KeyDown;
        }

        private void Dv1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.Handled = true;
                e.SuppressKeyPress = true;
                btSelect_Click(sender, e);
            }
        }

        private void Dv1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                var row = this.dv1.Rows[e.RowIndex];
                if (row.DataBoundItem is DataRowView drv)
                {
                    SelectedRow = drv.Row;
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
        }

        private void fSelectDT_Load(object sender, EventArgs e)
        {
            this.Show();
            Application.DoEvents();
            this.dv1.AutoResizeColumns();
            this.dv1.Focus();

        }

        private void btfind_Click(object sender, EventArgs e)
        {
            find();
        }
        void find()
        {
            var search = tbFind.Text.Trim();
            var filter = "";
            try
            {
                if (!search.isEmpty())
                {
                    // 검색어에서 작은따옴표 이스케이프 처리
                    var escapedSearch = search.Replace("'", "''");

                    // DataTable의 모든 컬럼에 대해 검색 필터 생성
                    var dt = this.bs.DataSource as DataTable;
                    if (dt != null && dt.Columns.Count > 0)
                    {
                        var filters = new List<string>();
                        foreach (DataColumn column in dt.Columns)
                        {
                            // 문자열 컬럼만 검색 (숫자나 날짜 컬럼은 Convert 사용)
                            if (column.DataType == typeof(string))
                            {
                                filters.Add($"ISNULL(CONVERT([{column.ColumnName}], 'System.String'), '') LIKE '%{escapedSearch}%'");
                            }
                            else
                            {
                                filters.Add($"CONVERT([{column.ColumnName}], 'System.String') LIKE '%{escapedSearch}%'");
                            }
                        }

                        // OR 조건으로 연결
                        filter = string.Join(" OR ", filters);
                    }
                }

                this.bs.Filter = filter;
                if (search.isEmpty()) tbFind.BackColor = Color.White;
                else tbFind.BackColor = Color.Lime;

            }
            catch (Exception ex)
            {
                this.bs.Filter = "";
                tbFind.BackColor = Color.HotPink;
            }
            finally
            {
                tbFind.SelectAll();
                tbFind.Focus();
            }
        }

        private void btSelect_Click(object sender, EventArgs e)
        {
            if (this.bs.Current == null)
            {
                UTIL.MsgE("선택된 데이터가 없습니다.");
                return;
            }

            if (this.bs.Current is DataRowView drv)
            {
                SelectedRow = drv.Row;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

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