using CanFly.Canvas.Shape;
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;
using CanFly.Canvas.Helper;
using CanFly.Helper;
using HalconDotNet;
using System.Diagnostics;
using CanFly.Canvas.UI;


namespace CanFly.UI.GuidePanel
{
    public partial class GuideCircleCtrl : BaseGuideControl
    {

        private float _x;
        private float _y;
        private float _r;
        private FlyShape? _circle;


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




        public GuideCircleCtrl()
        {
            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)
        {
            this._circle = shape;

            _x = shape.Points[0].X;
            _y = shape.Points[0].Y;
            _r = PointHelper.Distance(shape.Points[0], shape.Points[1]);

            this.tbX.Text = shape.Points[0].X.ToString("F3");
            this.tbY.Text = shape.Points[0].Y.ToString("F3");
            this.tbR.Text = _r.ToString("F3");
        }




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

            this.canvas.OutsideShapes.Clear();
            this.canvas.Invalidate();

            flag = new List<double>();
            x = new List<double>();
            y = new List<double>();
            r = 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["XCenter"] = _x;
            inputPara["YCenter"] = _y;
            inputPara["Radius"] = _r;


            List<string> outputKeys = new List<string>()
            {
                "OUTPUT_PreTreatedImage",
                "OUTPUT_Flag",
                "RXCenter",
                "RYCenter",
                "RRadius"
            };

            ExecuteHScript(
                    inputImg,
                    inputPara,
                    outputKeys);

        }
        List<double> flag = new List<double>(), x=new List<double>(),y=new List<double>(),r=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();
             x = resultDic["RXCenter"].HTupleToDouble();
             y = resultDic["RYCenter"].HTupleToDouble();
             r = resultDic["RRadius"].HTupleToDouble();

         
         






            if (flag.Count > 0)
            {
                lblResult.Text = flag[0].ToString();

            }
            else
            {
                lblResult.Text = "无";
            }
            if (flag.Count > 0 && x.Count > 0 && y.Count > 0 && r.Count > 0)
            {

                //detectResult.VisionImageSet.MLImage = resultDic["RRadius"].GetResultObject("OUTPUT_PreTreatedImage");
                this.canvas.DrawCircle(new PointF((float)x[0], (float)y[0]), (float)r[0]);
                lblElapsed.Text = $"{timeElasped} ms";
            }
        }




        private void Test()
        {
            string filePath = Path.Combine(_hScriptsDir, GetScriptFileName());
            if (!File.Exists(filePath))
            {
                MessageBox.Show($"文件 {filePath} 不存在");
                return;
            }


            try
            {
                HDevEngineTool tool = new HDevEngineTool(_hScriptsDir);
                tool.LoadProcedure(Path.GetFileNameWithoutExtension(GetScriptFileName()));


                if (hImage == null)
                {
                    HOperatorSet.ReadImage(out hImage, CurrentImageFile);
                }

                tool.InputImageDic["INPUT_Image"] = hImage;
                tool.InputTupleDic["XCenter"] = _x;
                tool.InputTupleDic["YCenter"] = _y;
                tool.InputTupleDic["Radius"] = _r;



                if (!tool.RunProcedure(out string error, out int timeElasped))
                {
                    throw new Exception();
                }

                HTuple hFlag = tool.GetResultTuple("OUTPUT_Flag");

                var flag = tool.GetResultTuple("OUTPUT_Flag").HTupleToDouble();
                List<double> x = tool.GetResultTuple("RXCenter").HTupleToDouble();
                var y = tool.GetResultTuple("RYCenter").HTupleToDouble();
                var r = tool.GetResultTuple("RRadius").HTupleToDouble();
                if (flag.Count > 0)
                {
                    lblResult.Text = flag[0].ToString();

                }
                else
                {
                    lblResult.Text = "无";
                }
                if (flag.Count > 0 && x.Count > 0 && y.Count > 0 && r.Count > 0)
                {
                    this.canvas.DrawCircle(new PointF((float)x[0], (float)y[0]), (float)r[0]);
                    lblElapsed.Text = $"{timeElasped} ms";
                }

                //
                Debug.WriteLine("");
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                hImage?.Dispose();
                hImage = null;
            }


        }



        private void btnClose_Click(object sender, EventArgs e)
        {
            OnControlCloseEvent?.Invoke();
        }

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




        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 btnCreateCircle_Click(object sender, EventArgs e)
        {
            if (this.canvas.pixmap == null)
            {
                MessageBox.Show("请先打开图片");
                return;
            }
            this.tbX.Text = string.Empty;
            this.tbY.Text = string.Empty;
            this.tbR.Text = string.Empty;
            this.canvas.Shapes.Clear();
            this.canvas.Invalidate();
            this.canvas.StartDraw(ShapeTypeEnum.Circle);
            this.canvas.Enabled = true;
        }



        private void Canvas_newShape()
        {

            this.canvas.StopDraw();
        }

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

            //List<double> x = tool.GetResultTuple("RXCenter").HTupleToDouble();
            //var y = tool.GetResultTuple("RYCenter").HTupleToDouble();
            //var r = tool.GetResultTuple("RRadius").HTupleToDouble();
            //tool.InputTupleDic["XCenter"] = _x;
            //tool.InputTupleDic["YCenter"] = _y;
            //tool.InputTupleDic["Radius"] = _r;
            string inputput = $"XCenter:{string.Join(";", _x)};YCenter:{string.Join(";", _y)};RRadius:{string.Join(";", _r)}";
            string output = $"RXCenter:{string.Join(";", x[0])};RYCenter:{string.Join(";", y[0])};RRadius:{string.Join(";", r[0])}";

            DataToTriggerEvent(inputput,output);
        }
    }
}