<%@ WebHandler Language="C#" Class="QualityData_NormalDistribution" %>

using System;
using System.Web;
using System.Data;
using MES_SPC;


public class QualityData_NormalDistribution : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string type = HttpContext.Current.Request["type"];
        string responseText = "";
        switch (type)
        {
            case "SaveImg":
                responseText = SaveImg();
                break;
            case "BindMinutes":
                responseText = BindMinutes();
                break;
            case "BindHour":
                responseText = BindHour();
                break;
            case "BindMachineType":
                responseText = BindMachineType();
                break;
            case "BindOPName":
                responseText = BindOPName();
                break;
            //绑定测量内容
            case "BindMeasurePartContent":
                responseText = BindMeasurePartContent();
                break;
            //绑定测量内容
            case "BindMeasurePart":
                responseText = BindMeasurePart();
                break;
            case "GetBaseTrendData":
                responseText = GetBaseTrendData();
                break;
            case "GetDataTableByConditent":
                responseText = GetDataTableByConditent();
                break;
            case "OutPutData":
                responseText = OutPutData();
                break;
        }
        context.Response.Write(responseText);
    }
    public string normal(double[] values, double miu, double sigma)
    {
        string str = "";
        if (values.Length > 0)
        {
            for (int i = 0; i < values.Length; i++)
            {
                str += (1.0 / Math.Sqrt(2 * Math.PI) / sigma * Math.Exp(-1 * (values[i] - miu) * (values[i] - miu) / (2 * sigma * sigma))).ToString("0.00000000000000");
                if (i != values.Length - 1)
                {
                    str += ",";
                }
            }
        }
        return str;
        // return 1.0 / Math.Sqrt(2 * Math.PI) / sigma *  Math.Exp(-1 * (x - miu) * (x - miu) / (2 * sigma * sigma));
    }

    double[] X;
    public string GetBaseTrendData()
    {
        DataTable dt = null;
        //System.Text.StringBuilder result = new System.Text.StringBuilder();
        string result = "";
        bool EnginIDCheck = false;
        string EnginID = "";
        bool OPNameCheck = true;
        string OPName = HttpContext.Current.Request["OPName"];
        bool shaftNameCheck = Convert.ToBoolean(HttpContext.Current.Request["shaftNameCheck"]);
        string shaftName = HttpContext.Current.Request["shaftName"];//测量位置
        bool itemNameCheck = Convert.ToBoolean(HttpContext.Current.Request["itemNameCheck"]);
        string itemName = HttpContext.Current.Request["itemName"];
        string startTime = HttpContext.Current.Request["startTime"];
        string endTime = HttpContext.Current.Request["endTime"];

        //string hour = HttpContext.Current.Request["Hour"];
        //string minutes = HttpContext.Current.Request["Minutes"];
        //startTime = startTime + " " + hour + ":" + minutes + ":" + "00";
        string EngineTypeID = HttpContext.Current.Request["EngineTypeID"]; ;
        bool EngineTypeIDCheck = Convert.ToBoolean(HttpContext.Current.Request["EngineTypeIDCheck"]);
        int n = Convert.ToInt32(HttpContext.Current.Request["Yangben"]);
        int k = Convert.ToInt32(HttpContext.Current.Request["Num"]);

        QualityData.SelectGoodDataReport_DataGroup(EnginIDCheck, EnginID,
                                  OPNameCheck, OPName,
                                   EngineTypeID,
                                    EngineTypeIDCheck,
                                   shaftNameCheck, shaftName,
                                  itemNameCheck, itemName,
                                   startTime, endTime, n, k, out  dt);
                
        if (dt != null && dt.Rows.Count > 2)
        {
            double Usl;
            double Lsl;
            double x;
            double s;
            double QU;
            double QL;
            double cp;
            double cpk;
            double usl;
            double qu;
            double sl;
            double ql;
            double lsl;
            double[] sx;
            double[] sy;
            try
            {
                X = new double[dt.Rows.Count];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    X[i] = Convert.ToDouble(dt.Rows[i]["测量值"].ToString());
                }


                double ValueUp = Max(X);
                double ValueDown = Min(X);

                // SpcCaculator.GetUslLsl(dt, out Usl, out Lsl);
                // 暂时改为手动输入 --20191030 LLJ

            
                Usl = Convert.ToDouble(HttpContext.Current.Request["Usl"]); // 上限值 
                Lsl = Convert.ToDouble(HttpContext.Current.Request["Lsl"]); // 下限值 
              
                if (Usl == 0 && Lsl == 0)
                {
                        //自动计算上下限
                        SpcCaculator.SpcValue(X, ref Usl, ref Lsl, out  x, out  s, out  QU, out  QL, out  cp, out  cpk, out  sx, out  sy);
                }
                else
                {
                        //使用输入的上下限
                        SpcCaculator.SpcValue(n,X, ref Usl, ref Lsl, out  x, out  s, out  QU, out  QL, out  cp, out  cpk, out  sx, out  sy);
                }
            }
            catch
            {
                Usl = 0; // 上限值 
                Lsl = 0; // 下限值 

                //自动计算上下限
                SpcCaculator.SpcValue(X, ref Usl, ref Lsl, out  x, out  s, out  QU, out  QL, out  cp, out  cpk, out  sx, out  sy);
            }

            //SpcCaculator.SpcValue(X, ref Usl, ref Lsl, out  x, out  s, out  QU, out  QL, out  cp, out  cpk, out  sx, out  sy);












            //坐标轴
            double ValueUpX = Convert.ToDouble(Max(sx).ToString("F4"));
            double ValueDownX = Convert.ToDouble(Min(sx).ToString("F4"));
            double ValueUpY = Convert.ToDouble(Max(sy).ToString("F4"));

            ValueDownX = Math.Min(ValueDownX, Lsl);
            ValueDownX = Math.Min(ValueDownX, QL);

            ValueUpX = Math.Max(ValueUpX, Usl);
            ValueUpX = Math.Max(ValueUpX, QU);
            double X1 = (ValueUpX - ValueDownX) / 10;
            double minValue = Math.Round(ValueDownX - X1, 4);
            double maxValue = Math.Round(ValueUpX + X1, 4);
            double[] value = new double[dt.Rows.Count];
            for (int i = 0; i < sy.Length; i++)
            {
                result += sy[i].ToString("0.00000000000000");
                if (i != sy.Length - 1)
                {
                    result += ",";
                }
            }
            result += "|";
            result += Usl + "," + QU + "," + sx[5].ToString("F4") + "," + QL + "," + Lsl + "," + cp + "," + cpk + "|";
            for (int i = 0; i < 6; i++)
            {
                result += i * (double)Math.Round(ValueUpY + ValueUpY / 10, 4) / 5;
                if (i != 5)
                {
                    result += ",";
                }
            }
            double XmaxValue = 0;
            if (QL > XmaxValue)
            {
                XmaxValue = QL;
            }
            if (Usl > XmaxValue)
            {
                XmaxValue = Usl;
            }
            if (QU > XmaxValue)
            {
                XmaxValue = QU;
            }
            if (Lsl > XmaxValue)
            {
                XmaxValue = Lsl;
            }
            if (Convert.ToDouble(sx[5].ToString("F4")) > XmaxValue)
            {
                XmaxValue = Convert.ToDouble(sx[5].ToString("F4"));
            }
            result += "|";
            for (int i = 0; i < sx.Length; i++)
            {
                result += sx[i];
                if (i != sx.Length - 1)
                {
                    result += ",";
                }
            }
            RealX(sx, Usl, out usl);
            RealX(sx, QU, out qu);
            RealX(sx, Convert.ToDouble(sx[5].ToString("F4")), out sl);
            RealX(sx, QL, out ql);
            RealX(sx, Lsl, out lsl);
            //添加显示对应标线在X轴的实际位置
            result += "|";
            result += usl + "," + qu + "," + sl + "," + ql + "," + lsl;


            //for (int i = 0; i <= 12; i++)
            //{
            //    result += i * (double)XmaxValue / 11;
            //    if (i != 12)
            //    {
            //        result += ",";
            //    }
            //}
            ////添加显示对应标线在X轴的实际位置
            //result += "|";
            //result += (double)Usl * 11 / XmaxValue + "," + (double)QU * 11 / XmaxValue + "," + (double)(Convert.ToDouble(sx[5].ToString("F4"))) * 11 / XmaxValue + "," + (double)QL * 11 / XmaxValue + "," + (double)Lsl * 11 / XmaxValue;
        }
        return result;
    }

    public static double RealX(double[] sx, double val, out double realVal)
    {
        realVal = 0.00;
        if (val < sx[0])
        {
            realVal = 0.00 - (sx[0] - val) / (2 * sx[0]);
        }
        else if (val > sx[sx.Length - 1])
        {
            realVal = sx.Length - 1;
        }
        else
        {
            for (int i = 0; i < sx.Length - 1; i++)
            {
                if (val > sx[i] && val < sx[i + 1])
                {
                    realVal = i + (val - sx[i]) / (sx[i + 1] - sx[i]);
                }
                if (val == sx[i])
                {
                    realVal = i;
                }
            }
        }
        return realVal;
    }


    //求正态分布的随机数
    public void Fenbu(double[] f)
    {
        double[] dd = new double[f.Length];
        //double fenbu=new double[f.Length ];
        for (int i = 0; i < f.Length; i++)
        {
            double a = 0, b = 0;
            a = Math.Sqrt((-2) * Math.Log(f[i], Math.E));
            b = Math.Cos(2 * Math.PI * f[i]);
            f[i] = a * b * 0.3 + 1;

        }
    }

    /// <summary>
    /// 观测值最大值
    /// </summary>
    /// <param name="Xn">子组观测值</param>
    /// <returns></returns>
    static private double Max(double[] Xn)
    {
        double temp;
        temp = Xn[0];
        for (int i = 0; i < Xn.Length; i++)
        {
            temp = (Xn[i] > temp) ? Xn[i] : temp;
        }
        return temp;
    }
    /// <summary>
    /// 观测值最小值
    /// </summary>
    /// <param name="Xn">子组观测值</param>
    /// <returns></returns>
    static private double Min(double[] Xn)
    {
        double temp;
        temp = Xn[0];
        for (int i = 0; i < Xn.Length; i++)
        {
            temp = (Xn[i] < temp) ? Xn[i] : temp;
        }
        return temp;
    }

    public string GetDataTableByConditent()
    {
        DataTable dt = null;
        DataTable dt1 = null;

        int pageSize = Convert.ToInt32(HttpContext.Current.Request["page"]);//请求的当前页码
        int pageList = Convert.ToInt32(HttpContext.Current.Request["rows"]);//请求一页显示的数据条数。

        string result = "";
        bool EnginIDCheck = false;
        string EnginID = "";
        bool OPNameCheck = Convert.ToBoolean(HttpContext.Current.Request["OPNameCheck"]);
        string OPName = HttpContext.Current.Request["OPName"];
        bool shaftNameCheck = Convert.ToBoolean(HttpContext.Current.Request["shaftNameCheck"]);
        string shaftName = HttpContext.Current.Request["shaftName"];
        bool itemNameCheck = Convert.ToBoolean(HttpContext.Current.Request["itemNameCheck"]);
        string itemName = HttpContext.Current.Request["itemName"];
        string startTime = HttpContext.Current.Request["startTime"];
        string endTime = null;
        string hour = HttpContext.Current.Request["Hour"];
        string minutes = HttpContext.Current.Request["Minutes"];
        startTime = startTime + " " + hour + ":" + minutes + ":" + "00";
        string EngineTypeID = HttpContext.Current.Request["EngineTypeID"]; ;
        bool EngineTypeIDCheck = Convert.ToBoolean(HttpContext.Current.Request["EngineTypeIDCheck"]);
        int n = Convert.ToInt32(HttpContext.Current.Request["Yangben"]);
        int k = Convert.ToInt32(HttpContext.Current.Request["Num"]);

        QualityData.SelectGoodDataReport_DataGroup(EnginIDCheck, EnginID,
       OPNameCheck, OPName,
       EngineTypeID, EngineTypeIDCheck,
        shaftNameCheck, shaftName,
       itemNameCheck, itemName,
        startTime, endTime, n, k, out  dt);

        dt1 = dt.Copy(); //复制dt
        dt1.Rows.Clear();//清空内容，只保留dt结构。
        for (int i = (pageSize - 1) * pageList; i < pageSize * pageList; i++)//循环需要显示的行
        {
            if (i < dt.Rows.Count)
            {
                dt1.ImportRow(dt.Rows[i]);//这是加入的是第i行
            }
        }
        if (dt1 != null && dt1.Rows.Count > 0)
        {
            result = JsonHelper.CreateJsonParameters(dt1, true, dt.Rows.Count);
        }
        return result;
    }

    /// <summary>
    /// 绑定测量名称
    /// </summary>
    /// <returns></returns>
    public string BindMeasurePart()
    {
        string text = "";
        DataTable dt;
        string opName;
        opName = HttpContext.Current.Request["opName"];
        QualityData.GetShaftName(opName, out dt);
        if (dt != null && dt.Rows.Count > 0)
        {
            text = JsonHelper.DataTableToJson(dt);
        }
        return text;
    }
    /// <summary>
    /// 绑定测量内容
    /// </summary>
    /// <returns></returns>
    public string BindMeasurePartContent()
    {
        string text = "";
        string opName;
        string shaftName;
        opName = HttpContext.Current.Request["opName"];
        shaftName = HttpContext.Current.Request["shaftName"];
        DataTable dt;
        QualityData.GetItemName(opName, shaftName, out dt);
        if (dt != null && dt.Rows.Count > 0)
        {
            text = JsonHelper.DataTableToJson(dt);
        }
        return text;
    }
    //绑定工位名称
    public string BindOPName()
    {
        string text = "";
        DataTable dt;
        QualityData.GetOpName(out dt);
        if (dt != null && dt.Rows.Count > 0)
        {
            text = JsonHelper.DataTableToJson(dt);
        }
        return text;
    }
    //绑定机型
    public string BindMachineType()
    {
        string text = "";
        DataTable dt;
        CraftMana_step.enginetypeSelect(out dt);
        if (dt != null && dt.Rows.Count > 0)
        {
            text = JsonHelper.DataTableToJson(dt);
        }
        return text;
    }
    //控件绑定分钟
    public string BindMinutes()
    {
        string text = "";
        DataTable dt = new DataTable();
        dt.Columns.Add("分钟", typeof(string));
        for (int i = 0; i < 60; i++)
        {
            DataRow dr = dt.NewRow();
            dr["分钟"] = i.ToString("00");
            dt.Rows.Add(dr);
        }
        if (dt != null && dt.Rows.Count > 0)
        {
            text = JsonHelper.DataTableToJson(dt);
        }
        return text;
    }

    //控件绑定小时
    public string BindHour()
    {
        string text = "";
        DataTable dt = new DataTable();
        dt.Columns.Add("小时", typeof(string));
        for (int i = 0; i < 24; i++)
        {
            DataRow dr = dt.NewRow();
            dr["小时"] = i;
            dt.Rows.Add(dr);
        }
        if (dt != null && dt.Rows.Count > 0)
        {
            text = JsonHelper.DataTableToJson(dt);
        }
        return text;
    }
    public string OutPutData()
    {
        DataTable dt = null;
        bool EnginIDCheck = false;
        string EnginID = "";
        bool OPNameCheck = Convert.ToBoolean(HttpContext.Current.Request["OPNameCheck"]);
        string OPName = HttpContext.Current.Request["OPName"];
        bool shaftNameCheck = Convert.ToBoolean(HttpContext.Current.Request["shaftNameCheck"]);
        string shaftName = HttpContext.Current.Request["shaftName"];
        bool itemNameCheck = Convert.ToBoolean(HttpContext.Current.Request["itemNameCheck"]);
        string itemName = HttpContext.Current.Request["itemName"];
        string startTime = HttpContext.Current.Request["startTime"];
        string endTime = null;
        string hour = HttpContext.Current.Request["Hour"];
        string minutes = HttpContext.Current.Request["Minutes"];
        startTime = startTime + " " + hour + ":" + minutes + ":" + "00";
        string EngineTypeID = HttpContext.Current.Request["EngineTypeID"]; ;
        bool EngineTypeIDCheck = Convert.ToBoolean(HttpContext.Current.Request["EngineTypeIDCheck"]);
        int n = Convert.ToInt32(HttpContext.Current.Request["Yangben"]);
        int k = Convert.ToInt32(HttpContext.Current.Request["Num"]);
        QualityData.SelectGoodDataReport_DataGroup(EnginIDCheck, EnginID,
           OPNameCheck, OPName,
           EngineTypeID, EngineTypeIDCheck,
            shaftNameCheck, shaftName,
           itemNameCheck, itemName,
            startTime, endTime, n, k, out  dt);
        //string path = HttpContext.Current.Server.MapPath("~/Chart_excel/QualityData_TrendPictureBasic_01.png");
        string path = "QualityData_TrendPictureBasic_01.png";
        if (dt != null)
        {
            if (dt.Rows.Count > 0)
            {
                CommonFunction.OutPutDataAndPic(path, dt);
            }
        }
        return "";
    }

    public string SaveImg()
    {
        //string path = "c:\\QualityData_TrendPictureBasic_01.png";
        string path = HttpContext.Current.Server.MapPath("~/Chart_excel/QualityData_TrendPictureBasic_01.png");
        string byteStr = HttpContext.Current.Request["ImageDate"].Replace("data:image/png;base64,", "");
        System.Drawing.Image returnImage = Base64StringToImage(byteStr);
        if (System.IO.File.Exists(path))
        {
            System.IO.File.Delete(path);
        }
        returnImage.Save(path, System.Drawing.Imaging.ImageFormat.Png);
        return "{\"result\":\"1\"}"; ;
    }
    private System.Drawing.Image Base64StringToImage(string txt)
    {
        byte[] arr = Convert.FromBase64String(txt);
        System.IO.MemoryStream ms = new System.IO.MemoryStream(arr);
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);
        return bmp;
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}