using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using Lucee.WebBase.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Lucee.WebBase.Utils;
using System.Net;

public partial class Temp_TempDraw : System.Web.UI.Page
{
    public static BoxType bt = null;
    public long tenant = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int action = Convert.ToInt32(Globals.Request("action")==""?0:Convert.ToInt32(Globals.Request("action")));
            if (action == 1) {
                Response.Clear();
                DrawGo();
                Response.End();
            }
           
        }
    }

    private void DrawGo()
    {
        long TempID = Convert.ToInt64(Globals.Request("TempID"));
        long UserID = Convert.ToInt64(Globals.Request("UserID")); 
        tenant =  Globals.Request("tenant") == "" ? 0 : Convert.ToInt64(Globals.Request("tenant"));

        //开始阅卷
        //获取主模板ID
        DataTable dt = MK_Data.GetMainTempData(TempID);
        if (dt.Rows.Count > 0)
        {
            //获取机阅基础数据
            bt = MK_Data.GetBoxType(MK_Data.GetMainTempDataMainBoxType(Convert.ToInt32(dt.Rows[0]["MainID_bigint"])));
            string[] GetData = dt.Rows[0]["TempValue_nvarchar"].ToString().Split('$');
            int width = Convert.ToInt32(GetData[6].Split(',')[0]);
            int height = Convert.ToInt32(GetData[6].Split(',')[1]);
            dt = MK_Data.GetMinTempDataUser(TempID, UserID);

            string imgUrl = Globals.Request("imgUrl");
            Bitmap bmp;
            if (imgUrl == "")
            {
                bmp = new Bitmap(UrlToImage(dt.Rows[0]["TempPicture64_nvarchar"].ToString()));
            }
            else
            {
                bmp = new Bitmap(UrlToImage(imgUrl));
            }
            //还原图片大小,这里可能有逻辑错误
            bmp = MK_Operater.ScaleToSize(bmp, width, height);
            //获取旋转偏移量
            string[] PXGetData = dt.Rows[0]["TempValue_nvarchar"].ToString().Split('$');
            bmp = MK_Operater.ImageRotates(bmp, (float)Convert.ToDouble(dt.Rows[0]["Rotate_float"])).Bitmap;
            //切换模板数据
            dt = MK_Data.GetMainTempData(TempID);
            string[] FinleGetData = dt.Rows[0]["TempValue_nvarchar"].ToString().Split('$');
            FinleGetData[0] = PXGetData[0];
            //斜率
            double xielv = Convert.ToDouble(dt.Rows[0]["XieLv_float"]);
            //原始宽度
            int oldWidth = Convert.ToInt32(dt.Rows[0]["CutWidth_int"]);
            //原始高度
            int oldHeight = Convert.ToInt32(dt.Rows[0]["CutHeight_int"]);
            //原始坐标
            string PYPostionList = dt.Rows[0]["PyPPostion_nvarchar"].ToString();
            //切换执行数组,如果没得定位点就不要覆盖原始数据
            Mat color_mat;
            Mat mat_dilate;
            VectorOfVectorOfPoint selected_contours;
            CommonUse commonUse = new CommonUse();
            string[] PYPostion;
            if (GetData[0] != "")
            {
                string[] postionc = GetData[0].Split('^');
                //pb_image.Image = bmp;
                for (int i = 0; i < postionc.Length; i++)
                {
                    string[] postCutList = postionc[i].Split(',');
                    int X = Convert.ToInt32(Convert.ToDouble(postCutList[0]));
                    int Y = Convert.ToInt32(Convert.ToDouble(postCutList[1]));
                    int W = Convert.ToInt32(Convert.ToDouble(postCutList[2]));
                    int H = Convert.ToInt32(Convert.ToDouble(postCutList[3]));
                    //bmp = commonUse.DrawGridByXYDraw(bmp, X, W, 1, Y, H, 1);
                }

                GetData = FinleGetData;




             


                //换算未灰度图片 并选取点
                Image<Gray, byte> EmguImagex = new Image<Gray, byte>(bmp);
                Mat mat_threshold = new Mat();
                CvInvoke.Threshold(EmguImagex, mat_threshold, 120, 253, Emgu.CV.CvEnum.ThresholdType.BinaryInv);
                mat_dilate = commonUse.MyDilate(mat_threshold);
                selected_contours = commonUse.GetUsefulContours(mat_dilate, 1);


                //color_mat = commonUse.DrawContours(mat_dilate, selected_contours);
                //Response.Write(ImgToBase64String(color_mat.Bitmap));
                //bmp.Dispose();
                //return;



                //获取当前斜率
                float myXielv = MK_Operater.GetPostionXYByFindRoteBmp(EmguImagex.Mat, selected_contours, GetData[0]);
                if (myXielv == -100||myXielv==0)
                {
                    Response.Write("-1");
                    return;
                }




             

                //同步主图斜率
                float flagxie = ((90 - myXielv) - (90 - (float)xielv));
                //更新图片
                EmguImagex.Bitmap = MK_Operater.ImageRotates(bmp, flagxie).Bitmap;
                //重新查找点阵
                CvInvoke.Threshold(EmguImagex, mat_threshold, bt.Threshold, 254, Emgu.CV.CvEnum.ThresholdType.BinaryInv);
                Mat mat_dilate6 = commonUse.MyDilate(mat_threshold);
                VectorOfVectorOfPoint selected_contours6;
                selected_contours6 = commonUse.GetUsefulContours(mat_dilate6, 1);


                //color_mat = EmguImagex.Mat;
                //color_mat = commonUse.DrawContours(color_mat, selected_contours6);
                //Response.Write(ImgToBase64String(color_mat.Bitmap));
                //bmp.Dispose();
                //return;




                //根据定位点重新裁剪图片
                EmguImagex = MK_Operater.GetPostionXYByFind(EmguImagex.Mat, selected_contours6, GetData[0]);
                if (EmguImagex == null)
                {
                    return;
                }
                //等比例同步
                EmguImagex.Bitmap = MK_Operater.ScaleToSize(EmguImagex.Bitmap, oldWidth, oldHeight);
                //下列操作项定位点数据
                PYPostion = PYPostionList.Split(',');
                //最终选取图形
                CvInvoke.Threshold(EmguImagex, mat_threshold, bt.Threshold, 254, Emgu.CV.CvEnum.ThresholdType.BinaryInv);
                mat_dilate = commonUse.MyDilate(mat_threshold);
                selected_contours = commonUse.GetUsefulContoursYueJuan(mat_dilate, 1);
                color_mat = EmguImagex.Mat;
                color_mat = commonUse.DrawContours(color_mat, selected_contours);
                bmp = color_mat.Bitmap;
            }
            else
            {
                PYPostion = "0,0".Split(',');
                Image<Gray, byte> EmguImagex = new Image<Gray, byte>(bmp);
                Mat mat_threshold = new Mat();
                CvInvoke.Threshold(EmguImagex, mat_threshold, bt.Threshold, 254, Emgu.CV.CvEnum.ThresholdType.BinaryInv);
                mat_dilate = commonUse.MyDilate(mat_threshold);
                selected_contours = commonUse.GetUsefulContoursYueJuan(mat_dilate, 1);
                color_mat = EmguImagex.Mat;
                color_mat = commonUse.DrawContours(color_mat, selected_contours);
                bmp = color_mat.Bitmap;
            }
      
            //如果要取条码
            if (GetData[5] != "")
            {
                string[] tiaomaData = GetData[5].Split(',');
                int X = Convert.ToInt32(Convert.ToDouble(tiaomaData[0])) - Convert.ToInt32(PYPostion[0]);
                int Y = Convert.ToInt32(Convert.ToDouble(tiaomaData[1])) - Convert.ToInt32(PYPostion[1]); ;
                int W = Convert.ToInt32(Convert.ToDouble(tiaomaData[2]));
                int H = Convert.ToInt32(Convert.ToDouble(tiaomaData[3]));
                bmp= commonUse.DrawGridByXYDraw(bmp, X, W, 1, Y, H, 1);
            }

            //如果要取填涂
            if (GetData[1] != "")
            {
                string[] XuehaoData = GetData[1].Split(',');
                int X = Convert.ToInt32(Convert.ToDouble(XuehaoData[0])) - Convert.ToInt32(PYPostion[0]);
                int Y = Convert.ToInt32(Convert.ToDouble(XuehaoData[1])) - Convert.ToInt32(PYPostion[1]); ;
                int W = Convert.ToInt32(Convert.ToDouble(XuehaoData[2]));
                int H = Convert.ToInt32(Convert.ToDouble(XuehaoData[3]));
                int num = Convert.ToInt32(Convert.ToDouble(XuehaoData[4]));
                int wL = Convert.ToInt32(W / num);
                int hL = Convert.ToInt32(H / 10);
                bmp = commonUse.DrawGridByXYDraw(bmp, X, wL, num, Y, hL, 10);
            }
            //缺考
            if (GetData[4] != "")
            {
                string[] quekao = GetData[4].Split(',');
                int X = Convert.ToInt32(Convert.ToDouble(quekao[0])) - Convert.ToInt32(PYPostion[0]);
                int Y = Convert.ToInt32(Convert.ToDouble(quekao[1])) - Convert.ToInt32(PYPostion[1]); ;
                int W = Convert.ToInt32(Convert.ToDouble(quekao[2]));
                int H = Convert.ToInt32(Convert.ToDouble(quekao[3]));
                bmp = commonUse.DrawGridByXYDraw(bmp, X, W, 1, Y, H, 1);
            }
            if (GetData[2] != "")
            {
                string[] keguantiList = GetData[2].Split('^');
                for (int i = 0; i < keguantiList.Length; i++)
                {
                    string[] keguanPos = keguantiList[i].Split(',');
                    int X = Convert.ToInt32(Convert.ToDouble(keguanPos[0])) - Convert.ToInt32(PYPostion[0]);
                    int Y = Convert.ToInt32(Convert.ToDouble(keguanPos[1])) - Convert.ToInt32(PYPostion[1]); ;
                    int W = Convert.ToInt32(Convert.ToDouble(keguanPos[2]));
                    int H = Convert.ToInt32(Convert.ToDouble(keguanPos[3]));
                    int xuanXiang = Convert.ToInt32(keguanPos[6]);//选项数量

                   
                    string bigTihao = "";
                    if (keguanPos[5].ToUpper().Contains("M")) // 如果存在客观题
                    {
                        bigTihao = keguanPos[5].ToUpper().Split('M')[0] + "M";
                        keguanPos[5] = keguanPos[5].ToUpper().Split('M')[1];
                        keguanPos[4] = keguanPos[4].ToUpper().Split('M')[1];
                    }
                    int tiliang = Convert.ToInt32(keguanPos[5]) - Convert.ToInt32(keguanPos[4]) + 1;//题量


                    if (keguanPos[7].ToString() == "0")//横向取值
                    {
                        int wL = Convert.ToInt32(W / xuanXiang);
                        int hL = Convert.ToInt32(H / tiliang);
                        bmp = commonUse.DrawGridByXYDraw(bmp, X, wL, xuanXiang, Y, hL, tiliang);
                    }
                    else
                    {
                        int wL = Convert.ToInt32(W / tiliang);
                        int hL = Convert.ToInt32(H / xuanXiang);
                        bmp = commonUse.DrawGridByXYDraw(bmp, X, wL, tiliang, Y, hL, xuanXiang);
                    }
                }
            }
            if (GetData[3] != "")
            {
                string[] Datalist = GetData[3].Split('^');
                foreach (string postiontiaoma in Datalist)
                {
                    string[] tiaomaData = postiontiaoma.Split(',');
                    int X = Convert.ToInt32(Convert.ToDouble(tiaomaData[0])) - Convert.ToInt32(PYPostion[0]);
                    int Y = Convert.ToInt32(Convert.ToDouble(tiaomaData[1])) - Convert.ToInt32(PYPostion[1]); ;
                    int W = Convert.ToInt32(Convert.ToDouble(tiaomaData[2]));
                    int H = Convert.ToInt32(Convert.ToDouble(tiaomaData[3]));
                    bmp = commonUse.DrawGridByXYDraw(bmp, X, W, 1, Y, H, 1);
                }
            }
            Response.Write(ImgToBase64String(bmp));
            bmp.Dispose();
        }

    }

    public static Bitmap UrlToImage(string url)
    {
        WebRequest imgRequest = WebRequest.Create(url);

        HttpWebResponse res=null;
        try
        {
            res = (HttpWebResponse)imgRequest.GetResponse();
            imgRequest.Timeout = 50000;
            if (res.StatusCode.ToString() == "OK")
            {
                var tempbitmap = new Bitmap(imgRequest.GetResponse().GetResponseStream());
                return new CommonUse().RotateByOrientation(tempbitmap);
            }
            else
            {
                return null;
            }
        }
        catch (WebException ex)
        {
            res = (HttpWebResponse)ex.Response;
            return null;
        }
        finally
        {
            if (res != null) {
                res.Dispose();
                res.Close();
            }
            imgRequest.Abort();
        }
    }


    /// <summary>
    /// 检查图片是否空白图片
    /// </summary>
    /// <param name="img">Image</param>
    /// <returns>是否空白图片</returns>
    public static bool CheckTransparentImg(System.Drawing.Image img)
    {
        bool blnIsTransparent = false;
        //加载位图
        Bitmap bitMap = new Bitmap(img);
        //图片总像素
        int intAll = img.Height * img.Width;
        int intCount = 0;
        //按像素遍历
        for (int intY = 0; intY < img.Height; intY++)
        {
            for (int intX = 0; intX < img.Width; intX++)
            {
                if (bitMap.GetPixel(intX, intY).GetBrightness() == 1)
                {
                    intCount += 1;
                }
            }
        }

        float a = (float)intCount / (float)intAll;
        Console.WriteLine(a.ToString());
        Console.WriteLine(intCount.ToString() + "---" + intAll.ToString());


        //释放资源
        bitMap.Dispose();
        int al = intAll - 1000;
        if (intCount > al)
        {
            blnIsTransparent = true;
        }
        return blnIsTransparent;
    }



    public static Bitmap Base64StringToImage(string strbase64)
    {
        try
        {
            byte[] arr = Convert.FromBase64String(strbase64);
            MemoryStream ms = new MemoryStream(arr);
            Bitmap bmp = new Bitmap(ms);
            ms.Close();
            return bmp;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    public static string ImgToBase64String(Bitmap bmp)
    {
        try
        {
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            ms.Dispose();
            ms.Close();
            return Convert.ToBase64String(arr);
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}
public class MK_Data
{

    public static long tenant = 0;
 

    public static void GetTenant(){
         tenant = Globals.Request("tenant") == "" ? 0 : Convert.ToInt64(Globals.Request("tenant"));
    }

    /// <summary>
    /// 获取我需要扫描的试卷
    /// </summary>
    /// <returns></returns>
    public static DataTable GetScanResult()
    { 
        GetTenant();
        string sql = "SELECT top 1 * FROM ScanResult WHERE  IsMarking=0 order by GroupNo ASC";
        DataTable dt = new MysqlDBHelper(tenant).ExecuteQuery(sql);
        if (dt.Rows.Count > 0)
        {
            return dt;
        }
        else
        {
            return null;
        }
    }

    /// <summary>
    /// 获取我需要扫描的试卷
    /// </summary>
    /// <returns></returns>
    public static DataTable GetScanResultDetail(int GroupNo)
    {
        GetTenant();
        string sql = "SELECT  * FROM ScanResult WHERE GroupNo=" + GroupNo + " AND   IsMarking=0 order by pageindex ASC";
        DataTable dt = new MysqlDBHelper(tenant).ExecuteQuery(sql);
        if (dt.Rows.Count > 0)
        {
            return dt;
        }
        else
        {
            return null;
        }
    }

    /// <summary>
    /// 获取主模板数据
    /// </summary>
    /// <param name="temID"></param>
    /// <returns></returns>
    public static DataTable GetMainTempData(long temID)
    {

        GetTenant();
        string sql = "select detaID_bigint from MK_TempleteDataUser where ID_bigint=" + temID;
        long detaID_bigint = Convert.ToInt64(new MysqlDBHelper(tenant).ExecuteScalar(sql));


        sql = "SELECT * FROM MK_TempleteData WHERE ID_bigint = " + detaID_bigint + " ORDER BY PageIndex_int ASC";
        return new MysqlDBHelper(tenant).ExecuteQuery(sql);
    }

       /// <summary>
        /// 获取主模板数据
        /// </summary>
        /// <param name="temID"></param>
        /// <returns></returns>
        public static int GetMainTempDataMainBoxType(long temID)
        {
        GetTenant();
            string sql = "SELECT BoxType FROM MK_TempleteMain WHERE ID_bigint=" + temID;
            return Convert.ToInt32(new MysqlDBHelper(tenant).ExecuteScalar(sql));
            
        }

    /// <summary>
    /// 获取用户模板数据
    /// </summary>
    /// <param name="tempID"></param>
    /// <param name="userID"></param>
    /// <returns></returns>
    public static DataTable GetMinTempDataUser(long tempID, long userID)
    {
        GetTenant();
        string sql = "SELECT * FROM MK_TempleteDataUser WHERE  UserID_bigint=" + userID + " AND ID_bigint=" + tempID;
        return new MysqlDBHelper(tenant).ExecuteQuery(sql);

    }

    /// <summary>
    /// 判断是否有重复试卷扫入
    /// </summary>
    /// <param name="ksNum"></param>
    /// <param name="StudentNO"></param>
    /// <returns></returns>
    public static bool CheckRepeatMKFlag(string ksNum, string StudentNO)
    {
        GetTenant();
        string sql = "SELECT COUNT(1) FROM ScanResult WHERE ExamSubjectSchoolId='" + ksNum + "' AND OCRStudentExamNum='" + StudentNO + "' AND ismarking=1";
        int count = Convert.ToInt32(new MysqlDBHelper(tenant).ExecuteScalar(sql));
        if (count > 0)
        {
            return false;
        }
        return true;
    }

    /// <summary>
    /// 清理所有该用户数据
    /// </summary>
    public static void DeleteAllMKSTData(string GroupNo, string StudentNO)
    {
        GetTenant();
        string sql = string.Format("DELETE MK_ExamResult  WHERE GroupNO_nvarchar = {0} AND StudentNo_nvarchar = '{1}'", GroupNo, StudentNO);
        new MysqlDBHelper(tenant).ExecuteNoQuery(sql);
    }


    /// <summary>
    /// 删除已有考号数据
    /// </summary>
    /// <param name="ksNum"></param>
    /// <param name="StudentNO"></param>
    public static void DeleteStudentExamResultData(string ksNum, string StudentNO)
    {
        GetTenant();
        //删除原始表中的数据
        string sql = string.Format("DELETE MK_ExamResult  WHERE ExamID_bigint = {0} AND StudentNo_nvarchar = '{1}'", ksNum, StudentNO);
        new MysqlDBHelper(tenant).ExecuteNoQuery(sql);

    }




    /// <summary>
    /// 新增一条错误数据
    /// </summary>
    /// <param name="et"></param>
    /// <param name="pictureUrl"></param>
    /// <param name="examID"></param>
    /// <param name="studentNO"></param>
    /// <param name="ErroMessage"></param>
    /// <param name="groupID"></param>
    public static void UpdateMkGo(string groupID, string orcStudentNum)
    {

        GetTenant();
        string sql = string.Format("UPDATE ScanResult SET IsMarking=1,OCRStudentExamNum='" + orcStudentNum + "' WHERE GroupNo=" + groupID);
        new MysqlDBHelper(tenant).ExecuteNoQuery(sql);
    }

    /// <summary>
    /// 新增一条错误数据
    /// </summary>
    /// <param name="et"></param>
    /// <param name="pictureUrl"></param>
    /// <param name="examID"></param>
    /// <param name="studentNO"></param>
    /// <param name="ErroMessage"></param>
    /// <param name="groupID"></param>
    public static void UpdateMkGoNoOrcStudentNum(string groupID)
    {

        GetTenant();
        string sql = string.Format("UPDATE ScanResult SET IsMarking=1 WHERE GroupNo=" + groupID);
        new MysqlDBHelper(tenant).ExecuteNoQuery(sql);
    }



    /// <summary>
    /// 获取扫描类型
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static BoxType GetBoxType(int type)
    {
        BoxType b = new BoxType();
        //红框
        if (type == 1)
        {
            b.fillRate = 30;
            b.Threshold = 50;
        }
        if (type == 2)
        {
            b.fillRate = 60;
            b.Threshold = 60;
        }
        if (type == 3)
        {
            b.fillRate = 45;
            b.Threshold = 18;
        }
        return b;
    }
}
public class BoxType
{
    public int fillRate { get; set; }
    public int Threshold { get; set; }
}



public class MK_Operater
{
    // <summary>
    /// 缩放图片
    /// </summary>
    /// <param name="bitmap">原图片</param>
    /// <param name="width">新图片宽度</param>
    /// <param name="height">新图片高度</param>
    /// <returns>新图片</returns>
    public static Bitmap ScaleToSize(Bitmap bitmap, int width, int height)
    {
        try
        {


            if (bitmap == null)
            {
                return null;
            }
            if (bitmap.Width == width && bitmap.Height == height)
            {
                return bitmap;
            }

            var scaledBitmap = new Bitmap(width, height);
            using (var g = Graphics.FromImage(scaledBitmap))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(bitmap, 0, 0, width, height);
            }
            return scaledBitmap;
        }
        catch
        {
            return null;
        }
    }

    public static Image<Bgra, byte> ImageRotates(Bitmap Map, double Dou, bool Bol = true)
    {
        try
        {
            Image<Bgra, byte> Imga1 = new Image<Bgra, byte>(Map);
            //Image<Bgra, byte> Imga2 = Imga1.Rotate(Dou, new Bgra(0, 0, 0, 0), Bol);
            // Image<Bgra, byte> Imga2 = Imga1.Rotate(Dou, new Bgra(0, 0, 0, 0), Bol) 等同于
            Image<Bgra, byte> Imga2 = Imga1.Rotate(Dou, new PointF(Imga1.Width / 2, Imga1.Height / 2), Inter.Cubic, new Bgra(255, 255, 255, 255), Bol);
            return Imga2;
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 获取偏移量 通过矩形查找
    /// </summary>
    /// <param name="bmp"></param>
    /// <param name="PointPath"></param>
    /// <param name="PostionXY"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public static float GetPostionXYByFindRoteBmp(Mat color_mat, VectorOfVectorOfPoint selected_contours, string postionCut)
    {

        try
        {
            CommonUse commonUse = new CommonUse();
            string[] postionc = postionCut.Split('^');
            Point GrXY;
            int Y2 = 0, Y1 = 0, X2 = 0, X1 = 0;
            for (int i = 0; i < postionc.Length; i++)
            {
                string[] postCutList = postionc[i].Split(',');
                int X = Convert.ToInt32(Convert.ToDouble(postCutList[0]));
                int Y = Convert.ToInt32(Convert.ToDouble(postCutList[1]));
                int W = Convert.ToInt32(Convert.ToDouble(postCutList[2]));
                int H = Convert.ToInt32(Convert.ToDouble(postCutList[3]));
                //commonUse.DrawGridByXY(测试查找坐标.myFrom.PB_guodu, X, W, 1, Y, H, 1);Response.Write(ImgToBase64String(bmp));
                string mx = "";
                try
                {
                    string message = string.Empty;
                    mx = commonUse.GetValueAndDrawGrid_Find(color_mat.Bitmap, selected_contours, X, W, 1, Y, H, 1, "", out GrXY,out message);
                }
                catch
                {
                    mx = "null";
                    GrXY = new Point(0, 0);
                }

                if (mx.Trim() != "A")
                {
                    break;
                }
                Point Mx = GrXY;
                if (i == 0)//左上角
                {
                    Y1 = GrXY.Y;
                    X1 = GrXY.X;

                }
                if (i == 2)//左下角
                {
                    X2 = GrXY.X;
                    Y2 = GrXY.Y;
                }
            }
            return (float)(Math.Atan2((Y2 - Y1), (X2 - X1)) * (180 / Math.PI));
        }
        catch
        {
            return -100;
        }
    }


    /// <summary>
    /// 获取偏移量 通过矩形查找
    /// </summary>
    /// <param name="bmp"></param>
    /// <param name="PointPath"></param>
    /// <param name="PostionXY"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public static Image<Gray, byte> GetPostionXYByFind(Mat color_mat, VectorOfVectorOfPoint selected_contours, string postionCut)
    {

        try
        {
            CommonUse commonUse = new CommonUse();
            string[] postionc = postionCut.Split('^');
            string PYPostion = "";
            Point GrXY;
            int PostionWW = 0;
            int PostionHH = 0;


            int Y2 = 0, Y1 = 0, X2 = 0, X1 = 0;

            for (int i = 0; i < postionc.Length; i++)
            {
                string[] postCutList = postionc[i].Split(',');
                int X = Convert.ToInt32(Convert.ToDouble(postCutList[0]));
                int Y = Convert.ToInt32(Convert.ToDouble(postCutList[1]));
                int W = Convert.ToInt32(Convert.ToDouble(postCutList[2]));
                int H = Convert.ToInt32(Convert.ToDouble(postCutList[3]));
                string mx = "";
                try
                {
                    string message = string.Empty;
                    mx = commonUse.GetValueAndDrawGrid_Find(color_mat.Bitmap, selected_contours, X, W, 1, Y, H, 1, "", out GrXY,out message);
                }
                catch
                {
                    mx = "null";
                    GrXY = new Point(0, 0);
                }

                if (mx.Trim() != "A")
                {
                    break;
                }
                Point Mx = GrXY;
                if (i == 0)//左上角
                {
                    PYPostion = GrXY.X + "," + GrXY.Y;
                    Y1 = GrXY.Y;
                    X1 = GrXY.X;

                }
                if (i == 1)//右上角
                {
                    PostionWW = GrXY.X;
                }
                if (i == 2)//左下角
                {
                    PostionHH = GrXY.Y;
                    X2 = GrXY.X;
                    Y2 = GrXY.Y;
                }
            }
            string[] posList = PYPostion.Split(',');
            int PostionX = Convert.ToInt32(posList[0]);
            int PostionY = Convert.ToInt32(posList[1]);
            int PostionW = PostionWW - PostionX;
            int PostionH = PostionHH - PostionY;

            //裁剪
            Rectangle rectangle = new Rectangle(PostionX, PostionY, PostionW, PostionH);
            Image<Gray, byte> Sub = new Image<Gray, byte>(color_mat.Bitmap).GetSubRect(rectangle);
            Image<Gray, byte> CropImage = new Image<Gray, byte>(Sub.Size);
            CvInvoke.cvCopy(Sub, CropImage, IntPtr.Zero);
            //获取偏移量
            return CropImage;
        }
        catch
        {
            return null;
        }
    }

   




    /// <summary>
    /// 获取裁剪 L T W H
    /// </summary>
    /// <param name="PointPath"></param>
    public static Image<Gray, byte> GetMatCutImg(Bitmap bmp, int sX, int sT, int sW, int sH)
    {
        List<Image<Gray, byte>> postionimageCut = new List<Image<Gray, byte>>();
        int L = sX;
        int T = sT;
        int W = sW;
        int H = sH;
        Rectangle rectangle = new Rectangle(L, T, W, H);
        Image<Gray, byte> Sub = new Image<Gray, byte>(bmp).GetSubRect(rectangle);
        Image<Gray, byte> CropImage = new Image<Gray, byte>(Sub.Size);
        CvInvoke.cvCopy(Sub, CropImage, IntPtr.Zero);
        return CropImage;
    }

    

    /// <summary>
    /// 获取主观题
    /// </summary>
    /// <param name="color_mat"></param>
    /// <param name="PYPostion"></param>
    /// <param name="postiontiaomaX"></param>
    /// <returns></returns>
    public static List<ZhuguantiList> GetZhuguantiText(Mat color_mat, string[] PYPostion, string postiontiaomaX, int pageIndex)
    {
        string[] Datalist = postiontiaomaX.Split('^');
        List<ZhuguantiList> lt = new List<ZhuguantiList>();
        CommonUse commonUse = new CommonUse();

        foreach (string postiontiaoma in Datalist)
        {
            ZhuguantiList zd = new ZhuguantiList();
            string[] tiaomaData = postiontiaoma.Split(',');
            int X = Convert.ToInt32(Convert.ToDouble(tiaomaData[0])) - Convert.ToInt32(PYPostion[0]);
            int Y = Convert.ToInt32(Convert.ToDouble(tiaomaData[1])) - Convert.ToInt32(PYPostion[1]); ;
            int W = Convert.ToInt32(Convert.ToDouble(tiaomaData[2]));
            int H = Convert.ToInt32(Convert.ToDouble(tiaomaData[3]));
            Image<Gray, byte> bytimg = GetMatCutImg(color_mat.Bitmap, X, Y, W, H);
            zd.btm = new Bitmap(bytimg.Bitmap);
            zd.num = tiaomaData[4];
            zd.QuestionSmallNum = Convert.ToInt32(tiaomaData[5]);
            lt.Add(zd);
            bytimg.Bitmap.Dispose();
        }
        return lt;
    }

    


    public static Bitmap GetDrawRectangleWhite(Bitmap bit)
    {
        Bitmap bmp = new Bitmap(bit);
        float w = (float)(2);//边框的宽度，可取任意值
        using (Graphics g = Graphics.FromImage(bmp))
        {
            // g.CopyFromScreen(0, 0, 0, 0, Screen.AllScreens[0].Bounds.Size);//抓取背景图
            using (Pen pen = new Pen(Color.White, w))
            {

                g.DrawRectangle(pen, new Rectangle(0, 0, Math.Abs(bmp.Width), Math.Abs(bmp.Height)));//加边框
                g.Dispose();
            }
        }
        return bmp;
    }






}