using CanFly.Canvas.Helper;
using CanFly.Canvas.Shape;
using CanFly.Canvas.UI;
using CanFly.Helper;
using HalconDotNet;
using OpenCvSharp;
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 CanFly.UI.GuidePanel
{
    public partial class GuideHeightCtrl : BaseGuideControl
    {



        private FlyShape? _line;


        private float _lineX1;
        private float _lineY1;
        private float _lineX2;
        private float _lineY2;
        float width, height;
        private float _lineWidth;
        private PointF[] _rectPoints = new PointF[4];
        //private float _LineLX=new float();
        //private float _LineLY =new float();
        //private float _LineRX =new float();
        //private float _LineRY =new float();





        protected override string GetScriptFileName() => "HeightMeasure.hdvp";



        public GuideHeightCtrl()
        {
            InitializeComponent();

            this.canvas.mouseMoved += Canvas_mouseMoved;
            this.canvas.OnShapeUpdateEvent += UpdateShape;
            this.canvas.selectionChanged += Canvas_selectionChanged;

            this.canvas.OnShapeMoving += Canvas_OnShapeMoving;
            this.canvas.newShape += Canvas_newShape;

            this.ctrlTitleBar.OnCloseClicked += OnControlClose;



        }



        protected override void UpdateShape(FlyShape shape)
        {
            switch (shape.ShapeType)
            {
                case ShapeTypeEnum.Rectangle:
                    this._line = shape;

                    var pts = this._line.Points;

                    _lineX1 = pts[0].X;
                    _lineY1 = pts[0].Y;
                    _lineX2 = pts[1].X;
                    _lineY2 = pts[1].Y;
                    _lineWidth = shape.LineVirtualRectWidth;
                    _rectPoints = shape.LineVirtualRectPoints;
                    //_LineLX = (shape.LineVirtualRectPoints[0].X + shape.LineVirtualRectPoints[3].X) / 2;
                    //_LineLY = (shape.LineVirtualRectPoints[0].Y + shape.LineVirtualRectPoints[3].Y) / 2;
                    //_LineRX = (shape.LineVirtualRectPoints[1].X + shape.LineVirtualRectPoints[2].X) / 2;
                    //_LineRY = (shape.LineVirtualRectPoints[1].Y + shape.LineVirtualRectPoints[2].Y) / 2;

                    width = Math.Abs(_lineX2 - _lineX1);
                    height = Math.Abs(_lineY2 - _lineY1);


                    tbLineX1.Text = _lineX1.ToString("F3");
                    tbLineY1.Text = _lineY1.ToString("F3");
                    tbLineX2.Text = _lineX2.ToString("F3");
                    tbLineY2.Text = _lineY2.ToString("F3");
                    tbwidth.Text = width.ToString();
                    tbheight.Text = height.ToString();
                    // NumRectWidth1.Value = (decimal)_lineWidth;
                    break;

                default:
                    break;
            }
        }





        private void GuideLineCircleCtrl_Load(object sender, EventArgs e)
        {



        }




        private void Canvas_mouseMoved(PointF pos)
        {
            if (InvokeRequired)
            {
                Invoke(Canvas_mouseMoved, pos);
                return;
            }

            lblStatus.Text = $"X:{pos.X}, Y:{pos.Y}";

        }




        private void Canvas_selectionChanged(List<FlyShape> shapes)
        {
            //if (shapes.Count != 1)
            //{
            //    // panelGuide.Controls.Clear();
            //    return;
            //}
            //SwitchGuideForm(shapes[0].ShapeType);
            // Canvas_OnShapeUpdateEvent(shapes[0]);

            if (shapes.Count != 1)
            {
                return;
            }
            UpdateShape(shapes[0]);

        }



        private void Canvas_OnShapeMoving(List<FlyShape> shapes)
        {
            if (shapes.Count != 1)
            {
                return;
            }

            UpdateShape(shapes[0]);
        }







        private void btnCreateLine_Click(object sender, EventArgs e)
        {
            if (this.canvas.pixmap == null)
            {
                MessageBox.Show("请先打开图片");
                return;
            }
            tbLineX1.Text = string.Empty;
            tbLineY1.Text = string.Empty;
            tbLineX2.Text = string.Empty;
            tbLineY2.Text = string.Empty; ;
            tbwidth.Text = string.Empty; ;
            tbheight.Text = string.Empty; ;
            this.canvas.Shapes.RemoveAll(shp => shp.ShapeType == ShapeTypeEnum.Rectangle);
            this.canvas.Invalidate();
            this.canvas.StartDraw(ShapeTypeEnum.Rectangle);

        }



        private void btnLoadImage_Click(object sender, EventArgs e)
        {
            OpenImageFile(bitmap =>
            {
                this.canvas.LoadPixmap(bitmap);
                this.canvas.Enabled = true;


            });
        }


        private void Canvas_newShape()
        {
            this.canvas.StopDraw();
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            if (this.canvas.pixmap == null)
            {
                MessageBox.Show("请先打开图片");
                return;
            }
            if (this.tbLineX1.Text.Trim().Length == 0)
            {
                MessageBox.Show("请先创建矩形");
                return;
            }
            this.canvas.OutsideShapes.Clear();
            this.canvas.Invalidate();


            flag = new List<double>();

            Line1Para = new List<double>();
            Line2Para = new List<double>();
            iHeight = new List<double>();
            Dictionary<string, HObject> inputImg = new Dictionary<string, HObject>();

            if (hImage == null)
            {
                HOperatorSet.ReadImage(out hImage, CurrentImageFile);
            }
            inputImg["INPUT_Image"] = hImage;
   

            Dictionary<string, HTuple> inputPara = new Dictionary<string, HTuple>();


            inputPara["row"] = _lineY1;
            inputPara["column"] = _lineX1;
            inputPara["Width"] = width;
            inputPara["Height"] = height;



            List<string> outputKeys = new List<string>()
            {
                "OUTPUT_PreTreatedImage",
                "OUTPUT_Flag",

                "Line1Para",
                "Line2Para",
                "iHeight"
            };

            ExecuteHScript(
                    inputImg,
                    inputPara,
                    outputKeys);

        }


        List<double> flag = new List<double>();
        List<double> Line1Para = new List<double>();
        List<double> Line2Para = new List<double>();
       
        List<double> iHeight = new List<double>();


        protected override void OnExecuteHScriptResult(
            bool success,
            Dictionary<string, HTuple> resultDic,
            int timeElasped)
        {
            if (!success)
            {
                return;
            }


            /*
               "OUTPUT_Flag",
                "RXCenter",
                "RYCenter",
                "RRadius"
             */

            flag = resultDic["OUTPUT_Flag"].HTupleToDouble();

            Line1Para = resultDic["Line1Para"].HTupleToDouble();
            Line2Para = resultDic["Line2Para"].HTupleToDouble();
           // EndRow = resultDic["EndRow"].HTupleToDouble();
            //EndCloumn = resultDic["EndColumn"].HTupleToDouble();
            iHeight = resultDic["iHeight"].HTupleToDouble();
      
            if (flag.Count > 0)
            {
                lblResult.Text = flag[0].ToString();

            }
            else
            {
                lblResult.Text = "无";
            }
            if (flag.Count > 0 && Line1Para.Count == 4 && Line2Para.Count == 4 && iHeight.Count > 0)
            {
                float width = 0;
                this.canvas.DrawLine(new PointF((float)Line1Para[1], (float)Line1Para[0]), new PointF((float)Line1Para[3], (float)Line1Para[2]), 0);
                this.canvas.DrawLine(new PointF((float)Line2Para[1], (float)Line2Para[0]), new PointF((float)Line2Para[3], (float)Line2Para[2]), 0);
                this.canvas.Invalidate();
                lblElapsed.Text = $"{timeElasped} ms";
            }
        }



        private void btnSave_Click(object sender, EventArgs e)
        {
            if (lblResult.Text.Equals("无"))
            {
                MessageBox.Show("请先进行绘制");
                return;
            }
            if (lblResult.Text != "0")
            {
                MessageBox.Show("测量计算错误,无法保存");
                return;
            }

           

            string input = $"row:{string.Join(";", _lineY1)};column:{string.Join(";", _lineX1)};" +
                $"Width:{string.Join(";", width)};Height:{string.Join(";", height)}";
   
            string output = $"iHeight:{string.Join(";", iHeight[0])}";
            DataToTriggerEvent(input, output);
        }

        private void tbLineX1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}