using Emgu.CV.Structure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace Project.Class
{

    public class VisionData
    {
        public int RetryLoader { get; set; }
        public List<string> bcdMessage { get; set; }
        public Boolean LightOn { get; set; }
        public DateTime STime;      //비젼시작시간
        public DateTime ETime;      //비젼종료시간
        public TimeSpan RunTime { get { return ETime - STime; } }   //비젼동작시간
        public DateTime GTime;      //이미지수집시간
        public string FileNameL;    //로딩존 촬영
        public string FileNameU;    //언로딩존 촬영
        public Boolean Complete;

        //public Boolean AngleQR { get; set; }
        //public Boolean AngleSTD { get; set; }
        //public double Angle { get; set; }

        //public Boolean IsAngleSet
        //{
        //    get
        //    {
        //        if (AngleQR == false && AngleSTD == false && Angle == 0.0) return true;
        //        else return false;
        //    }
        //}
        public double ApplyAngle { get; set; }     //적용된 회전 각도
        public Boolean NeedCylinderForward { get; set; } //부착시 실린더를 올려야하는가
        public Boolean ApplyOffset { get; set; }
        public Boolean BaseAngle(out string msg, out KeyenceBarcodeData bcd)
        {

            msg = string.Empty;
            bcd = null;

            //데이터없다면 회전하지 못한다.
            if (this.barcodelist == null || this.barcodelist.Count < 1)
            {
                msg = "No barcode data";
                return false;
            }

            //사용자가 확정한 코드를 우선으로 한다
            bcd = barcodelist.Where(t => t.UserActive).FirstOrDefault();
            if (bcd != null)
            {
                //angle = bcd.Angle;
                msg = "User Active";
                return true;
            }

            //표준바코드를 최우선 으로 사용
            //15자리 기존 바코드는 angle 로 사용하지 않는다.
            bcd = barcodelist.Where(t => t.isSTDBarcode && t.isNewLen15 == false).FirstOrDefault();
            if (bcd != null)
            {
                //angle = bcd.Angle;
                msg = "STD Barcode";
                return true;
            }

            //QR코드를 우선으로 사용 - return 릴은 적용하지 안게한다.
            //RQ코드가 적용되지 않게한다  210824
            bcd = barcodelist.Where(t => t.sym == "1" && t.isNewLen15 == false && t.Data.EndsWith(";;;") == false && t.Data.StartsWith("RQ")==false).FirstOrDefault();
            if (bcd != null)
            {
                //angle = bcd.Angle;
                msg = "QR Code";
                return true;
            }

            //첫번쨰 아이템을 우선으로 사용
            if (barcodelist.Count == 1)
            {
                bcd = barcodelist[0];
                msg = "First Barcode = " + bcd.Data;
                return true;
            }
            else
            {
                //여러개가 있음
                bcd = barcodelist.Where(t => t.sym == "0").FirstOrDefault();
                if (bcd != null)
                {
                    msg = "1D Data";
                    return true;
                }
                else
                {
                    bcd = barcodelist[0];
                    msg = "first";
                    return true;
                }
            }


            // angle = bcd.Angle;
            //return true;
        }   //모션회전각도
        public Boolean Ready { get; set; }
        public Boolean ServerUpdate { get; set; }

        public Boolean Confirm { get { return ConfirmAuto || ConfirmUser; } }
        public Boolean ConfirmUser { get; set; }
        public Boolean ConfirmAuto { get; set; }

        public Boolean ValidSkipbyUser { get; set; }

        public string QTY0 { get; set; }        //원본수량
        public string QTY { get; set; }       //바코드수량(=서버수량)

        /// <summary>
        /// QTY값이 RQ에서 입력된 데이터인가?
        /// </summary>
        public Boolean QTYRQ { get; set; }

        public string SID0 { get; set; }    //원본SID
        public string SID { get; set; }     //바코드

        private string _rid = string.Empty;
        public string RID
        {
            get { return _rid; }
        }     //바코드        
        public void SetRID(string value, string reason)
        {
            //값이 변경될때 로그에 변경
            if (_rid.Equals(value) == false)
            {
                Pub.AddDebugLog(string.Format("RID 변경 {0} -> {1} by {2}", _rid, value, reason));
            }
            _rid = value;
        }

        public string RID0 { get; set; }
        public string VLOT { get; set; }
        public string VNAME { get; set; }
        //public string SCODE { get; set; } //서플라이코드  210219
        public string MFGDATE { get; set; }
        public string PARTNO { get; set; }
        public Boolean HASHEADER { get; set; }

        public string temp_custcode { get; set; }
        public string temp_custname { get; set; }

        /// <summary>
        /// 데이터가 모두존재하는지 확인
        /// </summary>
        public Boolean DataValid
        {
            get
            {
                if (Confirm == false) return false;
                return QTY.isEmpty() == false &&
                    SID.isEmpty() == false &&
                    RID.isEmpty() == false &&
                    VLOT.isEmpty() == false &&
                    VNAME.isEmpty() == false &&
                    MFGDATE.isEmpty() == false &&
                    PARTNO.isEmpty();
            }
        }


        public Boolean PrintPositionCheck { get; set; }
        public string PrintPositionData { get; set; }

        //상단위치에 프린트를 할것인가?
        //프린트위치에 따른다
        public ePrintPutPos GetPrintPutPosition()
        {
            //하단에 찍는경우이다
            if (PrintPositionData == "1" ||
                PrintPositionData == "2" ||
                PrintPositionData == "3")
            {
                return ePrintPutPos.Bottom;
            }
            else if (PrintPositionData == "7" ||
                PrintPositionData == "8" ||
                PrintPositionData == "9")
            {
                return ePrintPutPos.Top;
            }
            else if (PrintPositionData == "4")  //왼쪽
            {
                return ePrintPutPos.Middle;
            }
            else if (PrintPositionData == "6")  //오른쪽
            {
                return ePrintPutPos.Middle;
            }
            else return ePrintPutPos.None;

        }
        //public string LabelPos { get; set; }
        //public Boolean PrintForce { get; set; }

        public eCartSize ReelSize { get; set; }

        public string QTY2 { get; set; }       //바코드수량
        public string SID2 { get; set; }     //바코드
        public string RID2 { get; set; }     //바코드        
        public string VLOT2 { get; set; }
        public string MANU2 { get; set; }
        public string MFGDATE2 { get; set; }
        public string PARTNO2 { get; set; }

        public Emgu.CV.Image<Gray, Byte> image { get; private set; }    //최종수집된 이미지

        public void SetImage(Emgu.CV.Image<Gray, Byte> img_)
        {
            if (this.image != null)
            {
                this.image.Dispose();
                this.image = null;
            }

            //이미지를 신규로 해성하고 데이터를 복사한다  210121
            this.image = new Emgu.CV.Image<Gray, byte>(img_.Size);
            img_.CopyTo(this.image);

        }
        public System.Drawing.Color GetColorByBarcodeCount(int idx)
        {
            if (QRPositionData[idx] > 0) return Color.Gold; //QR데이터가있다면 금색으로 한다

            var Cnt = LabelPositionData[idx];
            if (Cnt == MaxBarcodePosData) return Color.Purple;
            else if (Cnt == 0) return Color.FromArgb(32, 32, 32);
            {
                //나머진 숫자별로 데이터를 표시한다 (
                var GValue = Cnt * 10;
                if (GValue > 255) GValue = 255;
                return Color.FromArgb(32, 32, GValue);
            }

        }
        public Boolean isMaxBarcodePosition(int idx)
        {
            return LabelPositionData[idx] == MaxBarcodePosData;
        }

        public byte[] QRPositionData { get; private set; }
        public byte[] LabelPositionData { get; private set; }
        private List<Class.KeyenceBarcodeData> _barcodelist;
        //리더기로부터 읽은 자료 모두가 들어잇다
        public List<Class.KeyenceBarcodeData> barcodelist
        {
            get { return _barcodelist; }
            set
            {
                this._barcodelist = value;
                UpdateBarcodePositionData();
            }
        }

        public byte MaxBarcodePosData { get; private set; }
        /// <summary>
        /// 바코드목록을 이용해서 라벨위치 분포값을 변경합낟.
        /// 해당 위치값은 labelposdata로 접근가능함
        /// </summary>
        public void UpdateBarcodePositionData()
        {
            LabelPositionData[0] = (byte)_barcodelist.Where(t => t.LabelPosition == 1).Count();
            LabelPositionData[1] = (byte)_barcodelist.Where(t => t.LabelPosition == 2).Count();
            LabelPositionData[2] = (byte)_barcodelist.Where(t => t.LabelPosition == 3).Count();

            LabelPositionData[3] = (byte)_barcodelist.Where(t => t.LabelPosition == 4).Count();
            LabelPositionData[4] = (byte)_barcodelist.Where(t => t.LabelPosition == 6).Count();

            LabelPositionData[5] = (byte)_barcodelist.Where(t => t.LabelPosition == 7).Count();
            LabelPositionData[6] = (byte)_barcodelist.Where(t => t.LabelPosition == 8).Count();
            LabelPositionData[7] = (byte)_barcodelist.Where(t => t.LabelPosition == 9).Count();

            QRPositionData[0] = (byte)_barcodelist.Where(t => t.LabelPosition == 1 && t.AmkorData.isValid).Count();
            QRPositionData[1] = (byte)_barcodelist.Where(t => t.LabelPosition == 2 && t.AmkorData.isValid).Count();
            QRPositionData[2] = (byte)_barcodelist.Where(t => t.LabelPosition == 3 && t.AmkorData.isValid).Count();

            QRPositionData[3] = (byte)_barcodelist.Where(t => t.LabelPosition == 4 && t.AmkorData.isValid).Count();
            QRPositionData[4] = (byte)_barcodelist.Where(t => t.LabelPosition == 6 && t.AmkorData.isValid).Count();

            QRPositionData[5] = (byte)_barcodelist.Where(t => t.LabelPosition == 7 && t.AmkorData.isValid).Count();
            QRPositionData[6] = (byte)_barcodelist.Where(t => t.LabelPosition == 8 && t.AmkorData.isValid).Count();
            QRPositionData[7] = (byte)_barcodelist.Where(t => t.LabelPosition == 9 && t.AmkorData.isValid).Count();

            MaxBarcodePosData = LabelPositionData.Max(t => t);
        }

        /// <summary>
        /// Data1(인쇄전 인식데이터) 과 Data2(QR)가 동일한지 비교합니다.
        /// </summary>
        public Boolean MatchValidation
        {
            get
            {
                if (PARTNO == null) this.PARTNO = string.Empty;
                if (PARTNO2 == null) this.PARTNO2 = string.Empty;
                if (QTY == null) QTY = string.Empty;
                if (QTY2 == null) QTY2 = string.Empty;
                if (SID == null) SID = string.Empty;
                if (SID2 == null) SID2 = string.Empty;
                if (VLOT == null) VLOT = string.Empty;
                if (VLOT2 == null) VLOT2 = string.Empty;
                if (PARTNO == null) PARTNO = string.Empty;
                if (PARTNO2 == null) PARTNO2 = string.Empty;

                if (QTY.Equals(QTY2) == false)
                {
                    Pub.log.AddE(string.Format("QR검증실패 수량:{0} != {1}", QTY, QTY2));
                    return false;
                }
                if (RID.Equals(RID2) == false)
                {
                    Pub.log.AddE(string.Format("QR검증실패 RID:{0} != {1}", RID, RID2));
                    return false;
                }
                if (VLOT.Equals(VLOT2) == false)
                {
                    Pub.log.AddE(string.Format("QR검증실패 VLOT:{0} != {1}", VLOT, VLOT2));
                    return false;
                }
                if (PARTNO.Equals(PARTNO2) == false)
                {
                    Pub.log.AddE(string.Format("QR검증실패 PARTNO:{0} != {1}", PARTNO, PARTNO2));
                    return false;
                }
                if (SID.Equals(SID2) == false)
                {
                    Pub.log.AddE(string.Format("QR검증실패 SID:{0} != {1}", SID, SID2));
                    return false;
                }

                return true;
            }
        }

        public string QRInputRaw { get; set; }  //입력에 사용한 RAW
        public string QROutRaw { get; set; }    //부착된 QR코드의 값
        public string ZPL { get; set; } //출력시 사용한 ZPL
        public string QRData { get; set; }  //출력시 사용한 ZPL에 포함된 QR데이터

        public VisionData(string reason)
        {
            Clear(reason, false);
        }
        public Boolean isEmpty()
        {
            return RID.isEmpty();
        }
        public void Clear(string reason, Boolean timeBackup)
        {
            RetryLoader = 0;
            ApplyOffset = false;
            var baktime = new DateTime(1982, 11, 23);
            if (timeBackup) baktime = this.STime;
            bcdMessage = new List<string>();

         
            HASHEADER = false;
            temp_custcode = string.Empty;
            temp_custname = string.Empty;
            RID0 = string.Empty;
            LightOn = false;
            //SCODE = string.Empty;
            ValidSkipbyUser = false;
            NeedCylinderForward = false;
            ApplyAngle = 0;
            MaxBarcodePosData = 0;
            PrintPositionCheck = false;
            LabelPositionData = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            QRPositionData = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            ReelSize = eCartSize.None;
            // PrintForce = false;
            ConfirmAuto = false;
            ConfirmUser = false;
            if (image != null)
            {
                image.Dispose();
                image = null;
            }
            ServerUpdate = false;
            PrintPositionData = "";
            //LabelPos = "";
            _barcodelist = new List<KeyenceBarcodeData>();
            QRInputRaw = string.Empty;
            QROutRaw = string.Empty;
            ZPL = string.Empty;
            QRData = string.Empty;

            STime = baktime;// DateTime.Parse("1982-11-23");
            ETime = DateTime.Parse("1982-11-23");
            GTime = DateTime.Parse("1982-11-23");
            Complete = false;
            //Angle = 0.0;
            //AngleQR = false;
            //AngleSTD = false;
            Ready = false;
            QTY0 = string.Empty;
            QTY = string.Empty;// string.Empty;
            QTYRQ = false;
			Pub.log.AddI($"비젼개체 CLEAR 로 RQ 상태 초기화(false)");

            SID0 = string.Empty;
            SID = string.Empty;
            //RID = string.Empty;
            SetRID(string.Empty, reason);
            VLOT = string.Empty;
            MFGDATE = string.Empty;
            VNAME = string.Empty;
            PARTNO = string.Empty;

            QTY2 = "0";// string.Empty;
            SID2 = string.Empty;
            RID2 = string.Empty;
            VLOT2 = string.Empty;
            MFGDATE2 = string.Empty;
            MANU2 = string.Empty;
            PARTNO2 = string.Empty;

            FileNameL = string.Empty;
            FileNameU = string.Empty;

            Pub.log.Add($"Vision Data Clear : {reason}");
        }

        public void CopyTo(ref VisionData obj)
        {
            //바코드메세지 복사
            obj.bcdMessage = new List<string>();
            foreach (var item in this.bcdMessage)
                obj.bcdMessage.Add(item);

            obj.ApplyOffset = this.ApplyOffset;
            obj.ConfirmAuto = this.ConfirmAuto;
            obj.ConfirmUser = this.ConfirmUser;
            obj.temp_custcode = this.temp_custcode;
            obj.temp_custname = this.temp_custname;
            obj.LightOn = this.LightOn;
            //obj.SCODE = this.SCODE;
            obj.ValidSkipbyUser = this.ValidSkipbyUser;
            obj.NeedCylinderForward = this.NeedCylinderForward; //210207
            obj.ApplyAngle = this.ApplyAngle; //210207
            obj.STime = this.STime;
            obj.ETime = this.ETime;
            obj.GTime = this.GTime;
            obj.FileNameL = this.FileNameL;
            obj.FileNameU = this.FileNameU;
            obj.Complete = this.Complete;
            //obj.Angle = this.Angle;
            //obj.AngleQR = this.AngleQR;
            //obj.AngleSTD = this.AngleSTD;
            obj.Ready = this.Ready;
            obj.QTY = this.QTY;
            obj.QTYRQ = this.QTYRQ;
            obj.SID = this.SID;
            obj.SID0 = this.SID0; //210331
            obj.SetRID(this.RID, "copy");//	 obj.RID = this.RID;
            obj.RID0 = this.RID0;
            obj.VLOT = this.VLOT;
            obj.VNAME = this.VNAME;
            obj.MFGDATE = this.MFGDATE;
            obj.PARTNO = this.PARTNO;

            obj.QTY2 = this.QTY2;
            obj.SID2 = this.SID2;
            obj.RID2 = this.RID2;
            obj.VLOT2 = this.VLOT2;
            obj.MANU2 = this.MANU2;
            obj.MFGDATE2 = this.MFGDATE;
            obj.PARTNO2 = this.PARTNO2;

            obj.QRInputRaw = this.QRInputRaw;
            obj.QROutRaw = this.QROutRaw;
            obj.ZPL = this.ZPL;
            obj.QRData = this.QRData;
            obj.PrintPositionData = this.PrintPositionData;
            //obj.PrintForce = this.PrintForce;
            obj.ReelSize = this.ReelSize;
            obj.PrintPositionCheck = this.PrintPositionCheck;


            //라벨위치값 복사
            for (int i = 0; i < obj.LabelPositionData.Length; i++)
                obj.LabelPositionData[i] = this.LabelPositionData[i];
            for (int i = 0; i < obj.QRPositionData.Length; i++)
                obj.QRPositionData[i] = this.QRPositionData[i];
            if (obj.image != null)
            {
                obj.image.Dispose();
                obj.image = null;
            }

            //이미지를 복사해준다. 210121
            if (this.image != null)
            {
                obj.image = new Emgu.CV.Image<Gray, byte>(this.image.Size);
                this.image.CopyTo(obj.image);
            }

            //바코드 데이터를 복사해준다.             
            obj.barcodelist = new List<KeyenceBarcodeData>();
            if (this.barcodelist.Count > 0)
            {
                foreach (var bcd in this.barcodelist)
                {
                    var newitema = new KeyenceBarcodeData
                    {
                        Angle = bcd.Angle,
                        CenterPX = new Point(bcd.CenterPX.X, bcd.CenterPX.Y),
                        Data = bcd.Data,
                        LabelPosition = bcd.LabelPosition,
                        UserActive = bcd.UserActive,
                        sym = bcd.sym,
                    };

                    newitema.vertex = new Point[bcd.vertex.Length];
                    bcd.vertex.CopyTo(newitema.vertex, 0);
                    bcd.AmkorData.CopyTo(newitema.AmkorData);
                    obj.barcodelist.Add(newitema);
                }
            }

        }
    }
}
