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

namespace UniMarc
{
    public partial class Home_User_manage : Form
    {
        public string User_Name { get; internal set; }
        bool mOverlap = false;
        Helper_DB mDB = new Helper_DB();
        Main main;
        string comp_name = string.Empty;
        string Table_User = "User_Data";
        CheckBox[] tUserAccesschkBox;
        string[] tUserAcess_Col;
        public Home_User_manage(Main _main)
        {
            InitializeComponent();
            main = _main;
            comp_name = main.lbCompanyName.Text;

            tUserAccesschkBox =new CheckBox[] {
                chk_Div_ListInput, chk_Div_ListLookup, chk_Div_ListTotal, chk_Div_OrderInput, chk_Div_Inven,
                chk_Div_Stock, chk_Div_Return,

                chk_Acc_SendMoneyList, chk_Acc_SendMoneyInput, chk_Acc_Buy, chk_Acc_Sales, chk_Acc_PartTime,

                chk_Marc_Setup, chk_Marc_Work, chk_Marc_Input, chk_Marc_CopyCheck, chk_Marc_Option,
                chk_Marc_DLS, chk_Marc_ETC,

                chk_Manage_User, chk_Manage_Client, chk_Manage_Purchase, chk_Manage_Book
            };

             tUserAcess_Col =new string[] {
                "id", "Div_ListInput", "Div_ListLookup", "Div_ListTotal", "Div_OrderInput", "Div_Inven",
                "Div_Stock", "Div_Return",

                "Acc_SendMoneyList", "Acc_SendMoneyInput", "Acc_Buy", "Acc_Sales", "Acc_PartTime",

                "Marc_Setup", "Marc_Work", "Marc_Input", "Marc_CopyCheck", "Marc_Option",
                "Marc_DLS", "Marc_ETC",

                "Manage_User", "Manage_Client", "Manage_Purchase", "Manage_Book"
            };
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            mDB.DBcon();
            //tb_Affil.Text = comp_name;
            //tb_Affil.Enabled = false;
            Load_CompanyList();
            RefreshList();
        }
        /// <summary>
        /// DB에 저장된 사용자 데이터를 dataGridView1로 입력하는 함수.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_lookup_Click(object sender, EventArgs e)
        {
            RefreshList();
        }
        private void RefreshList()
        {
            dataGridView1.Rows.Clear();
            string Area = "`name`, `position`, `Phone`, `ID`, `PW`,`affil`";
            string cmd = mDB.DB_Select_Search(Area, "User_Data", "affil", comp_name);
            string db_res = mDB.DB_Send_CMD_Search(cmd);
            string[] data = db_res.Split('|');
            string[] grid = { "", "", "", "", "", "", "" };
            for (int a = 0; a < data.Length; a++)
            {
                if (a % 6 == 0) { grid[0] = data[a]; }
                if (a % 6 == 1) { grid[1] = data[a]; }
                if (a % 6 == 2) { grid[2] = data[a]; }
                if (a % 6 == 3) { grid[3] = data[a]; }
                if (a % 6 == 4) { grid[4] = data[a]; }
                if (a % 6 == 5)
                {
                    grid[5] = data[a];
                    dataGridView1.Rows.Add(grid);
                }
            }
            dataGridView1.ClearSelection();
        }
        private void Load_CompanyList()
        {
            cbCompany.Items.Clear();
            string compName = main.lbCompanyName.Text;
            string cmd = string.Format("SELECT `comp_name` FROM Comp");
            string res = mDB.self_Made_Cmd(cmd);
            List<string> Aryres = res.Split('|').ToList();
            Aryres.RemoveAll(x => x == "");
            cbCompany.Items.AddRange(Aryres.ToArray());
        }

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

        private void chk_Enabled(object sender, EventArgs e)
        {
            CheckBox Target = sender as CheckBox;

            bool IsCheck = Target.Checked;

            CheckBox[] Enabled = { chk_Div, chk_Acc, chk_Marc, chk_Manage };

            CheckBox[] Div = {
                chk_Div_ListInput, chk_Div_ListLookup, chk_Div_ListTotal, chk_Div_OrderInput, chk_Div_Inven,
                chk_Div_Stock, chk_Div_Return 
            };
            CheckBox[] Acc = { 
                chk_Acc_SendMoneyList, chk_Acc_SendMoneyInput, chk_Acc_Buy, chk_Acc_Sales, chk_Acc_PartTime
            };
            CheckBox[] Marc = {
                chk_Marc_Setup, chk_Marc_Work, chk_Marc_Input, chk_Marc_CopyCheck, chk_Marc_Option,
                chk_Marc_DLS, chk_Marc_ETC
            };
            CheckBox[] Manage = {
                chk_Manage_User, chk_Manage_Client, chk_Manage_Purchase, chk_Manage_Book
            };

            for(int a= 0; a < Enabled.Length; a++)
            {
                if (Target == Enabled[a])
                {
                    if (a % 4 == 0) { Enable_Sub(Div, IsCheck); }
                    if (a % 4 == 1) { Enable_Sub(Acc, IsCheck); }
                    if (a % 4 == 2) { Enable_Sub(Marc, IsCheck); }
                    if (a % 4 == 3) { Enable_Sub(Manage, IsCheck); }
                }
            }
        }

        private void Enable_Sub(CheckBox[] Target, bool IsCheck)
        {
            for (int a = 0; a < Target.Length; a++)
            {
                Target[a].Checked = IsCheck;
            }
        }

        /// <summary>
        /// 권한 설정 0일경우 체크없음, 1일경우 활성화만, 2일경우 활성화와 수정체크
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            if (dataGridView1.CurrentCell == null || dataGridView1.CurrentCell.RowIndex < 0 || dataGridView1.SelectedRows.Count == 0) return;
            cbCompany.Text = dataGridView1.Rows[row].Cells["affil"].Value.ToString(); ;
            tb_ID.Text = dataGridView1.Rows[row].Cells["ID"].Value.ToString();
            tb_PW.Text = dataGridView1.Rows[row].Cells["PW"].Value.ToString();
            tb_Name.Text = dataGridView1.Rows[row].Cells["Per_Name"].Value.ToString();
            //tb_Affil.Text = dataGridView1.Rows[row].Cells["affil"].Value.ToString(); ;
            tb_position.Text = dataGridView1.Rows[row].Cells["Rank"].Value.ToString();
            tb_Phone.Text = dataGridView1.Rows[row].Cells["Phone"].Value.ToString();

            User_Access_Set();
        }
        #region CellClick_Sub
        private void User_Access_Set()
        {
            CheckBox[] chkBox = {
                chk_Div_ListInput, chk_Div_ListLookup, chk_Div_ListTotal, chk_Div_OrderInput, chk_Div_Inven,
                chk_Div_Stock, chk_Div_Return,

                chk_Acc_SendMoneyList, chk_Acc_SendMoneyInput, chk_Acc_Buy, chk_Acc_Sales, chk_Acc_PartTime,

                chk_Marc_Setup, chk_Marc_Work, chk_Marc_Input, chk_Marc_CopyCheck, chk_Marc_Option,
                chk_Marc_DLS, chk_Marc_ETC,

                chk_Manage_User, chk_Manage_Client, chk_Manage_Purchase, chk_Manage_Book
            };


            string Area =
                "`Div_ListInput`, `Div_ListLookup`, `Div_ListTotal`, `Div_OrderInput`, `Div_Inven`," +
                "`Div_Stock`, `Div_Return`," +

                "`Acc_SendMoneyList`, `Acc_SendMoneyInput`, `Acc_Buy`, `Acc_Sales`, `Acc_PartTime`," +

                "`Marc_Setup`, `Marc_Work`, `Marc_Input`, `Marc_CopyCheck`, `Marc_Option`," +
                "`Marc_DLS`, `Marc_ETC`," +

                "`Manage_User`, `Manage_Client`, `Manage_Purchase`, `Manage_Book`";
            string cmd = mDB.DB_Select_Search(Area, "User_Access", "id", tb_ID.Text);
            string res = mDB.DB_Send_CMD_Search(cmd);
            string[] IsCheck = res.Split('|');

            for (int a = 0; a < chkBox.Length; a++)
            {
                if (IsCheck[a] == "1")
                    chkBox[a].Checked = true;
                else
                    chkBox[a].Checked = false;
            }
        }
        #endregion

        private void btn_IDOverlap_Click(object sender, EventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(tb_ID.Text, @"^[a-zA-Z0-9]"))
            {
                UTIL.MsgE("영어와 숫자 조합으로 작성해주세요!");
                mOverlap = false;
                return;
            }

            string cmd = mDB.DB_Search(Table_User, "id", tb_ID.Text);
            string db_res = mDB.DB_Send_CMD_Search(cmd);
            if (db_res == "") { UTIL.MsgI("사용가능한 아이디입니다. [" + tb_ID.Text + "]"); mOverlap = true; }
            else { UTIL.MsgE("중복된 아이디입니다. [" + tb_ID.Text + "]"); mOverlap = false; }
        }
        private void btn_Save_Click(object sender, EventArgs e)
        {
            if (tb_ID.Text == "" || tb_PW.Text == "" || tb_Name.Text == "")
            {
                UTIL.MsgE("성명 / 아이디 / 비밀번호 를 채워주세요.");
                return;
            }

            if (!CheckSelect())
            {
                if (!mOverlap)
                {
                    UTIL.MsgE("아이디 중복확인을 해주세요.");
                    return;
                }
            }
            string tCmd = mDB.DB_Search(Table_User, "id", tb_ID.Text);

            List<string> tAuthData = new List<string>();
            tAuthData.Add(tb_ID.Text);
            List<string> tCheckBoxData = tUserAccesschkBox.ToList().ConvertAll(x => {
                string tRet = "0";
                if (x.Checked) tRet = "1";
                return tRet;
            });
            tAuthData.AddRange(tCheckBoxData);
            string[] Update_Data = tAuthData.ToArray();


            string[] Insert_Col = { "ID", "PW", "name", "affil", "position", "Phone" };
            string[] Insert_Data = { tb_ID.Text, tb_PW.Text, tb_Name.Text, cbCompany.Text, tb_position.Text, tb_Phone.Text };

            tCmd = mDB.DB_INSERT("User_Data", Insert_Col, Insert_Data);
            Helper_DB.ExcuteNonQuery(tCmd);
            tCmd = mDB.DB_INSERT("User_Access", tUserAcess_Col, Update_Data);
            Helper_DB.ExcuteNonQuery(tCmd);
            tCmd = string.Format("INSERT INTO `User_ShortCut` (`id`) VALUES ('{0}')", tb_ID.Text);
            Helper_DB.ExcuteNonQuery(tCmd);

            UTIL.MsgI("저장되었습니다!");
            main.isAccess();
            RefreshList();
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentCell == null || dataGridView1.CurrentCell.RowIndex < 0 || dataGridView1.SelectedRows.Count == 0)
            {
                UTIL.MsgE("삭제할 행을 선택해 주세요.");
                return;
            }
            string tText = string.Format("{0} 를 수정 하시겠습니까?", dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString());
            if (UTIL.MsgQ(tText) == DialogResult.Yes)
            {
                if (tb_ID.Text == "" || tb_PW.Text == "" || tb_Name.Text == "")
                {
                    UTIL.MsgE("성명 / 아이디 / 비밀번호 를 채워주세요.");
                    return;
                }

                if (dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString() != tb_ID.Text )
                {
                    if (!CheckSelect())
                    {
                        if (!mOverlap)
                        {
                            UTIL.MsgE("아이디 중복확인을 해주세요.");
                            return;
                        }
                    }
                }
                string cmd = String.Empty;
                string[] tSearch_Col = { "ID" };
                string[] tSearch_Data = { dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString() };
                string[] Update1_Col = { "ID", "PW", "name", "affil", "position", "Phone" };
                string[] Update1_Data = { tb_ID.Text, tb_PW.Text, tb_Name.Text, cbCompany.Text, tb_position.Text, tb_Phone.Text };
                string[] tAccess_Col = { "ID" };
                string[] tAccess_Data = { tb_ID.Text };
                List<string> tAuthData = new List<string>();
                tAuthData.Add(tb_ID.Text);
                List<string> tCheckBoxData = tUserAccesschkBox.ToList().ConvertAll(x =>
                {
                    string tRet = "0";
                    if (x.Checked) tRet = "1";
                    return tRet;
                });
                tAuthData.AddRange(tCheckBoxData);
                string[] tCheckBox = tAuthData.ToArray();
                cmd = mDB.More_Update("User_ShortCut", tAccess_Col, tAccess_Data, tSearch_Col, tSearch_Data);
                Helper_DB.ExcuteNonQuery(cmd);
                cmd = mDB.More_Update("User_Access", tUserAcess_Col, tCheckBox, tSearch_Col, tSearch_Data);
                Helper_DB.ExcuteNonQuery(cmd);
                cmd = mDB.More_Update("User_Data", tAccess_Col, tAccess_Data, tSearch_Col, tSearch_Data);
                Helper_DB.ExcuteNonQuery(cmd);
                UTIL.MsgI("저장되었습니다!");
                RefreshList();
            }
        }
        private bool CheckSelect()
        {
            int row = dataGridView1.CurrentCell.RowIndex;

            string[] GridData = {
                dataGridView1.Rows[row].Cells["Per_name"].Value.ToString(),
                dataGridView1.Rows[row].Cells["Rank"].Value.ToString(),
                dataGridView1.Rows[row].Cells["Phone"].Value.ToString(),
                dataGridView1.Rows[row].Cells["ID"].Value.ToString()
            };
            string[] BoxData = {
                tb_Name.Text, tb_position.Text, tb_Phone.Text, tb_ID.Text
            };

            int count = 0;
            foreach (string data in GridData)
            {
                if (data != BoxData[count])
                    return false;
                count++;
            }
            return true;
        }

        private void btn_Empty_Click(object sender, EventArgs e)
        {
            tb_ID.Text = "";
            tb_PW.Text = "";
            tb_Name.Text = "";
            cbCompany.Text = comp_name;
            tb_position.Text = "";
            tb_Phone.Text = "";
        }

        private void btn_Del_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentCell == null || dataGridView1.CurrentCell.RowIndex < 0 || dataGridView1.SelectedRows.Count == 0)
            { 
                UTIL.MsgE("삭제할 행을 선택해 주세요.");
                return;
            }
            string tText = string.Format("{0} 를 삭제 하시겠습니까?", dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString());
            if (UTIL.MsgQ(tText) == DialogResult.Yes)
            {
                int row = dataGridView1.CurrentRow.Index;
                string tID = dataGridView1.SelectedRows[0].Cells["id"].Value.ToString();
                string tPW = dataGridView1.SelectedRows[0].Cells["pw"].Value.ToString();
                string D_cmd = string.Format("DELETE FROM User_ShortCut WHERE `ID`=\"{0}\"  LIMIT 1;", tID);
                Helper_DB.ExcuteNonQuery(D_cmd);
                D_cmd = string.Format("DELETE FROM User_Access WHERE `ID`=\"{0}\"  LIMIT 1;", tID);
                Helper_DB.ExcuteNonQuery(D_cmd);
                D_cmd = mDB.DB_Delete("User_Data", "ID", tID, "PW", tPW);
                Helper_DB.ExcuteNonQuery(D_cmd);
                UTIL.MsgI("삭제 완료되었습니다!");
                RefreshList();
            }
        }

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

        private void tb_ID_TextChanged(object sender, EventArgs e)
        {
            mOverlap = false;
        }
    }
}