using DBUtility;
using PaintingScreen.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;

namespace PaintingScreen.Handler
{
    public class Function
    {
        #region 喷涂下线合格率看板--滚动版
        public static string GetTable1()
        {
            string tableStr = "";
            try
            {
                tableStr += "<table>";

                DataTable dt = GetOnePassTable();
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        tableStr += "<tr>";
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            tableStr += "<td class='TableContent'>" + dt.Rows[i][j].ToString() + "</td>";
                        }
                        tableStr += "</tr>";
                    }
                    tableStr += "</tr>";
                }

                tableStr += "</table>";

                return tableStr;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogManager(ex);
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return tableStr;
            }
        }

        public static DataTable GetOnePassTable()
        {
            DataTable res = new DataTable();
            try
            {
                string sql = @"
                                
                                -- 一次合格数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #a
                                  FROM [BBMPT].[dbo].[tb_InspectResult] 
                                  WHERE InspectTimes = '1' AND " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC

                                -- 总合格数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #b
                                  FROM [BBMPT].[dbo].[tb_InspectResult]
                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC

                                --总下线数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #c
                                  FROM [BBMPT].[dbo].[tb_InspectResult]
                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult in ('[合格]','[抛光]','报废') AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC

                                --合并临时表
                                SELECT REPLACE(SUBSTRING(c.productInfo,1,charindex(',',c.productInfo)),',','') as  [color]
                                ,REPLACE(RIGHT(c.productInfo,charindex(',',REVERSE(c.productInfo))),',','') as  [productInfo]
                                ,ISNULL(c.num,0) sumNum, ISNULL(a.num,0) oncePassNum
                                ,CONVERT(VARCHAR(20),ROUND(100*(ISNULL(a.num,0)/CONVERT(float,ISNULL(c.num,0))),2))+'%' oncePassRate 
                                ,ISNULL(b.num,0) sumPassNum
                                ,CONVERT(VARCHAR(20),ROUND(100*(ISNULL(b.num,0)/CONVERT(float,ISNULL(c.num,0))),2))+'%' sumPassRate
                                FROM #c c
                                LEFT JOIN #a a
                                ON c.productInfo = a.productInfo
                                LEFT JOIN #b b
                                ON c.productInfo = b.productInfo
                                ORDER BY color,productInfo

                                DROP TABLE #a;
                                DROP TABLE #b;
                                DROP TABLE #c;
                            ";
                res = SqlHelper.GetDataDateTable(SqlHelper.SqlConnString, CommandType.Text, sql, null);
                return res;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogManager(ex);
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return res;
            }
        }

        public static string GetTableSum()
        {
            string res = "";
            try
            {
                #region 2019-08-06 注销:客户要求改变总合格率算法,使用总数-报废数,而不是实时合格数计算
//                string sql = @" 
//                                -- 一次合格数
//                                SELECT COUNT(DISTINCT barcode) num, productInfo
//                                  INTO #a
//                                  FROM [BBMPT].[dbo].[tb_InspectResult] 
//                                  WHERE InspectTimes = '1' AND " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
//                                  GROUP BY productInfo
//                                  ORDER BY productInfo DESC
//
//                                -- 总合格数
//                                SELECT COUNT(DISTINCT barcode) num, productInfo
//                                  INTO #b
//                                  FROM [BBMPT].[dbo].[tb_InspectResult]
//                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
//                                  GROUP BY productInfo
//                                  ORDER BY productInfo DESC
//
//                                --总下线数
//                                SELECT COUNT(DISTINCT barcode) num, productInfo
//                                  INTO #c
//                                  FROM [BBMPT].[dbo].[tb_InspectResult]
//                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult in ('[合格]','[抛光]','报废') AND SUBSTRING(productInfo,1,1) != ','
//                                  GROUP BY productInfo
//                                  ORDER BY productInfo DESC
//
//                                --合并临时表
//                                SELECT SUM(ISNULL(c.num,0)) sumNum, SUM(ISNULL(a.num,0)) oncePassNum
//                                ,CONVERT(VARCHAR(20),ROUND(100*(SUM(ISNULL(a.num,0))/CONVERT(float,SUM(ISNULL(c.num,0)))),2))+'%' oncePassRate 
//                                ,SUM(ISNULL(b.num,0)) sumPassNum
//                                ,CONVERT(VARCHAR(20),ROUND(100*(SUM(ISNULL(b.num,0))/CONVERT(float,SUM(ISNULL(c.num,0)))),2))+'%' sumPassRate
//                                FROM #c c
//                                LEFT JOIN #a a
//                                ON c.productInfo = a.productInfo
//                                LEFT JOIN #b b
//                                ON c.productInfo = b.productInfo
//
//                                DROP TABLE #a;
//                                DROP TABLE #b;
//                                DROP TABLE #c;
//                            "; 
                #endregion

                string sql = @"
                                    -- 一次合格数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #a
                                  FROM [BBMPT].[dbo].[tb_InspectResult] 
                                  WHERE InspectTimes = '1' AND " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC

                                -- 总合格数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #b
                                  FROM [BBMPT].[dbo].[tb_InspectResult]
                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC

								-- 报废+点修补数
								SELECT SUM(num) abtNum, productInfo INTO #d FROM
								(
								 SELECT num, productInfo FROM
								 (SELECT COUNT(DISTINCT barcode) num, productInfo
									  FROM [BBMPT].[dbo].[tb_InspectResult]
									  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[报废]'
									  AND SUBSTRING(productInfo,1,1) != ','
									  GROUP BY productInfo) a
									  UNION
								SELECT * FROM (SELECT COUNT(DISTINCT barcode) num, productInfo
									  FROM [BBMPT].[dbo].[tb_InspectResult]
									  WHERE " + GetQueryTime() + @" AND productInfo != ''
									  AND stationNo = 'S10' AND inspectResult <> '[合格]'
									  AND SUBSTRING(productInfo,1,1) != ','
									  GROUP BY productInfo) b
									  ) aa
								GROUP BY productInfo

                                --总下线数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #c
                                  FROM [BBMPT].[dbo].[tb_InspectResult]
                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult in ('[合格]','[抛光]','报废') AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC

                                --合并临时表(总合格数=总下线数-总报废数 计算比率)
                                SELECT SUM(ISNULL(c.num,0)) sumNum, SUM(ISNULL(a.num,0)) oncePassNum, SUM(ISNULL(d.abtNum,0)) abtNum,SUM(ISNULL(b.num,0)) sumPassNum
                                ,CONVERT(VARCHAR(20),ROUND(100*(SUM(ISNULL(a.num,0))/CONVERT(float,SUM(ISNULL(c.num,0)))),2))+'%' oncePassRate 
                                ,CONVERT(VARCHAR(20),ROUND(100*((SUM(ISNULL(c.num,0))-SUM(ISNULL(d.abtNum,0)))/CONVERT(float,SUM(ISNULL(c.num,0)))),2))+'%' sumPassRate
                                FROM #c c
                                LEFT JOIN #a a
                                ON c.productInfo = a.productInfo
                                LEFT JOIN #b b
                                ON c.productInfo = b.productInfo
								LEFT JOIN #d d
                                ON c.productInfo = d.productInfo

                                DROP TABLE #a;
                                DROP TABLE #b;
                                DROP TABLE #c;
								DROP TABLE #d;
                            ";

                DataTable dt = SqlHelper.GetDataDateTable(SqlHelper.SqlConnString, CommandType.Text, sql, null);
                if (dt != null && dt.Rows.Count > 0)
                {
                    res += @" <table class='borderTable' style='height:92px;'><tr><td class='TableContent'>总数</td><td class='TableContent'></td><td class='TableContent'>" + dt.Rows[0]["sumNum"] +
                           @"</td><td class='TableContent'>" + dt.Rows[0]["oncePassNum"] + "</td><td class='TableContent'>" + dt.Rows[0]["oncePassRate"] +
                           @"</td><td class='TableContent'>" + dt.Rows[0]["sumPassNum"] + @"</td><td class='TableContent'>" + dt.Rows[0]["sumPassRate"] + @"</td></tr></table> ";
                }

                return res;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogManager(ex);
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return res;
            }
        }

        /// <summary>
        /// 获取班次,规定早8至晚8为A班
        /// </summary>
        /// <returns></returns>
        public static string GetQueryTime()
        {
            bool classA = IsBetweenTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "2019-06-12 08:00:00", "2019-06-12 20:00:00");
            if (classA)
            {
                //A班为当日8点至20点
                return "createTime >= '" + DateTime.Now.ToShortDateString() + " 08:00:00' AND createTime <= '" + DateTime.Now.ToShortDateString() + " 20:00:00'";
            }
            else
            {
                //B班为当日20点至次日8点

                if (IsBetweenTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "2019-06-12 20:00:00", "2019-06-12 23:59:59"))
                {
                    return "createTime >= '" + DateTime.Now.ToShortDateString() + " 20:00:00' AND createTime <= '" + DateTime.Now.AddDays(1).ToShortDateString() + " 08:00:00'";
                }
                else
                {
                    return "createTime >= '" + DateTime.Now.AddDays(-1).ToShortDateString() + " 20:00:00' AND createTime <= '" + DateTime.Now.ToShortDateString() + " 08:00:00'";
                }
            }
        }

        /// <summary>
        /// 判断传入时间是否在工作时间段内
        /// </summary>
        /// <param name="timeStr"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public static bool IsBetweenTime(string timeStr, string startTime, string endTime)
        {
            //判断传入时间是否在工作时间段内
            try
            {
                TimeSpan startSpan = DateTime.Parse(startTime).TimeOfDay;
                TimeSpan endSpan = DateTime.Parse(endTime).TimeOfDay;

                DateTime t1 = Convert.ToDateTime(timeStr);
                TimeSpan dspNow = t1.TimeOfDay;
                if (dspNow > startSpan && dspNow < endSpan)
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return false;
            }
        } 
        #endregion

        #region 喷涂下线合格率看板--分页版

        public static string CreateTable()
        {
            try
            {
                string sql = @"
                                USE BBMPT;

                                IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_ReportPaintingScreen]') AND type in (N'U'))
                                drop table tb_ReportPaintingScreen;
                                    
                                 -- 一次合格数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #a
                                  FROM [BBMPT].[dbo].[tb_InspectResult] 
                                  WHERE InspectTimes = '1' AND " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC;

                                -- 总合格数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #b
                                  FROM [BBMPT].[dbo].[tb_InspectResult]
                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC;

                                --总下线数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #c
                                  FROM [BBMPT].[dbo].[tb_InspectResult]
                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult in ('[合格]','[抛光]','[报废]') AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC;

                                --合并临时表
                                SELECT REPLACE(SUBSTRING(c.productInfo,1,charindex(',',c.productInfo)),',','') as  [color]
                                ,REPLACE(RIGHT(c.productInfo,charindex(',',REVERSE(c.productInfo))),',','') as  [productInfo]
                                ,ISNULL(c.num,0) sumNum, ISNULL(a.num,0) oncePassNum
                                ,CONVERT(VARCHAR(20),ROUND(100*(ISNULL(a.num,0)/CONVERT(float,ISNULL(c.num,0))),2))+'%' oncePassRate 
                                ,ISNULL(b.num,0) sumPassNum
                                ,CONVERT(VARCHAR(20),ROUND(100*(ISNULL(b.num,0)/CONVERT(float,ISNULL(c.num,0))),2))+'%' sumPassRate
                                into tb_ReportPaintingScreen
                                FROM #c c 
                                LEFT JOIN #a a
                                ON c.productInfo = a.productInfo
                                LEFT JOIN #b b
                                ON c.productInfo = b.productInfo
                                ORDER BY color,productInfo;

                                DROP TABLE #a;
                                DROP TABLE #b;
                                DROP TABLE #c;
                            ";
               int res = SqlHelper.ExecuteNonQuery(SqlHelper.SqlConnString, CommandType.Text, sql, null);
               return "1";
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase("喷涂下线合格率看板-生成数据失败:"+ ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return "0";
            }
        }

        public static string CreateMiddleTable()
        {
            string tableStr = "";
            try
            {
                tableStr += "<table class='borderTable'>";
                for (int i = 0; i < 9; i++)
                {
                    tableStr += "<tr>";
                    for (int j = 0; j < 7; j++)
                    {
                        tableStr += "<td class='TableContent' id='m"+i+j+"'></td>";
                    }
                    tableStr += "</tr>";
                }
                tableStr += "</table>";
                return tableStr;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase("喷涂下线合格率看板-生成MiddleTable失败:" + ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return tableStr;
            }
        }

        public static string GetMiddleTableData(string page)
        {
            string res = "";
            try
            {
                string sql = @" 
                                select * from tb_ReportPaintingScreen 
                            ";
                DataTable dt = SqlHelper.GetDataDateTable(SqlHelper.SqlConnString, CommandType.Text, sql, null);
                if (Convert.ToInt32(page) * 9 >= dt.Rows.Count)
                {
                    //查询第一页
                    page = "0";
                }
                else
                { 
                    //查询下一页(page+1页)
                    page = (Convert.ToInt32(page) + 1).ToString();
                }
                string queryStr = @"
                                            declare @pageIndex int;
                                            declare @pageSize int;
                                            set @pageIndex = "+ page +@";
                                            set @pageSize = 9;
                                            select * from 
                                            (
                                            SELECT [color]
                                                    ,[productInfo]
                                                    ,[sumNum]
                                                    ,[oncePassNum]
                                                    ,[oncePassRate]
                                                    ,[sumPassNum]
                                                    ,[sumPassRate]
	                                                ,ROW_NUMBER() OVER(ORDER BY color,productInfo) xh
                                                FROM [tb_ReportPaintingScreen]
                                                ) t
                                                WHERE t.xh between @pageSize*(@pageIndex - 1)+1 and @pageSize*@pageIndex
                                      ";
                DataTable dt_page = SqlHelper.GetDataDateTable(SqlHelper.SqlConnString, CommandType.Text, queryStr, null);
                if (dt_page != null && dt_page.Rows.Count > 0)
                {
                    res += "<table class='borderTable' style='height:760px;'>";
                    for (int i = 0; i < dt_page.Rows.Count; i++)
                    {
                        res += "<tr>";
                        for (int j = 0; j < 7; j++)
                        {
                            res += "<td class='TableContent' id='m" + i + j + "'>" + dt_page.Rows[i][j].ToString() + @"</td>";
                        }
                        res += "</tr>";
                    }
                    res += "</table>";
                    res += ","+ page;
                }
                return res;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase("喷涂下线合格率看板-查询中间分页数据失败:" + ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return res;
            }
        }

        #endregion

        #region 抛光TOP5看板

        public static string CreateTablePaoGuang()
        {
            try
            {
                string sql = @"
                                
                                USE BBMPT;

                                IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_ReportPaintingScreen_pg]') AND type in (N'U'))
                                drop table tb_ReportPaintingScreen_pg;

                                ---------------------------------------------------------------------------

                                -- 总合格数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                INTO #a
                                FROM [tb_InspectResult]
                                WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
                                GROUP BY productInfo
                                ORDER BY productInfo DESC;

                                --总下线数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                INTO #b
                                FROM [tb_InspectResult]
                                WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult in ('[合格]','[抛光]','[报废]') AND SUBSTRING(productInfo,1,1) != ','
                                GROUP BY productInfo
                                ORDER BY productInfo DESC;

                                SELECT b.productInfo, ISNULL(b.num,0) AS sumNum, ISNULL(a.num,0) AS hgNum 
                                INTO #sum
                                FROM #b b
                                LEFT JOIN #a a
                                ON b.productInfo = a.productInfo;

                                ---------------------------------------------------------------------------------------

                                --缺陷分类统计数
                                SELECT [barcode]
                                      ,[reason]
                                      ,[productInfo]
	                                  INTO #result
                                  FROM [tb_InspectResult] 
                                  WHERE " + GetQueryTime() + @"
                                  AND inspectResult = '[抛光]' AND reason <> '' AND reason IS NOT NULL;

                                  SELECT DISTINCT DefectName
                                  INTO #DefectName
                                  FROM [tb_Defect];

                                  SELECT c.productInfo,COUNT(DISTINCT c.barcode) defectNum, d.DefectName
                                  INTO #Defect
                                  FROM #result c 
                                  LEFT JOIN #DefectName d
                                  ON c.reason like '%'+d.DefectName+'%'
                                  GROUP BY c.productInfo, d.DefectName;

                                  -----------------------------------------------------------------------

                                  --缺陷率top5
                                  SELECT tmp.productInfo, defectRate, tmp.DefectName,tmp.sumNum,tmp.hgNum
                                  INTO #FinalResult
                                  FROM
                                  (
                                  SELECT ISNULL(CONVERT(DECIMAL(10,2),(defect.defectNum/CONVERT(FLOAT, [sum].sumNum))*100),0) defectRate, [sum].productInfo, defect.DefectName,[sum].sumNum,[sum].hgNum
                                  FROM #sum [sum]
                                  LEFT JOIN #Defect defect
                                  ON [sum].productInfo = defect.productInfo
                                  WHERE defect.DefectName IS NOT NULL
                                  ) tmp
                                  GROUP BY tmp.productInfo, tmp.defectRate, tmp.DefectName,tmp.sumNum,tmp.hgNum
                                  ORDER BY tmp.productInfo, tmp.defectRate, tmp.DefectName DESC;

                                  SELECT a.productInfo, a.sumNum, a.hgNum,a.DefectName DefectName1,a.defectRate defectRate1,b.DefectName DefectName2,b.defectRate defectRate2,c.DefectName DefectName3,c.defectRate defectRate3,d.DefectName DefectName4,d.defectRate defectRate4,e.DefectName DefectName5,e.defectRate defectRate5
                                  INTO #ResultTemp
                                  FROM #FinalResult a
                                  LEFT JOIN #FinalResult b
                                  ON a.productInfo = b.productInfo AND a.DefectName <> b.DefectName
                                  LEFT JOIN #FinalResult c
                                  ON a.productInfo = c.productInfo AND a.DefectName <> c.DefectName AND b.DefectName <> c.DefectName
                                  LEFT JOIN #FinalResult d
                                  ON a.productInfo = d.productInfo AND a.DefectName <> d.DefectName AND b.DefectName <> d.DefectName AND c.DefectName <> d.DefectName
                                  LEFT JOIN #FinalResult e
                                  ON a.productInfo = e.productInfo AND a.DefectName <> e.DefectName AND b.DefectName <> e.DefectName AND c.DefectName <> e.DefectName AND d.DefectName <> e.DefectName;

                                  SELECT *, ROW_NUMBER() OVER(PARTITION BY a.productInfo ORDER BY a.defectRate1,a.defectRate2,a.defectRate3,a.defectRate4,a.defectRate5 DESC) rowid
                                  INTO #ResultTemp2
                                  FROM #ResultTemp a;
  
                                  SELECT REPLACE(SUBSTRING(a.productInfo,1,charindex(',',a.productInfo)),',','') as  [color]
                                  ,REPLACE(RIGHT(a.productInfo,charindex(',',REVERSE(a.productInfo))),',','') as  [productInfo]
                                  , a.sumNum, a.hgNum, a.DefectName1, a.defectRate1, a.DefectName2, a.defectRate2, a.DefectName3, a.defectRate3, a.DefectName4, a.defectRate4, a.DefectName5, a.defectRate5
                                  INTO tb_ReportPaintingScreen_pg
                                  FROM #ResultTemp2 a
                                  JOIN ( SELECT MAX(rowid) rowid,productInfo FROM #ResultTemp2 GROUP BY productInfo ) b
                                  on a.productInfo = b.productInfo AND a.rowid = b.rowid
                                  ORDER BY a.productInfo;

                                  DROP TABLE #a;
                                  DROP TABLE #b;
                                  DROP TABLE #sum;
                                  DROP TABLE #result;
                                  DROP TABLE #DefectName;
                                  DROP TABLE #Defect;
                                  DROP TABLE #FinalResult;
                                  DROP TABLE #ResultTemp;
                                  DROP TABLE #ResultTemp2;
                            ";
                int res = SqlHelper.ExecuteNonQuery(SqlHelper.SqlConnString, CommandType.Text, sql, null);
                return "1";
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase("抛光TOP5看板-生成数据失败:" + ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return "0";
            }
        }

        public static string GetTableSumPaoGuang()
        {
            string res = "";
            try
            {
                #region 2019-08-06 注销:客户要求改变总合格率算法,使用总数-报废数,而不是实时合格数计算
                //                string sql = @"
                //                                -- 一次合格数
                //                                SELECT COUNT(DISTINCT barcode) num, productInfo
                //                                  INTO #a
                //                                  FROM [BBMPT].[dbo].[tb_InspectResult] 
                //                                  WHERE InspectTimes = '1' AND " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
                //                                  GROUP BY productInfo
                //                                  ORDER BY productInfo DESC
                //
                //                                -- 总合格数
                //                                SELECT COUNT(DISTINCT barcode) num, productInfo
                //                                  INTO #b
                //                                  FROM [BBMPT].[dbo].[tb_InspectResult]
                //                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
                //                                  GROUP BY productInfo
                //                                  ORDER BY productInfo DESC
                //
                //                                --总下线数
                //                                SELECT COUNT(DISTINCT barcode) num, productInfo
                //                                  INTO #c
                //                                  FROM [BBMPT].[dbo].[tb_InspectResult]
                //                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult in ('[合格]','[抛光]','报废') AND SUBSTRING(productInfo,1,1) != ','
                //                                  GROUP BY productInfo
                //                                  ORDER BY productInfo DESC
                //
                //                                --合并临时表
                //                                SELECT SUM(ISNULL(c.num,0)) sumNum, SUM(ISNULL(a.num,0)) oncePassNum
                //                                ,CONVERT(VARCHAR(20),ROUND(100*(SUM(ISNULL(a.num,0))/CONVERT(float,SUM(ISNULL(c.num,0)))),2))+'%' oncePassRate 
                //                                ,SUM(ISNULL(b.num,0)) sumPassNum
                //                                ,CONVERT(VARCHAR(20),ROUND(100*(SUM(ISNULL(b.num,0))/CONVERT(float,SUM(ISNULL(c.num,0)))),2))+'%' sumPassRate
                //                                FROM #c c
                //                                LEFT JOIN #a a
                //                                ON c.productInfo = a.productInfo
                //                                LEFT JOIN #b b
                //                                ON c.productInfo = b.productInfo
                //
                //                                DROP TABLE #a;
                //                                DROP TABLE #b;
                //                                DROP TABLE #c;
                //                            "; 
                #endregion


                string sql = @"
                                    -- 一次合格数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #a
                                  FROM [BBMPT].[dbo].[tb_InspectResult] 
                                  WHERE InspectTimes = '1' AND " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC

                                -- 总合格数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #b
                                  FROM [BBMPT].[dbo].[tb_InspectResult]
                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[合格]' AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC

								-- 报废+点修补数
								SELECT SUM(num) abtNum, productInfo INTO #d FROM
								(
								 SELECT num, productInfo FROM
								 (SELECT COUNT(DISTINCT barcode) num, productInfo
									  FROM [BBMPT].[dbo].[tb_InspectResult]
									  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult = '[报废]'
									  AND SUBSTRING(productInfo,1,1) != ','
									  GROUP BY productInfo) a
									  UNION
								SELECT * FROM (SELECT COUNT(DISTINCT barcode) num, productInfo
									  FROM [BBMPT].[dbo].[tb_InspectResult]
									  WHERE " + GetQueryTime() + @" AND productInfo != ''
									  AND stationNo = 'S10' AND inspectResult <> '[合格]'
									  AND SUBSTRING(productInfo,1,1) != ','
									  GROUP BY productInfo) b
									  ) aa
								GROUP BY productInfo

                                --总下线数
                                SELECT COUNT(DISTINCT barcode) num, productInfo
                                  INTO #c
                                  FROM [BBMPT].[dbo].[tb_InspectResult]
                                  WHERE " + GetQueryTime() + @" AND productInfo != '' AND inspectResult in ('[合格]','[抛光]','报废') AND SUBSTRING(productInfo,1,1) != ','
                                  GROUP BY productInfo
                                  ORDER BY productInfo DESC

                                --合并临时表(总合格数=总下线数-总报废数 计算比率)
                                SELECT SUM(ISNULL(c.num,0)) sumNum, SUM(ISNULL(a.num,0)) oncePassNum, SUM(ISNULL(d.abtNum,0)) abtNum,SUM(ISNULL(b.num,0)) sumPassNum
                                ,CONVERT(VARCHAR(20),ROUND(100*(SUM(ISNULL(a.num,0))/CONVERT(float,SUM(ISNULL(c.num,0)))),2))+'%' oncePassRate 
                                ,CONVERT(VARCHAR(20),ROUND(100*((SUM(ISNULL(c.num,0))-SUM(ISNULL(d.abtNum,0)))/CONVERT(float,SUM(ISNULL(c.num,0)))),2))+'%' sumPassRate
                                FROM #c c
                                LEFT JOIN #a a
                                ON c.productInfo = a.productInfo
                                LEFT JOIN #b b
                                ON c.productInfo = b.productInfo
								LEFT JOIN #d d
                                ON c.productInfo = d.productInfo

                                DROP TABLE #a;
                                DROP TABLE #b;
                                DROP TABLE #c;
								DROP TABLE #d;
                            ";

                DataTable dt = SqlHelper.GetDataDateTable(SqlHelper.SqlConnString, CommandType.Text, sql, null);
                if (dt != null && dt.Rows.Count > 0)
                {
                    res += dt.Rows[0]["sumNum"] + ","
                           + dt.Rows[0]["oncePassNum"] + "," + dt.Rows[0]["oncePassRate"] +
                           "," + dt.Rows[0]["sumPassNum"] + "," + dt.Rows[0]["sumPassRate"];
                }
                return res;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase("抛光TOP5看板-生成数据失败:" + ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return res;
            }
        }

        public static string GetMiddleTablePaoGuang(string page)
        {
            string res = "";
            try
            {
                string sql = @" 
                                select * from tb_ReportPaintingScreen_pg 
                            ";
                DataTable dt = SqlHelper.GetDataDateTable(SqlHelper.SqlConnString, CommandType.Text, sql, null);
                if (Convert.ToInt32(page) * 4 >= dt.Rows.Count)
                {
                    //查询第一页
                    page = "0";
                }
                else
                {
                    //查询下一页(page+1页)
                    page = (Convert.ToInt32(page) + 1).ToString();
                }
                string queryStr = @"
                                            declare @pageIndex int;
                                            declare @pageSize int;
                                            set @pageIndex = " + page + @";
                                            set @pageSize = 4;
                                            select * from 
                                            (
                                            SELECT [color]
                                                  ,[productInfo]
                                                  ,[sumNum]
                                                  ,[hgNum]
                                                  ,[DefectName1]
                                                  ,[defectRate1]
                                                  ,[DefectName2]
                                                  ,[defectRate2]
                                                  ,[DefectName3]
                                                  ,[defectRate3]
                                                  ,[DefectName4]
                                                  ,[defectRate4]
                                                  ,[DefectName5]
                                                  ,[defectRate5]
	                                              ,ROW_NUMBER() OVER(ORDER BY color,productInfo) xh
                                                FROM [tb_ReportPaintingScreen_pg]
                                                ) t
                                                WHERE t.xh between @pageSize*(@pageIndex - 1)+1 and @pageSize*@pageIndex
                                      ";
                DataTable dt_page = SqlHelper.GetDataDateTable(SqlHelper.SqlConnString, CommandType.Text, queryStr, null);
                if (dt_page != null && dt_page.Rows.Count > 0)
                {
                    res += "<table class='borderTable' width='100%' cellpadding='0' cellspacing='0' height='500px' style='color:white; font-size:30px; font-family: 微软雅黑;'>";
                    for (int i = 0; i < dt_page.Rows.Count; i++)
                    {
                        res += @"
                                        <tr>
                                            <td rowspan='2' align='center' width='15%'>" + dt_page.Rows[i]["color"].ToString() + @"</td>
                                            <td rowspan='2' align='center' width='20%'>" + dt_page.Rows[i]["productInfo"].ToString() + @"</td>
                                            <td rowspan='2' width='10%' align='center'>" + dt_page.Rows[i]["sumNum"].ToString() + @"</td>
                                            <td rowspan='2' width='10%' align='center'>" + dt_page.Rows[i]["hgNum"].ToString() + @"</td>
                                            <td align='center' width='9%'>" + dt_page.Rows[i]["DefectName1"].ToString() + @"</td>
                                            <td align='center' width='9%'>" + dt_page.Rows[i]["DefectName2"].ToString() + @"</td>
                                            <td align='center' width='9%'>" + dt_page.Rows[i]["DefectName3"].ToString() + @"</td>
                                            <td align='center' width='9%'>" + dt_page.Rows[i]["DefectName4"].ToString() + @"</td>
                                            <td align='center' width='9%'>" + dt_page.Rows[i]["DefectName5"].ToString() + @"</td>
                                        </tr>
                                        <tr>
                                            <td align='center' width='9%'>" + AddPercent(dt_page.Rows[i]["defectRate1"]) + @"</td>
                                            <td align='center' width='9%'>" + AddPercent(dt_page.Rows[i]["defectRate2"]) + @"</td>
                                            <td align='center' width='9%'>" + AddPercent(dt_page.Rows[i]["defectRate3"]) + @"</td>
                                            <td align='center' width='9%'>" + AddPercent(dt_page.Rows[i]["defectRate4"]) + @"</td>
                                            <td align='center' width='9%'>" + AddPercent(dt_page.Rows[i]["defectRate5"]) + @"</td>
                                        </tr>     
                                   ";
                    }
                    res += "</table>";
                    res += "," + page;
                }
                return res;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase("抛光TOP5看板-查询中间table数据失败:" + ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return res;
            }
        }

        private static string AddPercent(object num)
        {
            if (num != null)
            {
                string tmp = num.ToString();
                if (!string.IsNullOrWhiteSpace(tmp))
                {
                    return tmp + "%";
                }
                else
                {
                    return "";
                }
            }
            else
            {
                return "";
            }
        }

        public static string GetSumDefectPercent()
        {
            string res = "";
            try
            {
                string sql = @"
                                --缺陷分类统计数
                                SELECT [barcode]
                                      ,[reason]
                                      ,[productInfo]
	                                  INTO #result
                                  FROM [tb_InspectResult] 
                                  WHERE " + GetQueryTime() + @"
                                  AND inspectResult = '[抛光]' AND reason <> '' AND reason IS NOT NULL;

                                  SELECT DISTINCT DefectName
                                  INTO #DefectName
                                  FROM [tb_Defect];

                                  SELECT c.productInfo,COUNT(DISTINCT c.barcode) defectNum, d.DefectName
                                  INTO #Defect
                                  FROM #result c 
                                  LEFT JOIN #DefectName d
                                  ON c.reason like '%'+d.DefectName+'%'
                                  GROUP BY c.productInfo, d.DefectName;


								  SELECT TOP 5 DefectName, CONVERT(DECIMAL(10,2),SUM(defectNum)/CONVERT(FLOAT,(SELECT SUM(defectNum) FROM #Defect))*100) defectRate
								  FROM #Defect
								  GROUP BY DefectName
								  ORDER BY defectRate DESC;

								  DROP TABLE #result;
								  DROP TABLE #DefectName;
								  DROP TABLE #Defect;
                            ";
                DataTable dt = SqlHelper.GetDataDateTable(SqlHelper.SqlConnString, CommandType.Text, sql, null);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        res += dt.Rows[i]["DefectName"].ToString() + "," + AddPercent(dt.Rows[i]["defectRate"]) + ",";
                    }
                }
                return res;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase("抛光TOP5看板-查询总数缺陷率数据失败:" + ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return res;
            }
        }

        #endregion
    }
}