using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UniMarc
{
    public partial class Mac_Output : Form
    {
        Helper_DB db = new Helper_DB();
        Main main;
        string compidx = string.Empty;
        List<string> save_date = new List<string>();
        public Mac_Output(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = PUB.user.CompanyIdx;
        }

        private void Mac_Output_Load(object sender, EventArgs e)
        {
            db.DBcon();

            string[] state = { "진행", "완료" };
            cb_state.Items.AddRange(state);
            cb_state.SelectedIndex = 0;

            string[] Encoding = { "ANSI", "UTF-8", "UniCode" };
            cb_EncodingType.Items.AddRange(Encoding);
            cb_EncodingType.SelectedIndex = 0;
        }

        private void cb_state_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_state.SelectedIndex == 0)
            {
                cb_years.Enabled = false;
            }
            else
            {
                cb_years.Enabled = true;

                int start_years = 2009;
                int now_years = Convert.ToInt32(DateTime.Now.ToString("yyyy"));
                int years_count = now_years - start_years;
                List<string> l_years = new List<string>();
                for (int a = 0; a <= years_count; a++)
                {
                    l_years.Add(start_years.ToString());
                    start_years += 1;
                }
                string[] years = l_years.ToArray();
                cb_years.Items.AddRange(years);
                cb_years.SelectedIndex = cb_years.Items.Count - 1;
            }
            Input_list_combo();
        }

        #region cb_state 선택 시 Sub함수
        private void Input_list_combo()
        {
            cb_list.Items.Clear();
            string area = "`date`, `list_name`";
            string cmd = string.Format("SELECT {0} FROM `Obj_List` WHERE `comp_num` = \"{1}\" AND `state` = \"{2}\" AND `chk_marc` > 0;",
                area, compidx, cb_state.Text);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] marc_list = db_res.Split('|');

            string[] tmp = { "", "" };
            bool years = true;

            for(int a = 0; a < marc_list.Length - 1; a++)
            {
                if (a % 2 == 0) { tmp[0] = marc_list[a];
                    years = years_UpAndDown(tmp[0]);
                    if (cb_state.SelectedIndex == 0) years = true;
                }
                if (a % 2 == 1) { tmp[1] = marc_list[a];
                    if (years) {
                        save_date.Add(tmp[0]);
                        cb_list.Items.Add(tmp[1]);
                    }
                }
            }
        }
        private bool years_UpAndDown(string years)
        {
            if(cb_years.Text == "") return false;
            int select = Convert.ToInt32(cb_years.Text);
            int year = Convert.ToInt32(years.Substring(0, 4));

            if (select != year) 
                return false;
            else 
                return true;
        }
        #endregion

        private void cb_list_SelectedIndexChanged(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            string area = "`isbn`, `book_name`, `author`, `book_comp`, `price`";
            string[] col = { "compidx", "list_name", "date" };
            string[] data = { compidx, cb_list.Text, save_date[cb_list.SelectedIndex] };
            string cmd = db.More_DB_Search("Obj_List_Book", col, data, area);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] tmp_ary = db_res.Split('|');
            Input_Grid(tmp_ary);
            Search_Marc();
        }

        #region cb_list 선택 시 Sub함수
        private void Input_Grid(string[] db_data)
        {
            string[] grid = { "", "", "", "", "", "", "" }; // isbn, 도서명, 총서명, 저자, 출판사, 정가, 마크
            for (int a = 0; a < db_data.Length; a++)
            {
                if (a % 5 == 0) { grid[0] = db_data[a]; }
                if (a % 5 == 1) { grid[1] = 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];
                    dataGridView1.Rows.Add(grid);
                }
            }
        }

        private void Search_Marc()
        {
            string area = "`총서명`, `marc`, `marc_chk`, `marc1`, `marc_chk1`, `marc2`, `marc_chk2`";
            string[] col = { "ISBN" };
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                string[] data = { dataGridView1.Rows[a].Cells["isbn"].Value.ToString() };

                string cmd = db.More_DB_Search("Marc", col, data, area);
                string db_res = db.DB_Send_CMD_Search(cmd);
                if (db_res.Length < 7) { continue; }
                string[] tmp_ary = db_res.Split('|');
                Add_Marc(tmp_ary, a);
            }
        }
        private void Add_Marc(string[] db_data, int idx)
        {
            if (db_data[2] == "1") {
                dataGridView1.Rows[idx].Cells["series"].Value = db_data[0];
                dataGridView1.Rows[idx].Cells["Marc"].Value = db_data[1];
            }
            else if (db_data[4] == "1") {
                dataGridView1.Rows[idx].Cells["series"].Value = db_data[0];
                dataGridView1.Rows[idx].Cells["Marc"].Value = db_data[3];
            }
            else if (db_data[6] == "1") {
                dataGridView1.Rows[idx].Cells["series"].Value = db_data[0];
                dataGridView1.Rows[idx].Cells["Marc"].Value = db_data[5];
            }
        }
        #endregion

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            sg.Print_Grid_Num(sender, e);
        }

        private void btn_file_save_Click(object sender, EventArgs e)
        {
            string Marc_data = "";
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["Marc"].Value.ToString() == "" &&
                    dataGridView1.Rows[a].Cells["Marc"].Value == null) continue;

                string marc = dataGridView1.Rows[a].Cells["Marc"].Value.ToString();
                Marc_data += marc.Replace("￦", "\\");
            }

            string FileName;
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Title = "저장 경로를 지정해주세요.";
            saveFile.OverwritePrompt = true;
            saveFile.Filter = "마크 파일 (*.mrc)|*.mrc|모든 파일 (*.*)|*.*";

            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                FileName = saveFile.FileName;
                switch (cb_EncodingType.SelectedIndex)
                {
                    case 0:
                        File.WriteAllText(FileName, Marc_data, Encoding.Default);
                        break;
                    case 1:
                        File.WriteAllText(FileName, Marc_data, Encoding.UTF8);
                        break;
                    case 2:
                        File.WriteAllText(FileName, Marc_data, Encoding.Unicode);
                        break;
                }
            }

            // Set_Macro sm = new Set_Macro();
            // 
            // string FileEncodingType = "";
            // 
            // switch (cb_EncodingType.SelectedIndex)
            // {
            //     case 0: FileEncodingType = "ANSI"; break;
            //     case 1: FileEncodingType = "UTF-8"; break;
            //     case 2: FileEncodingType = "UniCode"; break;
            //     default: break;
            // }
            // 
            // string[] MarcArray = new string[dataGridView1.RowCount];
            // for (int a = 0; a < dataGridView1.Rows.Count; a++)
            // {
            //     if (dataGridView1.Rows[a].Cells["marc"].Value.ToString() == "" &&
            //         dataGridView1.Rows[a].Cells["marc"].Value == null)
            //         continue;
            // 
            //     if (dataGridView1.Rows[a].Cells["colCheck"].Value.ToString() != "T")
            //         continue;
            // 
            //     string marc = dataGridView1.Rows[a].Cells["Marc"].Value.ToString().Replace("￦", "\\");
            //     marc = st.ConvertMarcType(marc);
            // 
            //     MarcArray[a] = marc;
            // }
            // 
            // sm.ViewMarcArray = MarcArray;
            // sm.FileType = FileEncodingType;
            // sm.Show();
        }

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