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 Project.Dialog
{
    public partial class fNewReelID : Form
    {
        public string NewID { get; set; }
        public fNewReelID(string custcode)
        {
            InitializeComponent();
            this.NewID = string.Empty;
            tbCustCode.Text = custcode;

            if (Pub.Result.JobType2 == "RET")
                radReturn.Checked = true;
            else
                radNormal.Checked = false;


            tbRID.TextChanged += (s1, e1) =>
            {
                lbLen.Text = $"길이({tbRID.Text.Length})";
                lbLen.BackColor = tbRID.Text.Length == 15 ? Color.Lime : Color.Tomato;
            };
        }
        private void fNewReelID_Load(object sender, EventArgs e)
        {
            tbtype.Text = "C";
            tbLoca.Text = Pub.setting.ReelIdDeviceLoc;
            tbDiv.Text = Pub.setting.ReelIdDeviceID;
            tbYear.Text = DateTime.Now.Year.ToString().Substring(2);
            tbMon.Text = DateTime.Now.Month.ToString("X");
            this.radNormal.Checked = true;
            RefreshID();
        }

        private void btOK_Click(object sender, EventArgs e)
        {
            var codelen = 15;
            this.NewID = tbRID.Text;
            if (this.NewID.Length != codelen)
            {
                Util.MsgE($"Reel ID는 {codelen}자리 입니다");
                return;
            }

            //db에서도 검색한다
            var db = new EEEntities();
            if (db.Component_Reel_Result.Where(t => t.RID == NewID).Any())
            {
                Util.MsgE($"해당 ID는 발행 기록이 있는 ID 입니다\n값:{NewID}");
                return;
            }

            //서버에서 중복검사실행
            if (Pub.setting.OnlineMode == false)
            {
                Util.MsgE("오프라인 모드라 사용할 수 없습니다");
                return;
            }

            var rlt = Amkor.RestfulService.get_existed_matl_by_id(NewID);
            if (rlt.Complete == false)
            {
                Util.MsgE("중복검사 실패\n" + rlt.Message);
                return;
            }
            else if (rlt.Result == true)
            {
                Util.MsgE("REEL ID 가 중복되었습니다\n새로고침 하세요");
                return;
            }

            ////데이터를 추가해준다.
            //var db = new EEEntities();
            //db.Component_Reel_NewAssign.Add(new Component_Reel_NewAssign()
            //{
            //	bPrint = false,
            //	CUST = tbCustCode.Text.Trim(),
            //	TIME = tbYear.Text.Trim(),
            //	DIV = tbDiv.Text.Trim(),
            //	SEQ = tbSeq.Text,
            //	RID = tbRID.Text.Trim(),
            //	wdate = DateTime.Now,
            //	wuid = Pub.setting.Asset,
            //});
            //db.SaveChanges();

            DialogResult = DialogResult.OK;
        }
        void UpdateRID()
        {
            var data = tb1.Text.Trim();
            data += tbtype.Text.Trim();
            data += tbCustCode.Text.Trim();
            data += tbLoca.Text.Trim();
            data += tbDiv.Text.Trim();
            data += tbYear.Text.Trim();
            data += tbMon.Text.Trim();
            data += tbSeq.Text.Trim();
            this.tbRID.Text = data;
        }

        private void tbCustCode_TextChanged(object sender, EventArgs e)
        {
            UpdateRID();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RefreshID();
        }
        void RefreshID()
        {
            if (tbCustCode.Text.Length != 4)
            {
                tbCustCode.Focus();
                tbCustCode.SelectAll();
            }


            //시간정보업데이트
            tbYear.Text = DateTime.Now.ToString("yy");
            tbDiv.Text = Pub.setting.ReelIdDeviceID; //라벨어태치용

            UpdateSN();
            UpdateRID();
        }

        /// <summary>
        /// 일련번호 업데이트
        /// </summary>
        void UpdateSN()
        {
            var datestr = this.tbYear.Text + this.tbMon.Text;
            if (datestr.Length != 3)
            {
                Util.MsgE("년도/월 값이 입력되지 않았습니다");
                return;
            }

            var newsn = string.Empty;

            if (this.radReturn.Checked)
                newsn = AmkorReelID.GetNextSNbyYM_Return(datestr);
            else if (this.radDup.Checked)
                newsn = AmkorReelID.GetNextSNbyYM_Dup(datestr);
            else
                newsn = AmkorReelID.GetNextSNbyYM(datestr);

            tbSeq.Text = newsn;
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Util.TouchKeyShow(tbCustCode, "고객코드를 입력하세요");
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Util.TouchKeyShow(tbDiv, "장치 분류를 입력(L:Logistic/M:Manufacture,A:AutoLabel Attach)");
        }

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Util.TouchKeyShow(tbSeq, "일련번호입력(001~999)");
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Util.TouchKeyShow(tbYear, "년도(2자리)");
        }

        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Util.TouchKeyShow(tb1, "예약됨(R)");
        }

        private void linkLabel6_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Util.TouchKeyShow(tbtype, "예약됨(C/I)");
        }

        private void linkLabel7_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Util.TouchKeyShow(tbLoca, "발행처(3/4/5)");
        }

        private void linkLabel8_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Util.TouchKeyShow(tbMon, "월(1자리 10월=A,11월=B,12월=C");
        }

        private void button8_Click(object sender, EventArgs e)
        {
            //중복검사
            var rid = tbRID.Text.Trim();
            if (rid.isEmpty())
            {
                Util.MsgE("Reel Id 값이 없습니다");
                return;
            }

            //db에서도 검색한다
            if (Pub.setting.OnlineMode)
            {
                var db = new EEEntities();
                if (db.Component_Reel_Result.Where(t => t.RID == rid).Any())
                {
                    Util.MsgE($"해당 ID는 발행 기록이 있는 ID 입니다\n값:{rid}");
                    return;
                }

                var result = Amkor.RestfulService.get_existed_matl_by_id(rid);
                if (result.Complete == false)
                {
                    Util.MsgE("중복검사 서버 오류\n" + result.Message);
                }
                else
                {
                    if (result.Result == true)
                    {
                        Util.MsgE($"해당 ID는 중복된 ID 입니다\n값:{rid}");
                        return;
                    }
                    else
                    {
                        Util.MsgI($"해당 ID는 중복되지 않았습니다\n{rid}");
                    }
                }
            }

        }

        private void chkReturn_CheckedChanged(object sender, EventArgs e)
        {
            UpdateSN();
            UpdateRID();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            UpdateSN();
        }

        private void radNormal_Click(object sender, EventArgs e)
        {
            UpdateSN();
            UpdateRID();
        }
    }
}
