using DataLinkMesWork;
using bizFacade;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
//using SystemFramework;

namespace MesWebFun
{
    public  class WebFunction11
    {
        HttpContext contextMesWebFun;
        public string ProcessRequest(HttpContext context)
        {
            contextMesWebFun = context; ;
            context.Response.ContentType = "text/plain";
            string type = contextMesWebFun.Request["type"];
            string responseText = "";
            switch (type)
            {
                //托盘信息
                case "MobySelect":
                   // responseText = MobySelect();
                    break;
                //保存手动生成条码
                case "SavingEngineIDShift":
                    responseText = SavingEngineIDShift();
                    break;
                case "SaveRepairStatus"://将返修路径及返修数据保存到数据库
                    responseText = SaveRepairStatus();
                    break;
                case "RepairStatusInit"://将返修路径及返修数据保存到数据库
                    responseText = RepairStatusInit();
                    break;
                case "Select_engineType_ByEnergineID": //根据发动机号显示机型
                    responseText = Select_engineType_ByEnergineID();
                    break;
                case "QualityDataButton_bgColor_Select_ByEnergineID":
                    responseText = QualityDataButton_bgColor_Select_energineSelect();
                    break;
                ///////////////////////质量查询根据发动机号
                case "QualityDataSelectByEnergineID":
                    responseText = QualityDataSelectByEnergineID();
                    break;
                default:
                    responseText = "05";
                    break;


            }
            return responseText;
        }
        /// <summary>
        /// //根据发动机号显示机型，界面提示
        /// </summary>
        /// <returns></returns>
        private string Select_engineType_ByEnergineID()
        {
            string text = "";
            try
            {
                System.Data.DataTable dt = null;
                string opName = HttpContext.Current.Request["value"];//发动机号
                string energineID = HttpContext.Current.Request["energineID"];//发动机号
                GetEngineID_Select(energineID, opName, out dt);

                string engineType = "";
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        engineType = dt.Rows[0]["发动机型号"].ToString();
                    }
                }
                text = "{\"engineType\":\"" + engineType + "\"}";
            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID");
            }
            return text;
        }
        /// <summary>
        /// 保存手动要求的条码
        /// </summary>
        /// <returns></returns>
        private string SavingEngineIDShift()
        {
            string text = "";
            bool flag = false;
            System.Data.DataTable dt = null;
            try
            {
                string opname = HttpContext.Current.Request["value"];//工位号
                string date = HttpContext.Current.Request["date"];//日期
                string num = HttpContext.Current.Request["num"];//流水号
                string[] dates = date.Split('-');
                if (dates.Length > 2)
                {
                    int year = Convert.ToInt32(dates[0]);
                    int month = Convert.ToInt32(dates[1]);
                    int day = Convert.ToInt32(dates[2]);
                    int single = Convert.ToInt32(num);
                    MES.OpName_MIS_Manual_Insert(opname, year, month, day, single);
                    flag = true;
                }
                if (flag)
                {
                    text = "{\"flag\":\"1\"}";
                }
                else
                {
                    text = "{\"flag\":\"0\"}";
                }
                return text;
            }
            catch (Exception err)
            {
                text = "{\"flag\":\"0\"}";
                //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift");
                return text;
            }
        }

        private static string RepairStatusInit()
        {
            string Opname = HttpContext.Current.Request["value"];//工位号 
            string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID
            string outtext = CreateRepairUpLine(Opname, selectID);
            return outtext;
        }


        /// <summary>
        /// 动态创建返修上线工位按钮
        /// </summary>
        /// <param name="OpName"></param>
        /// <returns></returns>
        public static string CreateRepairUpLine(string OpName, string selectID)
        {
            StringBuilder HtmlStr = new StringBuilder();//可修改字符串

            string BtnData = "";
            int RouteNum = 0;
            bool HaveDataOrNot = false;
            DataTable dt;

            string StationDataStr;//最近一条返修工位数据
            //查询返修上线字符串及路径数目
            RepairBtnDataSelect(OpName, out BtnData, out RouteNum);
            string[] RepairSta = BtnData.Split('^');//目标工位数组
            string TargetStationData = "";//目标工位数据
                                          //查询之前的返修上线数据
            HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt);
            //合成界面显示按钮字符串
            if (HaveDataOrNot)
            {
                StationDataStr = dt.Rows[0]["返修字符串"].ToString();
                if (StationDataStr == "")
                {
                    for (int i = 0; i < RepairSta.Length; i++)
                    {
                        if (i < (RepairSta.Length - 1))
                        {
                            TargetStationData = TargetStationData + "1^";
                        }
                        else
                        {
                            TargetStationData = TargetStationData + "1";
                        }
                    }
                }
                else
                {
                    TargetStationData = StationDataStr;
                }
            }
            else
            {

                for (int i = 0; i < RepairSta.Length; i++)
                {
                    if (i < (RepairSta.Length - 1))
                    {
                        TargetStationData = TargetStationData + "1^";
                    }
                    else
                    {
                        TargetStationData = TargetStationData + "1";
                    }
                }
            }
            //页面定义
            HtmlStr.Append("<table style=\"width:100%;height:100%;\" ><tr><td style=\"height:15px\"></td></tr>\r\n<tr>");
            for (int i = 0; i < RepairSta.Length; i++)
            {
                //动态生成标签
                //样式定义
                string td_style = "width:20%;height:35px";//td样式
                string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式
                string type = "button";
                string tagID = "Btn_" + RepairSta[i];
                string value = RepairSta[i];
                string onclick = "RepairBtnClick(Btn_" + value + ")";
                string[] StationDataArray = TargetStationData.Split('^');
                string bgColor;

                if (StationDataArray[i] == "1")
                {
                    bgColor = "background-color: green";
                }
                else
                {
                    bgColor = "background-color: gray";
                }
                //保证每行5个按钮
                if (i < RepairSta.Length - 1)
                {
                    if (i % 5 < 4)
                    {
                        HtmlStr.Append("<td  style=\"" + td_style + "\"><input name=\"RepairBtn\" id=\"" + tagID + "\" type=\"" + type + "\" style=\"" + btn_style + ";" + bgColor + "\" value=\"" + value + "\" onclick=\"" + onclick + "\"/></td>");
                    }
                    else
                    {
                        HtmlStr.Append("<td  style=\"" + td_style + "\"><input name=\"RepairBtn\" id=\"" + tagID + "\" type=\"" + type + "\" style=\"" + btn_style + ";" + bgColor + "\" value=\"" + value + "\" onclick=\"" + onclick + "\"/></td>");
                        HtmlStr.Append("</tr>\r\n<tr>");
                    }
                }
                else
                {
                    HtmlStr.Append("<td  style=\"" + td_style + "\"><input name=\"RepairBtn\" id=\"" + tagID + "\" type=\"" + type + "\" style=\"" + btn_style + ";" + bgColor + "\" value=\"" + value + "\" onclick=\"" + onclick + "\"/></td>");
                    HtmlStr.Append("</tr><tr><td style=\"height:15px\"></td></tr>");
                }

            }
            HtmlStr.Append("</table>");
            //上线路径大于1条则显示上线路径
            if (RouteNum > 1)
            {

            }
            return HtmlStr.ToString();
        }


        /// <summary>
        /// 向数据库写入返修数据
        /// </summary>
        /// <param name="opName"></param>
        /// <param name="engineID"></param>
        /// <returns></returns>
        public static bool updateRepairStatusTo_SQL(string opname, string status)
        {
            string produceName = "测量数据_返修工位_工位状态_修改";
            SqlParameter[] thisParms = new SqlParameter[2];
            thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname);
            thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status);

            return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms);
        }
        private static string SaveRepairStatus()
        {

            try
            {
                string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态
                string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号
                int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径
                string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号
                string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点
                string[] RepairStatusSplit = RepairStatus.Split('|');
                for (int i = 0; i < RepairStatusSplit.Length - 1; i++)
                {
                    updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]);
                }

                string produceName = "返修上线_返修工位及返修路径_增加";
                SqlParameter[] thisParms = new SqlParameter[5];
                thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID);
                thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus);
                thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod);
                thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType);
                thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName);
                string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms));
                return result;
            }
            catch (Exception err)
            {
                return "0";
            }

        }
        /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian
        /// </summary>
        /// <param name="engineID"></param>
        /// <param name="opName"></param>
        static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt)
        {
            string errorMessage = "";
            DataSet ds;
            bool isOK;
            dt = null;
            //string connectionString = ApplicationConfig.ConnectionString;
            string procedureName;
            procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号";
            SqlParameter[] thisParms = new SqlParameter[2];
            thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID);
            thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName);
            isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds);
            if (isOK)
            {
                if (ds.Tables.Count > 0)
                {
                    dt = ds.Tables[0];
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        private string QualityDataButton_bgColor_Select_energineSelect()
        {
            string text = "";
            try
            {
                System.Data.DataTable dt = null;
                //单号
                string energineID = HttpContext.Current.Request["energineID"];
                string opname = HttpContext.Current.Request["value"];
                QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数
                if (dt != null)
                {
                    if (dt.Rows.Count >= 0)
                    {
                        text = Buttons.Createbuttons(dt);
                    }
                }
            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select");
            }
            return text;

        }
        /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt
        /// </summary>
        /// <param name="opname"></param>
        /// <param name="engineId"></param>
        /// <param name="tb"></param>
        /// <returns></returns>
        public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt)
        {
            string procedureName = "显示测量数据_工位号_根据发动机型号_查询";
            SqlParameter[] sqlParameters = new SqlParameter[2];
            sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname);
            sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID);
            return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt);
        }


        /// <summary>
        /// 获取对应工位的质量数据
        /// </summary>
        /// <returns></returns>
        private string QualityDataSelectByEnergineID()
        {
            string qualitydata = "";
            try
            {
                System.Data.DataTable dt = null;
                string energineID = HttpContext.Current.Request["value"];
                string opname = HttpContext.Current.Request["opname"];
                QualityDataSelect(opname, energineID, out dt);
                if (dt != null)
                {
                    //if (dt.Rows.Count > 0)
                    {
                        qualitydata = JsonHelper.CreateJsonParameters(dt);
                    }
                }
            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect");
            }
            return qualitydata;

        }

        static public bool QualityDataSelect(string opname, string energineID, out DataTable dt)
        {
            string procedureName;
            procedureName = "显示测量数据_根据_工位号_发动机型号_查询";
            SqlParameter[] sqlParameters = new SqlParameter[2];
            sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname);
            sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID);
            return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt);
        }

        /// <summary>
        /// 查询返修上线工位及返修路径数目
        /// </summary>
        /// <param name="OpName"></param>
        /// <param name="BtnData"></param>
        /// <param name="RouteNum"></param>
        public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum)
        {

            DataTable dt;
            string procedureName;
            BtnData = "";
            RouteNum = 0;
            procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询";
            SqlParameter[] sqlParameters = new SqlParameter[1];
            sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName);
            DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    BtnData = dt.Rows[0]["待返修工位"].ToString();
                    RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]);
                }
            }
        }


        /// <summary>
        /// 查询当前上线点上次选择的返修工位，用于界面按钮颜色原始数据
        /// </summary>
        /// <param name="OpName"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static bool selectRepairData(string OpName, out DataTable dt)
        {

            string procedureName;
            procedureName = "返修上线_返修工位及返修路径_最近数据_查询";
            SqlParameter[] sqlParameters = new SqlParameter[1];
            sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName);
            DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt);
            if (dt.Rows.Count > 0)
            {
                return true;
            }
            else
            {

                return false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="OpName"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt)
        {
            string procedureName;
            procedureName = "返修上线_返修工位及返修路径_是否工作判断";
            SqlParameter[] sqlParameters = new SqlParameter[2];
            sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName);
            sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID);
            DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt);
            if (dt.Rows.Count > 0)
            {
                return true;
            }
            else
            {

                return false;
            }

        }

    }
}
