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

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



public class QualityData_Pareto : 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 "GetChart":
                responseText = GetChart();
                break;
            //导出excel
            case "dataoutexcel":
                responseText = outexcel();
                break;
        }



        context.Response.Write(responseText);
    }

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

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

        bool EngineTypeIDCheck = true;
        string EngineTypeID = HttpContext.Current.Request["EngineTypeID"];
        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 Hour = HttpContext.Current.Request["Hour"];
        string Minutes = HttpContext.Current.Request["Minutes"];
        int n = Convert.ToInt32(HttpContext.Current.Request["Yangben"]);
        int k = Convert.ToInt32(HttpContext.Current.Request["Num"]);
        startTime = startTime + " " + Hour + ":" + Minutes + ":" + "00";
        string endTime = null;
        bool EnginIDCheck = false;
        string EngineID = null;


        QualityData.SelectGoodDataReport_DataGroup(EnginIDCheck, EngineID,
        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行
            }
        }
        string text = "";
        if (dt1 != null && dt1.Rows.Count > 0)
        {
            text = JsonHelper.CreateJsonParameters(dt1, true, dt.Rows.Count);
        }
        return text;


    }

    public string GetChart()
    {
        System.Data.DataTable dt = null;

        bool EngineTypeIDCheck = Convert.ToBoolean(HttpContext.Current.Request["EngineTypeIDCheck"]);
        string EngineTypeID = HttpContext.Current.Request["EngineTypeID"];
        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 Hour = HttpContext.Current.Request["Hour"];
        //string Minutes = HttpContext.Current.Request["Minutes"];
        int n = Convert.ToInt32(HttpContext.Current.Request["Yangben"]);
        int k = Convert.ToInt32(HttpContext.Current.Request["Num"]);
        //startTime = startTime + " " + Hour + ":" + Minutes + ":" + "00";
        string endTime = HttpContext.Current.Request["endTime"];
        bool EnginIDCheck = false;
        string EngineID = null;


        QualityData.SelectGoodDataReport_DataGroup(EnginIDCheck, EngineID,
        OPNameCheck, OPName,
         EngineTypeID, EngineTypeIDCheck,
         shaftNameCheck, shaftName,
        itemNameCheck, itemName,
         startTime, endTime, n, k, out  dt);
        StringBuilder textadd = new StringBuilder();
        try
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                int len = dt.Rows.Count;
                double[] str = new double[len];
                for (int i = 0; i < len; i++)
                {
                    str[i] = Convert.ToDouble(dt.Rows[i]["测量值"]);
                }

                double minV = Min(str);
                double maxV = Max(str);
                double Dv = (maxV - minV) / n;
                Dv = RoundInterval(Dv);
                minV = Math.Floor(minV / Dv) * Dv;
                maxV = Math.Ceiling(maxV / Dv) * Dv;

                string textY1 = "";
                string textY2 = "";
                string textX = "";
                string textX1 = "";
                string textX2 = "";
                double acv = 0.0;
                object average;
                double bottom = minV;


                for (bottom = minV; bottom < maxV; bottom += Dv)
                {
                    int number = 0;
                    double top = bottom + Dv;
                    foreach (double p in str)
                    {
                        if (top >= maxV)
                        {
                            if (p >= bottom && p <= top)
                                ++number;
                        }
                        else
                        {
                            if (p >= bottom && p < top)
                                ++number;
                        }

                    }
                    acv += Convert.ToDouble(number);
                    average = ((acv / (n * k)) * 100).ToString("0.00");
                    textX1=Convert.ToString(bottom);
                    textX2=Convert.ToString(top);
                    textX += textX1+'-'+textX2;
                    textY1 += number;
                    textY2 += average;
                    if (top < maxV)
                    {
                        textY1 += ",";
                        textY2 += ",";
                        textX += ",";
                    }
                }

                textadd.Append(textY1);
                textadd.Append("|");
                textadd.Append(textY2);
                textadd.Append("|");
                textadd.Append(textX);


            }
        }
        catch (Exception)
        {

        }
        
        return Convert.ToString(textadd);
    }

    /// <summary>
    /// 观测值最大值
    /// </summary>
    /// <param name="Xn">子组观测值</param>
    /// <returns></returns>
    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>
    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 outexcel()
    {
        System.Data.DataTable dt = null;

        bool EngineTypeIDCheck = true;
        string EngineTypeID = HttpContext.Current.Request["EngineTypeID"];
        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 Hour = HttpContext.Current.Request["Hour"];
        string Minutes = HttpContext.Current.Request["Minutes"];
        int n = Convert.ToInt32(HttpContext.Current.Request["Yangben"]);
        int k = Convert.ToInt32(HttpContext.Current.Request["Num"]);
        startTime = startTime + " " + Hour + ":" + Minutes + ":" + "00";
        string endTime = null;
        bool EnginIDCheck = false;
        string EngineID = null;


        QualityData.SelectGoodDataReport_DataGroup(EnginIDCheck, EngineID,
        OPNameCheck, OPName,
         EngineTypeID, EngineTypeIDCheck,
         shaftNameCheck, shaftName,
        itemNameCheck, itemName,
         startTime, endTime, n, k, out  dt);
        //string path = "QualityData_Pareto.png";
        //string path = HttpContext.Current.Server.MapPath("~/Chart_excel/QualityData_Pareto.png");
        string path ="QualityData_Pareto.png";
        if (dt != null)
        {
            if (dt.Rows.Count > 0)
            {
                dt.TableName = "SPC分析排列图";

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dt.Rows[i]["序号"] = (i + 1).ToString("000000");
                }

                CommonFunction.OutPutDataAndPic(path, dt);
            }
        }
        return "";
    }

    /// <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 SaveImg()
    {
        string path = HttpContext.Current.Server.MapPath("~/Chart_excel/QualityData_Pareto.png"); //local path
        string byteStr = HttpContext.Current.Request["ImageDate"].Replace("data:image/png;base64,", "");//rec img data
        System.Drawing.Image returnImage = Base64StringToImage(byteStr); //init img
        if (System.IO.File.Exists(path))
        {
            System.IO.File.Delete(path);
        }
        returnImage.Save(path);
        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;
        }
    }

    public double RoundInterval(double interval)
    {
        // If the interval is zero return error
        if (interval == 0.0)
        {
            // throw (new ArgumentOutOfRangeException("interval", "Interval can not be zero."));
            return 0;
        }

        // If the real interval is > 1.0
        double step = -1;
        double tempValue = interval;
        while (tempValue > 1.0)
        {
            step++;
            tempValue = tempValue / 10.0;
            if (step > 1000)
            {
                throw (new InvalidOperationException("Auto interval error due to invalid point values or axis minimum/maximum."));
            }
        }

        // If the real interval is < 1.0
        tempValue = interval;
        if (tempValue < 1.0)
        {
            step = 0;
        }

        while (tempValue < 1.0)
        {
            step--;
            tempValue = tempValue * 10.0;
            if (step < -1000)
            {
                throw (new InvalidOperationException("Auto interval error due to invalid point values or axis minimum/maximum."));
            }
        }

        double tempDiff = interval / Math.Pow(10.0, step);
        if (tempDiff < 3.0)
        {
            tempDiff = 2.0;
        }
        else if (tempDiff < 7.0)
        {
            tempDiff = 5.0;
        }
        else
        {
            tempDiff = 10.0;
        }

        // Make a correction of the real interval
        return tempDiff * Math.Pow(10.0, step);
    }
}