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

namespace UniMarc
{
    public partial class Marc_CopyForm : Form
    {
        MarcEditorControl marcEditorControl1;
        Helper_DB db = new Helper_DB();
        String_Text st = new String_Text();
        private StatusStrip statusStrip1;
        private Panel panel5;
        private TableLayoutPanel tableLayoutPanel1;
        public RichTextBox etc1;
        public RichTextBox etc2;
        private Panel panel6;
        private Button button3;
        private Button btn_Save;
        private UC_SelectGrade uC_SelectGrade1;
        string base_midx = "";

        public Marc_CopyForm(string marcstring, string m_idx = "0")
        {
            InitializeComponent();
            base_midx = m_idx;
            db.DBcon();

            marcEditorControl1 = new MarcEditorControl();
            marcEditorControl1.db = this.db;
            marcEditorControl1.Dock = DockStyle.Fill;

            // Wire up events

            this.Controls.Add(marcEditorControl1);
            marcEditorControl1.BringToFront();
            this.StartPosition = FormStartPosition.CenterScreen;


            marcEditorControl1.LoadBookData(marcstring, null);
            var tags = st.Take_Tag(marcstring, new string[] { "245a" });
            var BookName = tags.Length > 0 ? tags[0] : "";
            this.Text = $"마크 복제 - {BookName}";

            this.uC_SelectGrade1.GradeName = "C";
            this.etc1.Text = string.Empty;
            this.etc2.Text = string.Empty;
        }

        private void InitializeComponent()
        {
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.panel5 = new System.Windows.Forms.Panel();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.etc1 = new System.Windows.Forms.RichTextBox();
            this.etc2 = new System.Windows.Forms.RichTextBox();
            this.panel6 = new System.Windows.Forms.Panel();
            this.button3 = new System.Windows.Forms.Button();
            this.btn_Save = new System.Windows.Forms.Button();
            this.uC_SelectGrade1 = new UniMarc.UC_SelectGrade();
            this.panel5.SuspendLayout();
            this.tableLayoutPanel1.SuspendLayout();
            this.panel6.SuspendLayout();
            this.SuspendLayout();
            // 
            // statusStrip1
            // 
            this.statusStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
            this.statusStrip1.Location = new System.Drawing.Point(0, 893);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(1316, 22);
            this.statusStrip1.TabIndex = 1;
            this.statusStrip1.Text = "statusStrip1";
            // 
            // panel5
            // 
            this.panel5.Controls.Add(this.tableLayoutPanel1);
            this.panel5.Controls.Add(this.panel6);
            this.panel5.Dock = System.Windows.Forms.DockStyle.Right;
            this.panel5.Location = new System.Drawing.Point(1050, 0);
            this.panel5.Name = "panel5";
            this.panel5.Size = new System.Drawing.Size(266, 893);
            this.panel5.TabIndex = 327;
            // 
            // tableLayoutPanel1
            // 
            this.tableLayoutPanel1.ColumnCount = 1;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tableLayoutPanel1.Controls.Add(this.etc1, 0, 0);
            this.tableLayoutPanel1.Controls.Add(this.etc2, 0, 1);
            this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 86);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.RowCount = 2;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(266, 807);
            this.tableLayoutPanel1.TabIndex = 0;
            // 
            // etc1
            // 
            this.etc1.BackColor = System.Drawing.SystemColors.ScrollBar;
            this.etc1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.etc1.Font = new System.Drawing.Font("굴림체", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));
            this.etc1.Location = new System.Drawing.Point(3, 3);
            this.etc1.Name = "etc1";
            this.etc1.Size = new System.Drawing.Size(260, 397);
            this.etc1.TabIndex = 32;
            this.etc1.Text = "Remark1";
            this.etc1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.etc1_KeyDown);
            // 
            // etc2
            // 
            this.etc2.BackColor = System.Drawing.SystemColors.ScrollBar;
            this.etc2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.etc2.Font = new System.Drawing.Font("굴림체", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));
            this.etc2.Location = new System.Drawing.Point(3, 406);
            this.etc2.Name = "etc2";
            this.etc2.Size = new System.Drawing.Size(260, 398);
            this.etc2.TabIndex = 32;
            this.etc2.Text = "Remark2";
            this.etc2.KeyDown += new System.Windows.Forms.KeyEventHandler(this.etc1_KeyDown);
            // 
            // panel6
            // 
            this.panel6.Controls.Add(this.uC_SelectGrade1);
            this.panel6.Controls.Add(this.button3);
            this.panel6.Controls.Add(this.btn_Save);
            this.panel6.Dock = System.Windows.Forms.DockStyle.Top;
            this.panel6.Location = new System.Drawing.Point(0, 0);
            this.panel6.Name = "panel6";
            this.panel6.Size = new System.Drawing.Size(266, 86);
            this.panel6.TabIndex = 1;
            // 
            // button3
            // 
            this.button3.Location = new System.Drawing.Point(147, 6);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(107, 33);
            this.button3.TabIndex = 405;
            this.button3.Text = "닫기";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            // 
            // btn_Save
            // 
            this.btn_Save.Location = new System.Drawing.Point(11, 6);
            this.btn_Save.Name = "btn_Save";
            this.btn_Save.Size = new System.Drawing.Size(107, 33);
            this.btn_Save.TabIndex = 215;
            this.btn_Save.Text = "저장(F9)";
            this.btn_Save.UseVisualStyleBackColor = true;
            this.btn_Save.Click += new System.EventHandler(this.btn_Save_Click);
            // 
            // uC_SelectGrade1
            // 
            this.uC_SelectGrade1.BackColor = System.Drawing.Color.White;
            this.uC_SelectGrade1.Grade = -1;
            this.uC_SelectGrade1.GradeName = "";
            this.uC_SelectGrade1.Location = new System.Drawing.Point(11, 47);
            this.uC_SelectGrade1.Name = "uC_SelectGrade1";
            this.uC_SelectGrade1.Size = new System.Drawing.Size(243, 29);
            this.uC_SelectGrade1.TabIndex = 406;
            // 
            // Marc_CopyForm
            // 
            this.ClientSize = new System.Drawing.Size(1316, 915);
            this.Controls.Add(this.panel5);
            this.Controls.Add(this.statusStrip1);
            this.Name = "Marc_CopyForm";
            this.Text = "마크 복제";
            this.Load += new System.EventHandler(this.Marc_CopyForm_Load);
            this.panel5.ResumeLayout(false);
            this.tableLayoutPanel1.ResumeLayout(false);
            this.panel6.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        private void Marc_CopyForm_Load(object sender, EventArgs e)
        {

        }

        private void btSave_Click(object sender, EventArgs e)
        {

        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            string errMsg = string.Empty;
            bool isbnWarning = false;

            // 중앙 집중식 유효성 검사 수행
            if (!marcEditorControl1.CheckValidation())
            {
                return;
            }

            var v_ISBN = this.marcEditorControl1.lbl_ISBN.Text.Trim();

            // ISBN 미포함 경고 처리
            if (isbnWarning)
            {
                var dlg = UTIL.MsgQ("저장된 ISBN이 마크데이터에 없습니다.\nISBN값이 변경되었습니다.\n그래도 저장 할까요?");
                if (dlg != DialogResult.Yes) return;
            }

            // ISBN 중복 체크 (DB 관련이므로 폼에서 처리)
            if (DB_Utils.ExistISBN(v_ISBN))
            {
                if (UTIL.MsgQ($"입력하신 ISBN({v_ISBN})은 이미 등록된 데이터가 존재합니다.\n그래도 저장하시겠습니까?") != DialogResult.Yes)
                {
                    return;
                }
            }

            //등급추가
            string v_grade = uC_SelectGrade1.Grade == -1 ? "2" : uC_SelectGrade1.Grade.ToString();
            //if (radA.Checked) v_grade = "0";
            //else if (radB.Checked) v_grade = "1";
            //else if (radC.Checked) v_grade = "2";
            //else if (radD.Checked) v_grade = "3";

            var v_remark1 = this.etc1.Text.Trim();
            var v_remark2 = this.etc2.Text.Trim();

            // 008 태그 최신화 및 056 추출
            string tag056 = marcEditorControl1.Tag056(out string with008fullstring);
            var savedMarc = this.marcEditorControl1.MakeMarcString();
            var date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


            //도서정보추출
            var v_isbn = "";
            var v_price = "";
            var v_author = "";
            var v_title = "";
            var v_publisher = "";
            var v_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            //파서를 사용해서 변경한다
            var parser = new UniMarc.MarcParser();
            parser.ParseFullMarc(savedMarc);

            //ISBN와 가격 (처음나오는 020태그의 값을 적용)
            var tag_020 = parser.GetTag<MarcField>("020").FirstOrDefault();
            if (tag_020 != null)
            {
                v_isbn = tag_020.GetSubfieldValue('a');
                v_price = tag_020.GetSubfieldValue('c');
            }

            //저자(100 -> 110 -> 111 순으로 적용)  
            var tag_100 = parser.GetTag<MarcField>("100").FirstOrDefault();
            var tag_110 = parser.GetTag<MarcField>("110").FirstOrDefault();
            var tag_111 = parser.GetTag<MarcField>("111").FirstOrDefault();
            if (tag_111 != null)
                v_author = tag_111.GetSubfieldValue('a');
            else if (tag_110 != null)
                v_author = tag_110.GetSubfieldValue('a');
            else if (tag_100 != null)
                v_author = tag_100.GetSubfieldValue('a');

            //서명
            var tag_245 = parser.GetTag<MarcSubfield>("245a").FirstOrDefault();
            v_title = tag_245?.Value ?? string.Empty;

            //출판사   
            var tag_264b = parser.GetTag<MarcSubfield>("264b").FirstOrDefault();
            var tag_260b = parser.GetTag<MarcSubfield>("260b").FirstOrDefault();
            if (tag_264b != null)
                v_publisher = tag_264b?.Value ?? string.Empty;
            else if (tag_260b != null)
                v_publisher = tag_260b?.Value ?? string.Empty;

            //056a
            var v_056 = parser.GetTag("056a").FirstOrDefault() ?? string.Empty;
            var v_008 = parser.GetTag("008").FirstOrDefault() ?? string.Empty;


            string[] insert_col = {
                "ISBN", "compidx", "marc", "marc_chk",
                "grade", "008tag", "user", "date","비고1", "비고2", "division","서명","저자","출판사","가격"
            };
            string[] insert_data = {
                v_ISBN, PUB.user.CompanyIdx.ToString(), savedMarc, "1",
                v_grade, v_008, PUB.user.UserName, date,v_remark1, v_remark2, tag056,v_title, v_author, v_publisher, v_price
            };

            string cmd = db.DB_INSERT("Marc", insert_col, insert_data);
            var rlt = Helper_DB.ExcuteNonQuery(cmd);
            if (rlt.applyCount == 1)
            {
            UTIL.MsgI("저장되었습니다.");
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
            else
            {
                UTIL.MsgE(rlt.errorMessage);
            }
        }

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

        private void etc1_KeyDown(object sender, KeyEventArgs e)
        {
            var rt = sender as RichTextBox;
            if(rt == null) return;  
            if (e.KeyCode == Keys.F5)
            {
                rt.AppendText("[" + DateTime.Now.ToString("yy-MM-dd") + "]");
            }
        }
    }
}
