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
{
    public partial class Sales_Deposit : Form
    {
        public string compidx;
        Main main;
        Helper_DB db = new Helper_DB();
        public Sales_Deposit(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = PUB.user.CompanyIdx;
        }
        private void Sales_Deposit_Load(object sender, EventArgs e)
        {
            db.DBcon();
            Start_Date.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            rb_clt.Checked = true;
        }
        private void btn_Lookup_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            string[] grid = { "", "0", "0", "0", "0", "0", "0", "0" };
            string start = Start_Date.Text.Substring(0, 10);
            string end = End_Date.Text.Substring(0, 10);
            if (rb_Date.Checked) {
                string Area = "`date`, `count`, `out_price`, `deposit`";
                string cmd = db.Search_Date("Sales", Area, "date", start, end, compidx);
                string db_res = db.DB_Send_CMD_Search(cmd);

                input_Grid_Date(grid, db_res);
            }
            else if (rb_clt.Checked) {
                string Area = "`client`, `count`, `out_price`, `deposit`, `date`";
                string cmd = db.DB_Select_Search(Area, "Sales", "compidx", compidx);
                string db_res = db.DB_Send_CMD_Search(cmd);
                input_Grid_Clt(grid, db_res);
            }
            Print_Total();
        }
        #region btn_Lookup_Click_Sub
        private void Print_Total()
        {
            int[] grid = { 0, 0, 0, 0, 0, 0, 0, 0 };    // [0]번은 버림.

            for (int a = 0; a < dataGridView1.Rows.Count; a++) 
            {
                if (rb_clt.Checked) {    // 1,7 계산
                    grid[1] += Convert.ToInt32(dataGridView1.Rows[a].Cells["grid1"].Value.ToString());
                    grid[7] += Convert.ToInt32(dataGridView1.Rows[a].Cells["grid7"].Value.ToString());
                }
                grid[2] += Convert.ToInt32(dataGridView1.Rows[a].Cells["grid2"].Value.ToString());
                grid[3] += Convert.ToInt32(dataGridView1.Rows[a].Cells["grid3"].Value.ToString());
                grid[4] += Convert.ToInt32(dataGridView1.Rows[a].Cells["grid4"].Value.ToString());
                grid[5] += Convert.ToInt32(dataGridView1.Rows[a].Cells["grid5"].Value.ToString());
                grid[6] += Convert.ToInt32(dataGridView1.Rows[a].Cells["grid6"].Value.ToString());
            }
            tb_grid1.Text = grid[1].ToString();
            tb_grid2.Text = grid[2].ToString();
            tb_grid3.Text = grid[3].ToString();
            tb_grid4.Text = grid[4].ToString();
            tb_grid5.Text = grid[5].ToString();
            tb_grid6.Text = grid[6].ToString();
            tb_grid7.Text = grid[7].ToString();
        }
        #endregion

        #region 라디오버튼 "일자별" 활성화
        private void input_Grid_Date(string[] grid, string value)
        {
            // grid
            // [0]매출일자 / [1]     / [2]건수 / [3]권수 / [4]매출금액 / [5]입금액 / [6]합계금액 / [7]         / 
            // 
            // db
            // [0]매출일자 / [1]권수 / [2]매출금액 / [3]입금액

            string[] ary = value.Split('|');
            string[] db = { "", "", "", "" };
            int cot = 4;
            for (int a = 0; a < ary.Length; a++) 
            {
                if (a % cot == 0) { db[0] = ary[a]; }
                if (a % cot == 1) { db[1] = ary[a]; }
                if (a % cot == 2) { db[2] = ary[a]; }
                if (a % cot == 3) { db[3] = ary[a];
                    setting_grid_date(grid, db);
                }
            }
        }
        private void setting_grid_date(string[] grid, string[] db)
        {
            if (dataGridView1.Rows.Count <= 0) {
                base_grid_date(grid, db);
                return;
            }
            bool lap = false;
            int row = 0;
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["grid0"].Value.ToString() == db[0]) { 
                    lap = true; 
                    row = a; 
                }
            }
            if (lap) {

                int count = Convert.ToInt32(dataGridView1.Rows[row].Cells["grid2"].Value.ToString());
                int EA = Convert.ToInt32(dataGridView1.Rows[row].Cells["grid3"].Value.ToString());
                int sales = Convert.ToInt32(dataGridView1.Rows[row].Cells["grid4"].Value.ToString());
                int dep = Convert.ToInt32(dataGridView1.Rows[row].Cells["grid5"].Value.ToString());

                count++;
                EA += Convert.ToInt32(db[1]);
                sales += Convert.ToInt32(db[2]);
                dep += Convert.ToInt32(db[3]);

                int total = sales - dep;

                dataGridView1.Rows[row].Cells["grid2"].Value = count.ToString();
                dataGridView1.Rows[row].Cells["grid3"].Value = EA.ToString();
                dataGridView1.Rows[row].Cells["grid4"].Value = sales.ToString();
                dataGridView1.Rows[row].Cells["grid5"].Value = dep.ToString();
                dataGridView1.Rows[row].Cells["grid6"].Value = total.ToString();
            }
            else {
                base_grid_date(grid, db);
            }
        }
        private void base_grid_date(string[] grid, string[] db)
        {
            int total = Convert.ToInt32(db[2]) - Convert.ToInt32(db[3]);

            grid[0] = db[0];
            grid[2] = "1";
            grid[3] = db[1];
            grid[4] = db[2];
            grid[5] = db[3];
            grid[6] = total.ToString();
            dataGridView1.Rows.Add(grid);

            return;
        }
        #endregion

        #region 라디오버튼 "거래처별" 활성화
        private void input_Grid_Clt(string[] grid, string value)
        {
            // grid
            // [0]거래처명 / [1]이월미수금 / [2]건수 / [3]권수 / [4]매출금액 / [5]입금액 / [6]기간잔고 / [7]최종잔고 /
            // 
            // db
            // [0]거래처명 / [1]권수 / [2]매출금액 / [3]입금액 / [4] 매출일자
            string[] ary = value.Split('|');
            string[] db = { "", "", "", "", "" };

            for(int a= 0; a < ary.Length; a++)
            {
                if (a % 5 == 0) { db[0] = ary[a]; }
                if (a % 5 == 1) { db[1] = ary[a]; }
                if (a % 5 == 2) { db[2] = ary[a]; }
                if (a % 5 == 3) { db[3] = ary[a]; }
                if (a % 5 == 4) { db[4] = ary[a];
                    setting_grid_Clt(grid, db);
                }
            }
        }
        private void setting_grid_Clt(string[] grid, string[] db)
        {
            DateTime start = Start_Date.Value;
            DateTime end = End_Date.Value;
            DateTime sear = Convert.ToDateTime(db[4]);

            bool date_chk = false;
            bool chk = false;

            if (sear >= start && sear < end) { date_chk = true; }
            if (sear > end) { return; }

            if (dataGridView1.Rows.Count == 0) {
                grid[0] = db[0];
                dataGridView1.Rows.Add(grid);
            }
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["grid0"].Value.ToString() == db[0])
                {
                    if (!date_chk)
                    {
                        int sales = Convert.ToInt32(db[2]);
                        int dep = Convert.ToInt32(db[3]);
                        int remain = sales - dep;

                        int _remain = Convert.ToInt32(dataGridView1.Rows[a].Cells["grid1"].Value.ToString());
                        _remain += remain;
                        dataGridView1.Rows[a].Cells["grid1"].Value = _remain.ToString();
                    }
                    else
                    {
                        int count = Convert.ToInt32(dataGridView1.Rows[a].Cells["grid2"].Value.ToString());
                        int EA = Convert.ToInt32(dataGridView1.Rows[a].Cells["grid3"].Value.ToString());
                        int sales = Convert.ToInt32(dataGridView1.Rows[a].Cells["grid4"].Value.ToString());
                        int dep = Convert.ToInt32(dataGridView1.Rows[a].Cells["grid5"].Value.ToString());

                        count++;
                        EA += Convert.ToInt32(db[1]);
                        sales += Convert.ToInt32(db[2]);
                        dep += Convert.ToInt32(db[3]);

                        int mid = sales - dep;
                        int fin = Convert.ToInt32(dataGridView1.Rows[a].Cells["grid1"].Value.ToString()) + mid;

                        dataGridView1.Rows[a].Cells["grid2"].Value = count.ToString();
                        dataGridView1.Rows[a].Cells["grid3"].Value = EA.ToString();
                        dataGridView1.Rows[a].Cells["grid4"].Value = sales.ToString();
                        dataGridView1.Rows[a].Cells["grid5"].Value = dep.ToString();
                        dataGridView1.Rows[a].Cells["grid6"].Value = mid.ToString();
                        dataGridView1.Rows[a].Cells["grid7"].Value = fin.ToString();
                    }
                    chk = false;
                    break;
                }
                else
                {
                    chk = true;
                }
            }
            if (chk)
            {
                grid[0] = db[0];
                grid[3] = db[1];
                grid[4] = db[2];
                grid[5] = db[3];
                dataGridView1.Rows.Add(grid);
            }

        }
        #endregion
        private void radio_Button_CheckedChanged(object sender, EventArgs e)
        {
            string text = ((RadioButton)sender).Text;
            bool chk = ((RadioButton)sender).Checked;

            if (text == "일자별" && chk) {
                dataGridView1.Columns[0].HeaderText = "매출일자";
                dataGridView1.Columns[1].HeaderText = "";
                dataGridView1.Columns[2].HeaderText = "건수";
                dataGridView1.Columns[3].HeaderText = "권수";
                dataGridView1.Columns[4].HeaderText = "매출금액";
                dataGridView1.Columns[5].HeaderText = "입금액";
                dataGridView1.Columns[6].HeaderText = "합계금액";
                dataGridView1.Columns[7].HeaderText = "";
            }
            else if (text == "거래처별" && chk)
            {
                dataGridView1.Columns[0].HeaderText = "거래처명";
                dataGridView1.Columns[1].HeaderText = "이월미수금";
                dataGridView1.Columns[2].HeaderText = "건수";
                dataGridView1.Columns[3].HeaderText = "권수";
                dataGridView1.Columns[4].HeaderText = "매출금액";
                dataGridView1.Columns[5].HeaderText = "입금액";
                dataGridView1.Columns[6].HeaderText = "기간잔고";
                dataGridView1.Columns[7].HeaderText = "최종잔고";
            }
            btn_Lookup_Click(null, null);
        }
        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tb_grid7_TextChanged(object sender, EventArgs e)
        {
            String_Text st = new String_Text();
            st.Int_Comma(sender, e);
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (rb_Date.Checked) return;
            if (e.RowIndex < 0) { return; }
            var sb = main.OpenFormInTab(() => new Sales_Book(this, main));
            sb.row = e.RowIndex;
            sb.tb_clt.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            sb.Start_Date.Value = DateTime.Parse(Start_Date.Value.ToString());
            sb.End_Date.Value = DateTime.Parse(End_Date.Value.ToString());
            sb.btn_Lookup_Click(null, null);
        }
    }
}
