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 WindowsFormsApp1.Account
{
    public partial class Purchase_Aggregation : Form
    {
        Main main;
        Helper_DB db = new Helper_DB();
        public string compidx;
        public Purchase_Aggregation(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = main.com_idx;
        }
        private void Purchase_Aggregation_Load(object sender, EventArgs e)
        {
            db.DBcon();
            radioButton2.Checked = true;
            start_date.Value = new DateTime(int.Parse(DateTime.Now.ToString("yyyy")),
                                                 int.Parse(DateTime.Now.ToString("MM")), 1);
        }
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            Column1.HeaderText = "매입일자";
            Column2.HeaderText = "";
            Column7.HeaderText = "합계금액";
            Column8.HeaderText = "";
        }
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            Column1.HeaderText = "거래처명";
            Column2.HeaderText = "이월미수금";
            Column7.HeaderText = "기간잔고";
            Column8.HeaderText = "최종잔고";
        }
        private void btn_Lookup_Click(object sender, EventArgs e)
        {
            // 매입일자 / 거래처 / 권수 / 매입금액 / 결제금액
            string Select_Area = "`buy_date`, `purchase`, `count`, `buy_money`, `payment`";
            dataGridView1.Rows.Clear();
            string[] Search_col = { "compidx" };
            string[] Search_data = { compidx };
            string db_tmp = db.More_DB_Search("Buy_ledger", Search_col, Search_data, Select_Area);
            string[] db_data = db_tmp.Split('|');
            input_Grid(db_data);
        }
        private void input_Grid(string[] db_data) 
        { 
            // 매입일자 / . / 건수 / 권수 / 매입금액 / 결제금액 / 합계금액 / . /
            // 거래처명 / 이월미수금 / 건수 / 권수 / 매입금액 / 결제금액 / 기간잔고 / 최종잔고
            string[] grid = { "", "", "0", "0", "0", "0", "0", "", "" };
            int cases = 0;
            if (radioButton1.Checked == true) {
                for (int a = 0; a < db_data.Length - 1; a++)
                {
                    if (a % 5 == 0) { grid[0] = db_data[a].Substring(0, 10); }             // 매입일자
                    if (a % 5 == 2) { grid[3] = db_data[a]; }                              // 권수
                    if (a % 5 == 3) { grid[4] = db_data[a]; }                              // 매입금액
                    if (a % 5 == 4) { grid[5] = db_data[a]; date_grid_sub(grid, cases); }  // 결제금액
                }
            }
            else {
                for (int a = 0; a < db_data.Length - 1; a++)
                {
                    if (a % 5 == 0) { grid[8] = db_data[a].Substring(0, 10); }             // 매입일자(H)
                    if (a % 5 == 1) { grid[0] = db_data[a]; }                              // 거래처명
                    if (a % 5 == 2) { grid[3] = db_data[a]; }                              // 권수
                    if (a % 5 == 3) { grid[4] = db_data[a]; }                              // 매입금액
                    if (a % 5 == 4) { grid[5] = db_data[a]; date_grid_sub(grid, cases); }  // 결제금액
                }
            }
        }
        private void date_grid_sub(string[] grid, int cases)
        {
            string str_end = end_date.Value.ToString().Substring(0, 10);
            string str_start = start_date.Value.ToString().Substring(0, 10);
            
            if (radioButton1.Checked == true) {
                bool chk_grid = false;
                if (DateTime.Parse(str_start) <= DateTime.Parse(grid[0]) && 
                    DateTime.Parse(str_end) >= DateTime.Parse(grid[0])) {
                    cases += 1;
                    chk_grid = true;
                }
                grid[2] = cases.ToString();
                int buy = 0, pay = 0;
                buy += Convert.ToInt32(grid[4]);
                pay += Convert.ToInt32(grid[5]);
                int total = buy - pay;
                grid[6] = total.ToString();
            
                if(chk_grid == true) {
                    if (dataGridView1.Rows.Count > 0) {
                        if (case_up(grid) == false) {
                            dataGridView1.Rows.Add(grid);
                        } 
                    }
                    else if (dataGridView1.Rows.Count == 0) {
                        dataGridView1.Rows.Add(grid);
                    }
                }
            }
            // 0.거래처명 1.이월미수금 2.건수 3.권수 4.매입금액 5.결제금액 6.기간잔고 7.최종잔고 8.매입일자(H)
            else if (radioButton2.Checked == true || radioButton3.Checked == true || radioButton4.Checked == true){
                string msg = "";
                int chk_idx = over_chk(grid);
                if (chk_idx >= 0) {
                    mk_grid(grid, str_start, str_end, chk_idx);
                }
                if (DateTime.Parse(str_start) > DateTime.Parse(grid[8]) && 
                    DateTime.Parse(str_end) < DateTime.Parse(grid[8])) {
                    grid[3] = "0"; grid[4] = "0"; grid[5] = "0";
                }
                // Grid내에 자료가 없을경우 DB에서 불러온 자료 일단 추가
                if (chk_idx == -1) {
                    if (DateTime.Parse(str_start) > DateTime.Parse(grid[8])) {
                        grid = ex_handling(grid); 
                    }
                    else { 
                        grid[1] = "0"; 
                        grid[7] = chk_final(grid).ToString();
                    }
                    for(int a = 0; a < grid.Length; a++)
                    {
                        msg += grid[a] + " | ";
                    }
                    dataGridView1.Rows.Add(grid);
                }
            }
        }
        private int chk_final(string[] grid)
        {
            if (grid[4] != "0") {
                return Convert.ToInt32(grid[4]);
            }
            if (grid[5] != "0") {
                return Convert.ToInt32(grid[5]) * -1;
            }
            return 0;
        }
        private string[] ex_handling(string[] grid)
        {
            int buy = Convert.ToInt32(grid[4]);
            int pay = Convert.ToInt32(grid[5]);
            int remain = buy - pay;
            grid[1] = remain.ToString();
            grid[3] = "0";
            grid[4] = "0";
            grid[5] = "0";
            grid[7] = remain.ToString();
            return grid;
        }
        private void mk_grid(string[] grid, string start, string end, int idx)
        {
            int cases = Convert.ToInt32(dataGridView1.Rows[idx].Cells[2].Value.ToString());
            int book_count = Convert.ToInt32(dataGridView1.Rows[idx].Cells[3].Value.ToString());
            int buy = 0;
            if (dataGridView1.Rows[idx].Cells[4].Value.ToString() != "0") {
                buy = Convert.ToInt32(dataGridView1.Rows[idx].Cells[4].Value.ToString());
            }
            int pay = 0;
            if (dataGridView1.Rows[idx].Cells[5].Value.ToString() != "0") {
                pay = Convert.ToInt32(dataGridView1.Rows[idx].Cells[5].Value.ToString());
            }
            int book_count_plus = Convert.ToInt32(grid[3]);
            int buy_plus = Convert.ToInt32(grid[4]);
            int pay_plus = Convert.ToInt32(grid[5]);
            if (DateTime.Parse(start) > DateTime.Parse(grid[8])) {      // 지정된 날짜 이전
                int remain = 0;
                if (dataGridView1.Rows[idx].Cells[1].Value.ToString() != "") {
                    remain = Convert.ToInt32(dataGridView1.Rows[idx].Cells[1].Value.ToString());
                }
                remain += buy_plus - pay_plus;
                dataGridView1.Rows[idx].Cells[1].Value = remain.ToString();
            }
            if (DateTime.Parse(start) <= DateTime.Parse(grid[8]) && 
                DateTime.Parse(end) >= DateTime.Parse(grid[8])) {       // 지정된 날짜 포함
                cases += 1;
                book_count += book_count_plus;
                pay += pay_plus;
                buy += buy_plus;
                int total_plus = 0;
                total_plus += buy - pay;
                dataGridView1.Rows[idx].Cells[2].Value = cases.ToString();
                dataGridView1.Rows[idx].Cells[3].Value = book_count.ToString();
                dataGridView1.Rows[idx].Cells[4].Value = buy.ToString();
                dataGridView1.Rows[idx].Cells[5].Value = pay.ToString();
                dataGridView1.Rows[idx].Cells[6].Value = total_plus.ToString();
            }
            int final = 0;
            if (dataGridView1.Rows[idx].Cells[7].Value.ToString() != "") {
                final = Convert.ToInt32(dataGridView1.Rows[idx].Cells[7].Value.ToString());
            }
            final += buy_plus - pay_plus;
            dataGridView1.Rows[idx].Cells[7].Value = final.ToString();
        }
        private int over_chk(string[] grid)
        {
            int grididx = dataGridView1.Rows.Count;
            for(int a = 0; a < grididx; a++)
            {
                if (dataGridView1.Rows[a].Cells[0].Value.ToString() == grid[0]) {
                    return a;
                }
            }
            return -1;
        }
        /// 
        /// 일자별 정렬로 체크되었을 경우 Grid에 나타내는 함수
        /// 
        /// 
        /// True일 경우, Grid내 값만 변경 / False일 경우, Grid추가
        private bool case_up(string[] grid)
        {
            int grididx = dataGridView1.Rows.Count;
            if (grid[0] == dataGridView1.Rows[grididx - 1].Cells[0].Value.ToString()) {
                int cases = Convert.ToInt32(dataGridView1.Rows[grididx - 1].Cells[2].Value.ToString());
                int book_count = Convert.ToInt32(dataGridView1.Rows[grididx - 1].Cells[3].Value.ToString());
                int buy = 0;
                if (dataGridView1.Rows[grididx - 1].Cells[4].Value.ToString() != "") { 
                    buy = Convert.ToInt32(dataGridView1.Rows[grididx - 1].Cells[4].Value.ToString().Replace(",", ""));
                }
                int pay = 0;
                if (dataGridView1.Rows[grididx - 1].Cells[5].Value.ToString() != "") {
                    pay = Convert.ToInt32(dataGridView1.Rows[grididx - 1].Cells[5].Value.ToString().Replace(",", ""));
                }
                int book_count_plus = Convert.ToInt32(grid[3]);
                int buy_plus = Convert.ToInt32(grid[4]);
                int pay_plus = Convert.ToInt32(grid[5]);
                cases += 1;
                book_count += book_count_plus;
                buy += buy_plus;
                pay += pay_plus;
                int total_plus = 0;
                total_plus += buy - pay;
                dataGridView1.Rows[grididx - 1].Cells[2].Value = cases.ToString();
                dataGridView1.Rows[grididx - 1].Cells[3].Value = book_count.ToString();
                dataGridView1.Rows[grididx - 1].Cells[4].Value = buy.ToString();
                dataGridView1.Rows[grididx - 1].Cells[5].Value = pay.ToString();
                dataGridView1.Rows[grididx - 1].Cells[6].Value = total_plus.ToString();
                return true;
            }
            else {
                return false;
            }
        }
        private void btn_Close_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            // 일자별이나 전체에선 더블클릭 이벤트 활성화 되지않음.
            if(radioButton1.Checked == true || radioButton4.Checked == true) { return; }
            Purchase_Book pb = new Purchase_Book(this);
            pb.MdiParent = main;
            pb.WindowState = FormWindowState.Maximized;
            pb.tb_purchase.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            pb.start_Date.Value = DateTime.Parse(start_date.Value.ToString());
            pb.end_Date.Value = DateTime.Parse(end_date.Value.ToString());
            pb.Show();
            pb.btn_Lookup_Click(null, null);
            
        }
    }
}