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_Book : Form
    {
        Main main;
        Sales_Deposit sd;
        Helper_DB db = new Helper_DB();
        public string compidx;
        public int row = -1;
        public Sales_Book(Sales_Deposit _sd, Main _main)
        {
            InitializeComponent();
            sd = _sd;
            compidx = sd.compidx;
            main = _main;
        }
        public Sales_Book(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = PUB.user.CompanyIdx;
        }
        private void Sales_Book_Load(object sender, EventArgs e)
        {
            db.DBcon();
        }
        public void btn_Lookup_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            // grid
            // [0]매출일자 / [1]내용 / [2]수량 / [3]출고율 / [4]매출금액 / [5]입금액 / [6]현잔액 / [7]비고
            string[] grid = { "", "", "", "", "", "", "0", "" };
            // db
            // [0]매출일자 / [1]책이름 / [2]수량 / [3]출고율 / [4]매출금액 / [5]입금액 / [6]비고 / [7]입금구분
            string Area = "`date`, `book_name`, `count`, `out_per`, `out_price`, `deposit`, `etc`, `gu`";
            string[] sear_col = { "compidx", "client" };
            string[] sear_data = { compidx, tb_clt.Text };
            string cmd = db.More_DB_Search("Sales", sear_col, sear_data, Area);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] ary = db_res.Split('|');
            input_grid(grid, ary);
        }
        #region btn_Lookup_Click_Sub
        private void input_grid(string[] grid, string[] db)
        {
            int count = 8;
            for(int a = 0; a < db.Length; a++)
            {
                if (a % count == 0) { grid[0] = db[a]; }
                if (a % count == 1) { grid[1] = db[a]; }
                if (a % count == 2) { grid[2] = db[a]; }
                if (a % count == 3) { grid[3] = db[a]; }
                if (a % count == 4) { grid[4] = db[a]; }
                if (a % count == 5) { grid[5] = db[a]; }
                if (a % count == 6) { grid[7] = db[a]; }
                if (a % count == 7) {
                    if (db[a] != "") {
                        grid[1] = "입금 " + db[a];
                    }
                    set_grid(grid);
                }
            }
            set_now_money(dataGridView1.Rows.Count);
        }
        private void set_grid(string[] grid)
        {
            DateTime start = Start_Date.Value;
            DateTime end = End_Date.Value;
            DateTime sear = Convert.ToDateTime(grid[0]);

            bool date_chk = false;

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

            int row = accord_grid(grid);
            if (date_chk)
            {
                int out_price = Convert.ToInt32(grid[4]);
                int in_price = Convert.ToInt32(grid[5]);
                if (row > 0) {
                    int ori_out_price = Convert.ToInt32(dataGridView1.Rows[row].Cells["out_price"].Value.ToString());
                    int ori_in_price = Convert.ToInt32(dataGridView1.Rows[row].Cells["in_price"].Value.ToString());

                    out_price += ori_out_price;
                    in_price += ori_in_price;

                    dataGridView1.Rows[row].Cells["out_price"].Value = out_price.ToString();
                    dataGridView1.Rows[row].Cells["in_price"].Value = in_price.ToString();
                }
                if (row <= 0) {
                    dataGridView1.Rows.Add(grid);
                }
            }
            else if (!date_chk)
            {
                set_remain(grid, row);
            }
        }
        private void set_remain(string[] grid, int row)
        {
            if (dataGridView1.Rows.Count <= 0) {
                string[] grid_base = { "이월미수금", "", "", "", "", "", "0", "" };
                dataGridView1.Rows.Add(grid_base);
            }
            int out_price = Convert.ToInt32(grid[4]);
            int in_price = Convert.ToInt32(grid[5]);
            int result = Convert.ToInt32(dataGridView1.Rows[row].Cells["now_money"].Value.ToString());
            result += out_price - in_price;
            dataGridView1.Rows[0].Cells["now_money"].Value = result.ToString();
        }
        private void set_now_money(int count)
        {
            for(int a = 0; a < count; a++)
            {
                if (dataGridView1.Rows[0].Cells["out_date"].Value.ToString() != "이월미수금") {
                    string[] grid_base = { "이월미수금", "", "", "", "", "", "0", "" };
                    dataGridView1.Rows.Insert(0, grid_base);
                    count++;
                }

                int money_idx = a - 1;
                if (a - 1 < 1) { money_idx = 0; }
                if (a < 1) { continue; }

                int cout = Convert.ToInt32(dataGridView1.Rows[a].Cells["count"].Value.ToString());
                int out_price = Convert.ToInt32(dataGridView1.Rows[a].Cells["out_price"].Value.ToString());
                int in_price = Convert.ToInt32(dataGridView1.Rows[a].Cells["in_price"].Value.ToString());
                int money = Convert.ToInt32(dataGridView1.Rows[money_idx].Cells["now_money"].Value.ToString());

                set_total(cout, out_price, in_price);

                money += out_price - in_price;

                dataGridView1.Rows[a].Cells["now_money"].Value = money.ToString();
            }
        }
        private void set_total(int count, int out_price, int in_price)
        {
            int text_count = Convert.ToInt32(tb_count.Text.Replace(",", ""));
            int text_out = Convert.ToInt32(tb_out.Text.Replace(",", ""));
            int text_in = Convert.ToInt32(tb_in.Text.Replace(",", ""));

            text_count += count;
            text_out += out_price;
            text_in += in_price;

            tb_count.Text = text_count.ToString();
            tb_out.Text = text_out.ToString();
            tb_in.Text = text_in.ToString();
        }
        private int accord_grid(string[] grid)
        {
            int result = 0;
            bool[] check_list = { false, false, false };
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["out_date"].Value.ToString() == grid[0]) {
                    check_list[0] = true;
                }
                if (dataGridView1.Rows[a].Cells["out_per"].Value.ToString() == grid[3]) {
                    check_list[1] = true;
                }
                if (dataGridView1.Rows[a].Cells["etc"].Value.ToString() == grid[7]) {
                    check_list[2] = true;
                }
                if (check_list[0] && check_list[1] && check_list[2]) {
                    result = a;
                }
            }
            return result;
        }
        #endregion
        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void tb_count_TextChanged(object sender, EventArgs e)
        {
            String_Text st = new String_Text();
            st.Int_Comma(sender, e);
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            if (row < 0) { return; }
            if (dataGridView1.Rows[row].Cells["out_date"].Value.ToString() == "이월미수금") { return; }
            if (dataGridView1.Rows[row].Cells["content"].Value.ToString() == "입금 통장" ||
                dataGridView1.Rows[row].Cells["content"].Value.ToString() == "입금 카드" ||
                dataGridView1.Rows[row].Cells["content"].Value.ToString() == "입금 현금" ||
                dataGridView1.Rows[row].Cells["content"].Value.ToString() == "입금 어음") { return; }
            var sde = main.OpenFormInTab(() => new Sales_Detail(this));
            string out_date = dataGridView1.Rows[e.RowIndex].Cells["out_date"].Value.ToString().Substring(0, 10).Replace("-", "");
            int yesr = Convert.ToInt32(out_date.Substring(0, 4));
            int month = Convert.ToInt32(out_date.Substring(4, 2));
            int day = Convert.ToInt32(out_date.Substring(6, 2));
            sde.Out_Date.Value = new DateTime(yesr, month, day);
            sde.tb_clt.Text = tb_clt.Text;
        }
    }
}
