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

public partial class Temp_UserTemp : System.Web.UI.Page
{


    public long TempID = 0;
    public string Bindlist = "";
    public string imgage = "";
    public string UserID = "";
    public string Rotate = "";
    public string ID_bigint = "";
    public string islocked = "";
    public string pager = "";
    public long tenant = 0;

    protected void Page_Load(object sender, EventArgs e)
    {


        int action = Globals.Request("action") == "" ? 0 : Convert.ToInt32(Globals.Request("action"));
        tenant = Globals.Request("tenant") == "" ? 0 : Convert.ToInt64(Globals.Request("tenant"));
        if (action != 0)
        {

            Response.Clear();
            switch (action)
            {
                case 1:
                    UpdateTempData();
                    break;
                case 2:
                    AnsyTemplete();
                    break;
            }
            Response.End();
        }
        else
        {

            UserID = Globals.Decrypt(Globals.Request("UserID"));
            pager = Globals.Request("pager");
            if (string.IsNullOrEmpty(UserID))
            {
                Response.Write("<script>alert('数据有误,请检查');</script>");
                return;
            }
            else
            {
                long UID = Convert.ToInt64(UserID);

                TempID = Globals.Request("TempID") == "" ? 0 : Convert.ToInt32(Globals.Request("TempID"));//获取小模板ID
                string sql = "select * from MK_TempleteDataUser where DetaID_bigint=" + TempID + " AND UserID_bigint=" + UID;
                //string sql = "select * from MK_TempleteDataUser where DetaID_bigint=" + TempID ;
                DataTable dtx = new MysqlDBHelper(tenant).ExecuteQuery(sql);

                if (dtx.Rows.Count > 0)
                {
                    ID_bigint = dtx.Rows[0]["ID_bigint"].ToString();
                    Bindlist = dtx.Rows[0]["TempValue_nvarchar"].ToString();
                    imgage = dtx.Rows[0]["TempPicture64_nvarchar"].ToString();
                    Rotate = dtx.Rows[0]["Rotate_float"].ToString();
                    islocked = dtx.Rows[0]["islocked_int"].ToString();
                }
                else
                {
                    Response.Write("<script>alert('无有效数据');</script>");
                }
            }

        }
    }

    public void AnsyTemplete()
    {
        UserID = Globals.Request("UserID");
        TempID = Globals.Request("TempID") == "" ? 0 : Convert.ToInt32(Globals.Request("TempID"));//获取小模板ID
        string totalHtml = Server.UrlDecode(Globals.Request("totalHtml"));
        string Rotate_float = Globals.Request("roteDY");
        string sql = "Update MK_TempleteDataUser SET islocked_int=1 where DetaID_bigint=" + TempID + " AND UserID_bigint=" + Convert.ToInt64(UserID);
        MySqlParameter[] sp = new MySqlParameter[] {
                new MySqlParameter("@TempValue_nvarchar",totalHtml),
            new MySqlParameter("@Rotate_float",Rotate_float),
            };

        if (new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp) == 1)
        {
            AnsyTemp(Convert.ToInt64(UserID), TempID);
        }
    }

    private void UpdateTempData()
    {


        UserID = Globals.Request("UserID");
        TempID = Globals.Request("TempID") == "" ? 0 : Convert.ToInt32(Globals.Request("TempID"));//获取小模板ID
        string totalHtml = Server.UrlDecode(Globals.Request("totalHtml"));
        string Rotate_float = Globals.Request("roteDY");
        string sql = "Update MK_TempleteDataUser SET TempValue_nvarchar=@TempValue_nvarchar,Rotate_float=@Rotate_float where DetaID_bigint=" + TempID + " AND UserID_bigint=" + Convert.ToInt64(UserID);
        MySqlParameter[] sp = new MySqlParameter[] {
                new MySqlParameter("@TempValue_nvarchar",totalHtml),
            new MySqlParameter("@Rotate_float",Rotate_float),
            };

        if (new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp) == 1)
        {
            AnsyTemp(Convert.ToInt64(UserID), TempID);
        }
    }

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

    }
    /// <summary>
    /// 锁定模板数据
    /// </summary>
    public void AnsyTemp(long userID, long TempID)
    {
        try
        {
            string sql = "SELECT * FROM MK_TempleteDataUser WHERE detaID_bigint=" + TempID + " AND UserID_bigint=" + UserID;
            DataTable dt = new MysqlDBHelper(tenant).ExecuteQuery(sql);
            if (dt.Rows.Count <= 0)
            {
                Response.Write("NODATA");
                return;
            }
            Bitmap temp = ImgGet(dt.Rows[0]["TempPicture64_nvarchar"].ToString());
            var PictureBoxBitMap = new CommonUse().RotateByOrientation(temp);
            if (PictureBoxBitMap == null)
            {
                Response.Write("NOPICTURE");
            }
            string[] GetData = dt.Rows[0]["TempValue_nvarchar"].ToString().Split('$');
            string PYPostionList = "";
            //BoxType bt = null;
            //bt = GetBoxType(GetMainTempDataMainBoxType(Convert.ToInt32(dt.Rows[0]["MainID_bigint"])));

            if (GetData[0] != "")
            {
                //计算模板图片参数
                double xielv = 0;
                int width = Convert.ToInt32(GetData[6].Split(',')[0]);
                int height = Convert.ToInt32(GetData[6].Split(',')[1]);
                PictureBoxBitMap = ScaleToSize(PictureBoxBitMap, width, height);
                Image<Gray, byte> imagex = new Image<Gray, byte>(PictureBoxBitMap);
                CommonUse commonUse = new CommonUse();
                Mat mat_threshold1 = new Mat();

                Image<Gray, byte> zaodianPic = new Image<Gray, byte>(commonUse.FilterRed(PictureBoxBitMap));
                // 去除定位点周围噪点 
                CvInvoke.MedianBlur(zaodianPic, zaodianPic, 5);
                //commonUse.ShowMatWaitKey("zaodianPic zaodianPic", zaodianPic.Mat, 0.6);
                CvInvoke.GaussianBlur(zaodianPic, zaodianPic, new Size(5, 5), 0);



                CvInvoke.Threshold(zaodianPic, mat_threshold1, 180, 255, Emgu.CV.CvEnum.ThresholdType.BinaryInv);
                Mat mat_dilate1 = commonUse.MyDilate(mat_threshold1);
                VectorOfVectorOfPoint selected_contours1;
                selected_contours1 = commonUse.GetUsefulContoursDingWei(mat_dilate1, 1);
                Image<Gray, byte> currentFramext = new Image<Gray, byte>(PictureBoxBitMap);

                //Mat color_mat1 = commonUse.DrawContours(currentFramext.Mat, selected_contours1);

                //commonUse.ShowMatWaitKey("shijuan bianjie", color_mat1, 0.6);
                string message = string.Empty;
                Mat color_mxxx = commonUse.GetPostionXYByFindPostionAndXieLv(imagex.Mat, selected_contours1, GetData[0], out PYPostionList, currentFramext, out xielv,out message);
                if (xielv == -100)
                {
                    Response.Write(message);
                    return;
                }
                imagex.Dispose();
                color_mxxx.Dispose();
                PictureBoxBitMap.Dispose();
                Response.Write("ok");
                return;
            }
            Response.Write("ok");

        }
        catch (Exception ex)
        {
            Response.Write("TEMPERRO");
        }
    }


    private Bitmap ScaleToSize(Bitmap bitmap, int width, int height)
    {
        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;
    }

    // <summary>
    /// 图片另存为
    /// </summary>
    /// <param name="url">路径</param>
    public Bitmap ImgGet(string url)
    {

        WebRequest imgRequest = WebRequest.Create(url);
        HttpWebResponse res = null;

        try
        {
            res = (HttpWebResponse)imgRequest.GetResponse();
            if (res.StatusCode.ToString() == "OK")
            {
                return new Bitmap(imgRequest.GetResponse().GetResponseStream());
            }
            else
            {
                return null;
            }
        }
        catch (WebException ex)
        {
            return null;
        }
        finally
        {
            res.Dispose();
            imgRequest.Abort();
            res.Close();
        }




        GC.Collect();
    }



}