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;
using UniMarc.ListOfValue;
using AR;

namespace UniMarc
{
    public partial class Mac_List_Edit : Form
    {
        Helper_DB db = new Helper_DB();
        MacListItem item;
        Mac_List ml;

        public Mac_List_Edit(Mac_List _ml, MacListItem _item)
        {
            InitializeComponent();
            ml = _ml;
            item = _item;
        }

        private void Mac_List_Edit_Load(object sender, EventArgs e)
        {
            db.DBcon();

            string compidx = PUB.user.CompanyIdx;

            #region 콤보박스 채우기

            // 담당자
            string CompQuery = string.Format("SELECT `comp_name` FROM `Comp` WHERE `idx` = {0}", compidx);
            string cmd = string.Format("SELECT `name` FROM `User_Data` WHERE `affil` = ({0});", CompQuery);
            string[] cmdResult = db.DB_Send_CMD_Search(cmd).Split('|');

            foreach (string UserName in cmdResult)
            {
                if (!string.IsNullOrEmpty(UserName))
                    cb_User.Items.Add(UserName);
            }

            // 상태
            cb_State.Items.AddRange(new string[] { "진행", "완료" });

            #endregion

            // 데이터 로드
            tb_ListName.Text = item.list_name;
            tb_divComp.Text = item.customer_name;
            tbCustomIDX.Text = item.customer;
            cb_User.SelectedItem = item.charge;
            cb_State.SelectedItem = item.state;
            tb_WorkName.Text = item.work_name;
            tb_Etc.Text = item.etc;

            DateTime resDate;
            if (DateTime.TryParse(item.end_date, out resDate))
            {
                chk_DateRes.Checked = true;
                dtp_DateRes.Enabled = true;
                dtp_DateRes.Value = resDate;
            }
            else
            {
                chk_DateRes.Checked = false;
                dtp_DateRes.Enabled = false;
            }
        }

        private void chk_DateRes_CheckedChanged(object sender, EventArgs e)
        {
            dtp_DateRes.Enabled = chk_DateRes.Checked;
        }

        private void btCustom_Click(object sender, EventArgs e)
        {
            LovCustom();
        }

        void LovCustom()
        {
            string compidx = PUB.user.CompanyIdx;
            var inputsearch = tb_divComp.Text.Trim();
            var where = $"campanyidx={compidx}";
            if (!string.IsNullOrEmpty(inputsearch))
            {
                where += $" and c_sangho like '%{inputsearch.Replace("'", "''")}%'";
            }
            var dt = Helper_DB.ExecuteQueryData("Client", columns: "idx,c_sangho", orders: "c_sangho", wheres: where);
            using (var f = new fSelectDT(dt))
                if (f.ShowDialog() == DialogResult.OK)
                {
                    var dr = f.SelectedRow;
                    if (dr == null) return;
                    tbCustomIDX.Text = dr["idx"]?.ToString() ?? string.Empty;
                    tb_divComp.Text = dr["c_sangho"]?.ToString() ?? string.Empty;
                }
        }

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

        private void btSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tb_ListName.Text))
            {
                UTIL.MsgI("목록명을 입력하세요.");
                return;
            }

            string table = "Obj_List";
            string[] edit_col = { "list_name", "customer", "m_charge", "state", "work_name", "m_etc", "date_res" };
            string resDateVal = chk_DateRes.Checked ? dtp_DateRes.Value.ToString("yyyy-MM-dd") : "NULL";

            string[] edit_tbl = { 
                tb_ListName.Text, 
                tbCustomIDX.Text, 
                cb_User.Text, 
                cb_State.Text, 
                tb_WorkName.Text, 
                tb_Etc.Text,
                resDateVal
            };
            string[] sear_col = { "idx", "comp_num" };
            string[] sear_tbl = { item.idx, PUB.user.CompanyIdx };

            string U_cmd = db.More_Update(table, edit_col, edit_tbl, sear_col, sear_tbl);
            if (resDateVal == "NULL")
            {
                U_cmd = U_cmd.Replace("`date_res` = \"NULL\"", "`date_res` = NULL");
            }

            var result = Helper_DB.ExcuteNonQuery(U_cmd);

            if (result.applyCount > 0)
            {
                //UTIL.MsgI("수정되었습니다.");
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                UTIL.MsgE("수정에 실패했습니다.\n" + result.errorMessage);
            }
        }

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