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.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UniMarc
{
    public partial class Part_time : Form
    {
        string compidx;
        Main main;
        Helper_DB db = new Helper_DB();
        public Part_time(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = PUB.user.CompanyIdx;
        }

        private void Part_time_Load(object sender, EventArgs e)
        {
            db.DBcon();
            Setting_combo();
            Setting_Date();
            Setting_Etc();
        }
        #region Load_Sub
        /// <summary>
        /// 콤보박스 초기 세팅
        /// </summary>
        private void Setting_combo()
        {
            string[] start = {
                "8시", "9시", "10시", "11시", "12시",
                "13시", "14시", "15시", "16시", "17시",
                "18시", "19시", "20시", "21시", "22시"
            };
            cb_start_hour.Items.AddRange(start);

            string[] end = {
                "8시", "9시", "10시", "11시", "12시",
                "13시", "14시", "15시", "16시", "17시",
                "18시", "19시", "20시", "21시", "22시"
            };
            cb_end_hour.Items.AddRange(end);

            string[] set_time = { "직접입력", "풀타임 (9시~18시)", "오전 (9시~12시)", "오후 (13시~18시)" };
            cb_work_time.Items.AddRange(set_time);

            //string tmp_db = db.search
        }
        /// <summary>
        /// 조회창 datepicker 세팅
        /// </summary>
        private void Setting_Date()
        {
            int year = DateTime.Now.Year;
            int month = DateTime.Now.Month;
            int day = DateTime.Now.Day;
            if (day < 10)
            {
                if (month - 1 <= 0)
                {
                    year--;
                    month = 12;
                }
                month--;
            }
            day = 10;
            string set_start = string.Format("{0}-{1}-{2}", year, month, day);
            start_date.Value = DateTime.Parse(set_start);
        }
        /// <summary>
        /// 기타 세팅
        /// </summary>
        private void Setting_Etc()
        {
            rb_minpay.Checked = true;
            for(int a = 0; a < dataGridView1.Columns.Count; a++)
            {
                if (a == 0 || a == 2 || a == 3)  {
                    dataGridView1.Columns[a].ReadOnly = true;
                }
            }

            string cmd = db.DB_Select_Search("`name`", "Part_Time", "compidx", compidx);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] ary_name = db_res.Split('|');
            for (int a = 0; a < ary_name.Length - 1; a++)
            {
                cb_name.Items.Add(ary_name[a]);
            }

        }
        #endregion

        private void btn_Add_Click(object sender, EventArgs e)
        {
            #region 날짜 설정
            string date = set_date.Value.ToString().Substring(0, 10);
            #endregion

            #region 근무 시작종료 설정
            if (cb_start_hour.SelectedIndex > cb_end_hour.SelectedIndex) {
                int tmp = cb_start_hour.SelectedIndex;
                cb_start_hour.SelectedIndex = cb_end_hour.SelectedIndex;
                cb_end_hour.SelectedIndex = tmp;
            }
            string start_time = Regex.Replace(cb_start_hour.Text, @"\D", "");
            if (cb_start_hour.SelectedIndex < 0) { UTIL.MsgE("시간이 선택되지 않았습니다!"); return; }
            else if (start_30min.Checked) { start_time += ":30"; }
            else { start_time += ":00"; }

            string end_time = Regex.Replace(cb_end_hour.Text, @"\D", "");
            if (cb_end_hour.SelectedIndex < 0) { UTIL.MsgE("시간이 선택되지 않았습니다!"); return; }
            else if (end_30min.Checked) { end_time += ":30"; }
            else { end_time += ":00"; }
            #endregion

            #region 근무시간 계산
            double start_work = cb_start_hour.SelectedIndex;
            if (start_30min.Checked) { start_work += 0.5; }

            double end_work = cb_end_hour.SelectedIndex;
            if (end_30min.Checked) { end_work += 0.5; }

            double work = end_work - start_work;
            #endregion

            #region 시급입력
            string pay = "";
            if (rb_minpay.Checked) { pay = "8720"; }
            else { pay = tb_pay.Text; }
            #endregion

            string[] grid = { date, "", start_time, end_time, "0", work.ToString(), pay, "", "False" };

            dataGridView1.Rows.Add(grid);
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            string[] input_area = { "compidx", "date", "name", "start", "end", 
                                    "work_time", "pay", "work" };
            if (!chk_name()) return;
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                string[] input_data = {
                    compidx,
                    dataGridView1.Rows[a].Cells["date"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["Per_name"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["start"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["end"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["today"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["pay"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["work"].Value.ToString()
                };
                string Incmd = db.DB_INSERT("Part_Time", input_area, input_data);
                Helper_DB.ExcuteNonQuery(Incmd);
            }
            UTIL.MsgI("저장되었습니다!");
        }
        #region Save_Sub
        /// <summary>
        /// 이름에 빈칸이 있는지 확인
        /// </summary>
        /// <returns></returns>
        private bool chk_name()
        {
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["per_name"].Value.ToString() == "")
                {
                    UTIL.MsgE("이름이 빈칸입니다!");
                    return false;
                }
            }
            return true;
        }
        #endregion

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++) 
            {
                if (dataGridView1.Rows[a].Cells["del_chk"].Value.ToString() == "True") {
                    dataGridView1.Rows.RemoveAt(a);
                }
            }
            UTIL.MsgI("삭제되었습니다!");
        }

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

        private void btn_Lookup_Click(object sender, EventArgs e)
        {
            dataGridView2.Rows.Clear();

            string Area = "`date`, `name`, `start`, `end`, `work_time`, `pay`, `work`";
            string[] s_date = { start_date.Value.ToString("yyyy-MM-dd"), end_date.Value.ToString("yyyy-MM-dd") };
            string cmd = db.Search_Date("Part_Time", Area, "date", s_date[0], s_date[1], compidx);
            string db_res = db.DB_Send_CMD_Search(cmd);
            input_Grid(db_res.Split('|'));
            total_pay();
        }
        #region Lookup_Sub
        private void input_Grid(string[] data)
        {
            string[] grid = { "", "", "", "", "", "", "", "" };
            for(int a = 0; a < data.Length; a++)
            {
                if (a % 7 == 0) { grid[0] = data[a]; }
                if (a % 7 == 1) { grid[1] = data[a]; }
                if (a % 7 == 2) { grid[2] = data[a]; }
                if (a % 7 == 3) { grid[3] = data[a]; }
                if (a % 7 == 4) { grid[4] = data[a]; }
                if (a % 7 == 5) { grid[5] = data[a]; }
                if (a % 7 == 6) {
                    grid[6] = res_pay(grid);
                    grid[7] = data[a];
                    if (filter_name(grid)) { dataGridView2.Rows.Add(grid); }
                }
            }
        }
        private string res_pay(string[] grid)
        {
            double time = Convert.ToDouble(grid[4]);
            double pay = Convert.ToDouble(grid[5]);
            double res = time * pay;
            return res.ToString();
        }
        private void total_pay()
        {
            double total = 0;
            for(int a = 0; a < dataGridView2.Rows.Count; a++)
            {
                double pay = Convert.ToDouble(dataGridView2.Rows[a].Cells["total"].Value.ToString());
                total += pay;
            }
            lbl_pay.Text = string.Format("{0:#,###}", total);
        }
        private bool filter_name(string[] grid)
        {
            if (cb_name.SelectedIndex == -1) return true;
            if (grid[1] == cb_name.Text) return true;
            return false;
        }
        #endregion

        private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            int col = e.ColumnIndex;
            int row = e.RowIndex;
            string name = dataGridView1.Columns[col].Name;
            if (name == "minus")
            {
                string str_start = dataGridView1.Rows[row].Cells["start"].Value.ToString();
                if (str_start.Contains(":30")) { str_start = str_start.Replace(":30", ".5"); }
                else { str_start = str_start.Replace(":00", ""); }
                double start_work = Convert.ToDouble(str_start);

                string str_end = dataGridView1.Rows[row].Cells["end"].Value.ToString();
                if (str_end.Contains(":30")) { str_end = str_end.Replace(":30", ".5"); }
                else { str_end = str_end.Replace(":00", ""); }
                double end_work = Convert.ToDouble(str_end);

                string value = dataGridView1.Rows[row].Cells[col].Value.ToString();
                value = Regex.Replace(value, @"\D", "");
                double minus = Convert.ToDouble(value);
                double total = end_work - start_work - minus;
                dataGridView1.Rows[row].Cells["today"].Value = total.ToString();
            }
        }

        private void cb_work_time_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cb_work_time.SelectedIndex)
            {
                case 0:
                    break;
                case 1:
                    cb_start_hour.SelectedIndex = 1;
                    cb_end_hour.SelectedIndex = 10;
                    break;
                case 2:
                    cb_start_hour.SelectedIndex = 1;
                    cb_end_hour.SelectedIndex = 4;
                    break;
                case 3:
                    cb_start_hour.SelectedIndex = 5;
                    cb_end_hour.SelectedIndex = 10;
                    break;
                default:
                    break;
            }
        }

        private void rb_pay_CheckedChanged(object sender, EventArgs e)
        {
            if (rb_pay.Checked) { tb_pay.Enabled = true; }
            else { tb_pay.Enabled = false; }
        }

        private void tb_pay_KeyPress(object sender, KeyPressEventArgs e)
        {
            String_Text st = new String_Text();
            st.Only_Int(sender, e);
        }
    } 
}
