using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using ICSharpCode.Core;
using Mesnac.Codd.Session;

namespace Mesnac.Action.ChemicalWeighing.Product
{
    /// <summary>
    /// 生产管理辅助类
    /// </summary>
    public class ProductHelper
    {
        #region 班次

        /// <summary>
        /// 查询所有可用班次数据
        /// </summary>
        /// <returns>返回所有可用班次数据</returns>
        public static DataTable GetShiftData()
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            string sqlstr = "SELECT * FROM Pmt_Shiftime order by Shift_id";
            DataTable dt = dbHelper.GetDataTableBySql(sqlstr);
            return dt;
        }

        /// <summary>
        /// 查询所有可用班次列表
        /// </summary>
        /// <returns>返回所有可用班次实体列表</returns>
        public static List<Entity.Pmt_Shiftime> GetShiftEntityList()
        {
            List<Entity.Pmt_Shiftime> lst = new List<Entity.Pmt_Shiftime>();
            DataTable dt = GetShiftData();
            if (dt != null)
            {
                Entity.Pmt_Shiftime entity = null;
                foreach(DataRow dr in dt.Rows)
                {
                    entity = ConvertDataRowToPptShift(dr);
                    lst.Add(entity);
                }
            }
            return lst;
        }

        /// <summary>
        /// 把DataRow数据行转换未Pmt_Shiftime实体对性爱那个
        /// </summary>
        /// <param name="dr">要转换的DataRow数据行</param>
        /// <returns>返回转换后的实体对象</returns>
        public static Entity.Pmt_Shiftime ConvertDataRowToPptShift(DataRow dr)
        {
            if (dr != null)
            {
                Entity.Pmt_Shiftime entity = new Entity.Pmt_Shiftime();
                entity.Shift_id = (short)Mesnac.Basic.DataProcessor.RowValue(dr, "Shift_id", 0);
                entity.Shift_name = Mesnac.Basic.DataProcessor.RowValue(dr, "Shift_name", String.Empty);
                entity.Shift_st = Mesnac.Basic.DataProcessor.RowValue(dr, "Shift_st", String.Empty);
                entity.Shift_st = Mesnac.Basic.DataProcessor.RowValue(dr, "Shift_st", String.Empty);
                entity.Shift_class = Mesnac.Basic.DataProcessor.RowValue(dr, "Shift_class", 0);
                return entity;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 根据GUID查询班次行记录
        /// </summary>
        /// <param name="guid">guid</param>
        /// <returns>返回对应的行记录</returns>
        public static DataRow GetShiftDataRowByGUID(string guid)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            string sqlstr = "SELECT * FROM Pmt_Shiftime WHERE GUID = @GUID";
            dbHelper.ClearParameter();
            dbHelper.CommandType = CommandType.Text;
            dbHelper.CommandText = sqlstr;
            dbHelper.AddParameter("@GUID", guid);
            DataTable dt = dbHelper.ToDataTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 根据ShiftID查询班次行记录
        /// </summary>
        /// <param name="shiftID">要查询的ShiftID</param>
        /// <returns>返回对应的班次行记录</returns>
        public static DataRow GetShiftDataRowByID(int shiftID)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            string sqlstr = "SELECT * FROM Pmt_Shiftime WHERE Shift_id = @ShiftID";
            dbHelper.ClearParameter();
            dbHelper.CommandType = CommandType.Text;
            dbHelper.CommandText = sqlstr;
            dbHelper.AddParameter("@ShiftID", shiftID);
            DataTable dt = dbHelper.ToDataTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 根据班次ID获取班次名称
        /// </summary>
        /// <param name="shiftID">班次ID</param>
        /// <returns>返回对应的班次名称</returns>
        public static string GetShiftNameByShiftID(int shiftID)
        {
            DataRow dr = GetShiftDataRowByID(shiftID);
            if (dr != null)
            {
                return Mesnac.Basic.DataProcessor.RowValue(dr, "Shift_name", String.Empty);
            }
            return String.Empty;
        }

        /// <summary>
        /// 判断ShiftID在班次表中是否存在
        /// </summary>
        /// <param name="shiftID">要判断的ShiftID</param>
        /// <returns>存在返回true,否则返回false</returns>
        public static bool IsExistsShiftID(string shiftID)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            string sqlstr = "SELECT COUNT(GUID) FROM Pmt_Shiftime WHERE ShiftID = @ShiftID";
            dbHelper.ClearParameter();
            dbHelper.CommandType = CommandType.Text;
            dbHelper.CommandText = sqlstr;
            dbHelper.AddParameter("@ShiftID", shiftID);
            object result = dbHelper.ToScalar();
            if (result != null && result != System.DBNull.Value)
            {
                int intResult = 0;
                if (int.TryParse(result.ToString(), out intResult))
                {
                    if (intResult > 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 判断ShiftName在班次表中是否存在
        /// </summary>
        /// <param name="shiftName">要判断的ShiftName</param>
        /// <returns>存在返回true,否则返回false</returns>
        public static bool IsExistsShiftName(string shiftName)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            string sqlstr = "SELECT COUNT(GUID) FROM Pmt_Shiftime WHERE ShiftName = @ShiftName";
            dbHelper.ClearParameter();
            dbHelper.CommandType = CommandType.Text;
            dbHelper.CommandText = sqlstr;
            dbHelper.AddParameter("@ShiftName", shiftName);
            object result = dbHelper.ToScalar();
            if (result != null && result != System.DBNull.Value)
            {
                int intResult = 0;
                if (int.TryParse(result.ToString(), out intResult))
                {
                    if (intResult > 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        #endregion

        #region 班组

        /// <summary>
        /// 查询所有可用的班组数据
        /// </summary>
        /// <returns>返回所有的班组数据</returns>
        public static DataTable GetClassData()
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            string sqlstr = "SELECT * FROM Pmt_ShiftClass ORDER BY Shift_Class";
            DataTable dt = dbHelper.GetDataTableBySql(sqlstr);
            return dt;
        }

        /// <summary>
        /// 根据GUID查询对用的班组记录行
        /// </summary>
        /// <param name="guid">要查询的GUID</param>
        /// <returns>返回对应的班组记录行</returns>
        public static DataRow GetClassDataRowByGUID(string guid)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            string sqlstr = "SELECT * FROM PptClass WHERE GUID = @GUID";
            dbHelper.ClearParameter();
            dbHelper.CommandType = CommandType.Text;
            dbHelper.CommandText = sqlstr;
            dbHelper.AddParameter("@GUID", guid);
            DataTable dt = dbHelper.ToDataTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 根据ClassID查询对应的记录行
        /// </summary>
        /// <param name="classID">要查询的ClassID</param>
        /// <returns>返回对应的记录行</returns>
        public static DataRow GetClassDataRowByID(int classID)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            string sqlstr = "SELECT * FROM Pmt_ShiftClass WHERE Shift_Class = @ClassID";
            dbHelper.ClearParameter();
            dbHelper.CommandType = CommandType.Text;
            dbHelper.CommandText = sqlstr;
            dbHelper.AddParameter("@ClassID", classID);
            DataTable dt = dbHelper.ToDataTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 根据班次ID获取班次名称
        /// </summary>
        /// <param name="classID">班次ID</param>
        /// <returns>返回对应的班次名称</returns>
        public static string GetClassNameByClassID(int classID)
        {
            DataRow dr = GetClassDataRowByID(classID);
            if (dr != null)
            {
                return Mesnac.Basic.DataProcessor.RowValue(dr, "Shift_Class_Name", String.Empty);
            }
            else
            {
                return String.Empty;
            }            
        }

        /// <summary>
        /// 获取当前班组的下一个班组
        /// </summary>
        /// <param name="classID">当前班组ID</param>
        /// <returns>返回下一班组ID</returns>
        public static int GetNextClassID(int classID)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            string sqlstr = @"if exists(select top 1 ClassID from PptClass where ClassID > @ClassID order by ClassID)
	                                select top 1 ClassID from PptClass where ClassID > @ClassID order by ClassID
                                else
	                                select top 1 ClassID from PptClass order by ClassID";
            dbHelper.CommandType = CommandType.Text;
            dbHelper.CommandText = sqlstr;
            dbHelper.ClearParameter();
            dbHelper.AddParameter("@ClassID", classID);
            object result = dbHelper.ToScalar();
            if (!Mesnac.Basic.DataProcessor.IsNullOrEmpty(result))
            {
                int intResult = 0;
                int.TryParse(result.ToString(), out intResult);
                return intResult;
            }
            return 0;
        }

        /// <summary>
        /// 判断ClassID在班组表中是否存在
        /// </summary>
        /// <param name="classID">要判断的ClassID</param>
        /// <returns>存在返回true,否则返回false</returns>
        public static bool IsExistsClassID(string classID)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            string sqlstr = "SELECT COUNT(GUID) FROM PptClass WHERE ClassID = @ClassID";
            dbHelper.ClearParameter();
            dbHelper.CommandType = CommandType.Text;
            dbHelper.CommandText = sqlstr;
            dbHelper.AddParameter("@ClassID", classID);
            object result = dbHelper.ToScalar();
            if (result != null && result != System.DBNull.Value)
            {
                int intResult = 0;
                if (int.TryParse(result.ToString(), out intResult))
                {
                    if (intResult > 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 判断ClassName在班组表中是否存在
        /// </summary>
        /// <param name="className">要判断的ClassName</param>
        /// <returns>存在返回true,否则返回false</returns>
        public static bool IsExistsClassName(string className)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            string sqlstr = "SELECT COUNT(GUID) FROM PptClass WHERE ClassName = @ClassName";
            dbHelper.ClearParameter();
            dbHelper.CommandType = CommandType.Text;
            dbHelper.CommandText = sqlstr;
            dbHelper.AddParameter("@ClassName", className);
            object result = dbHelper.ToScalar();
            if (result != null && result != System.DBNull.Value)
            {
                int intResult = 0;
                if (int.TryParse(result.ToString(), out intResult))
                {
                    if (intResult > 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        #endregion

        #region 日期班次验证
        /// <summary>
        /// 日期班次验证
        /// </summary>
        /// <param name="plandate">验证后输出的正确日期</param>
        /// <param name="shiftitem">验证后输出的正确班次</param>
        /// <param name="pickervalue">要验证的日期值</param>
        /// <param name="comshiftitem">要验证的班次值</param>
        /// <param name="msg">消息提示</param>
        /// <returns>验证通过返回true,否则返回false</returns>
        public static bool PlanDateVerify(out DateTime plandate, out int shiftitem, string pickervalue, int comshiftitem, out string msg)
        {
            #region 换班

            string firstBegin = "0758";
            string firstEnd = "1540";
            string secondBegin = "1558";
            string secondEnd = "2340";
            string thirdBegin = "2358";
            string thirdEnd = "0740";
            DateTime dt = DateTime.Now;
            object shiftT = null;

            #region 从数据库获取值,填充以上变量

            DataTable shiftTable = GetShiftData();
            if (shiftTable != null && shiftTable.Rows.Count >= 3)
            {
                shiftT = shiftTable.Rows[0]["Shift_st"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        firstBegin = String.Format("{0:HHmm}", dt.AddMinutes(-2));
                    }
                }
                shiftT = shiftTable.Rows[0]["Shift_et"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        firstEnd = String.Format("{0:HHmm}", dt.AddMinutes(-19));
                    }
                }

                shiftT = shiftTable.Rows[1]["Shift_st"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        secondBegin = String.Format("{0:HHmm}", dt.AddMinutes(-2));
                    }
                }
                shiftT = shiftTable.Rows[1]["Shift_et"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        secondEnd = String.Format("{0:HHmm}", dt.AddMinutes(-19));
                    }
                }

                shiftT = shiftTable.Rows[2]["Shift_st"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        thirdBegin = String.Format("{0:HHmm}", dt.AddMinutes(-2));
                    }
                }
                shiftT = shiftTable.Rows[2]["Shift_et"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        thirdEnd = String.Format("{0:HHmm}", dt.AddMinutes(-19));
                    }
                }
            }
            #endregion

            string hhmm = DateTime.Now.ToString("HHmm");
            plandate = DateTime.Now;
            shiftitem = comshiftitem;
            msg = string.Empty;
            if (((hhmm.CompareTo(firstBegin) > 0) && (hhmm.CompareTo(firstEnd) < 0)) || ((hhmm.CompareTo(secondBegin) > 0) && (hhmm.CompareTo(secondEnd) < 0)) || ((hhmm.CompareTo(thirdBegin) > 0) || (hhmm.CompareTo(thirdEnd) < 0)))
            {
                string dt2 = Convert.ToDateTime(pickervalue).ToString("yyyy-MM-dd");
                if ((hhmm.CompareTo(secondBegin) == 1) && (hhmm.CompareTo(secondEnd) == -1))
                {
                    shiftitem = 2;
                }
                else if (hhmm.CompareTo(thirdEnd) == -1 || hhmm.CompareTo(thirdEnd) == 0)
                {
                    plandate = DateTime.Now.Date.AddDays(-1);
                    shiftitem = 3;
                }
                else if (hhmm.CompareTo(thirdBegin) == 1)
                {
                    plandate = DateTime.Now;
                    if (thirdBegin.CompareTo(thirdEnd) == -1)
                    {
                        plandate = DateTime.Now.Date.AddDays(-1);
                    }
                    shiftitem = 3;
                }
                else if ((hhmm.CompareTo(firstEnd) == -1) && (hhmm.CompareTo(firstBegin) == 1)) 
                { 
                    shiftitem = 1; 
                }
                string dt1 = plandate.ToString("yyyy-MM-dd");
                if ((dt1 != dt2) || (comshiftitem != shiftitem))
                {
                    comshiftitem = shiftitem - 1;
                    msg = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Product_ProductHelper_PlanDateVerify_msg"));   // 请将日期班次调整正确:{0}当前生产日期:{1}当前生产班次:{2}!
                    msg = String.Format(msg, "\r\n", String.Format("{0:yyyy-MM-dd}\r\n", plandate), shiftitem.ToString());
                    return false;
                }
                return true;
            }
            return true;

            #endregion
        }
        #endregion

        #region 自动刷新班次号
        /// <summary>
        /// 自动刷新班次号
        /// </summary>
        /// <returns>当前班次号</returns>
        public static int shiftIDAtuoRefresh()
        {
            int shiftitem = 0;
            string firstBegin = "0758";
            string firstEnd = "1540";
            string secondBegin = "1558";
            string secondEnd = "2340";
            string thirdBegin = "2358";
            string thirdEnd = "0740";
            DateTime dt = DateTime.Now;
            object shiftT = null;

            #region 从数据库获取值,填充以上变量

            DataTable shiftTable = GetShiftData();
            if (shiftTable != null && shiftTable.Rows.Count >= 3)
            {
                shiftT = shiftTable.Rows[0]["Shift_st"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        firstBegin = String.Format("{0:HHmm}", dt);
                    }
                }
                shiftT = shiftTable.Rows[0]["Shift_et"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        firstEnd = String.Format("{0:HHmm}", dt);
                    }
                }

                shiftT = shiftTable.Rows[1]["Shift_st"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        secondBegin = String.Format("{0:HHmm}", dt);
                    }
                }
                shiftT = shiftTable.Rows[1]["Shift_et"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        secondEnd = String.Format("{0:HHmm}", dt);
                    }
                }

                shiftT = shiftTable.Rows[2]["Shift_st"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        thirdBegin = String.Format("{0:HHmm}", dt);
                    }
                }
                shiftT = shiftTable.Rows[2]["Shift_et"];
                if (shiftT != null && shiftT != System.DBNull.Value)
                {
                    if (DateTime.TryParse(shiftT.ToString(), out dt))
                    {
                        thirdEnd = String.Format("{0:HHmm}", dt);
                    }
                }
            }
            #endregion

            string hhmm = DateTime.Now.ToString("HHmm");
            if (((hhmm.CompareTo(firstBegin) > 0) && (hhmm.CompareTo(firstEnd) < 0)) || ((hhmm.CompareTo(secondBegin) > 0) && (hhmm.CompareTo(secondEnd) < 0)) || ((hhmm.CompareTo(thirdBegin) > 0) || (hhmm.CompareTo(thirdEnd) < 0)))
            {
                if ((hhmm.CompareTo(secondBegin) == 1) && (hhmm.CompareTo(secondEnd) == -1))
                {
                    shiftitem = 2;
                }
                //else if (hhmm.CompareTo(thirdEnd) == -1 || hhmm.CompareTo(thirdEnd) == 0)
                //{
                //    shiftitem = 3;
                //}
                else if ((hhmm.CompareTo(thirdBegin) == 1) && (hhmm.CompareTo(thirdEnd) == -1))
                {
                    shiftitem = 3;
                }
                else if ((hhmm.CompareTo(firstEnd) == -1) && (hhmm.CompareTo(firstBegin) == 1))
                {
                    shiftitem = 1;
                }
            }
            return shiftitem;
            
        }
        #endregion

        #region 工厂日历

        /// <summary>
        /// 工厂日历行
        /// </summary>
        /// <param name="planDate">计划生产日期</param>
        /// <param name="shiftId">班次</param>
        /// <returns>返回对应工厂日历行</returns>
        public static DataRow GetShiftTimeRow(DateTime planDate, int shiftId)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            dbHelper.ClearParameter();
            dbHelper.CommandType = CommandType.Text;
            string strSql = "select * from PptShiftTime where Convert(varchar,Convert(datetime,ShiftDT),112) = @PlanDate and ShiftId = @ShiftId";
            dbHelper.CommandText = strSql;
            dbHelper.AddParameter("@PlanDate", String.Format("{0:yyyyMMdd}", planDate));
            dbHelper.AddParameter("@ShiftId", shiftId);
            DataTable dt = dbHelper.ToDataTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0];
            }
            else
            {
                return null;
            }
        }

        #endregion

        #region 计划及配方

        #region 获取当前计划配方数据(基于PlanLog)

        /// <summary>
        /// 获取当前计划配方数据(基于PlanLog)
        /// </summary>
        /// <returns>返回当前计划配方数据</returns>
        //public static Entity.PlanRecipeData GetCurrentPlanRecipeData()
        //{
        //    Entity.PlanLog planLog = PptPlan.PlanHelper.PlanLog;
        //    if (planLog != null)
        //    {
        //        Entity.PlanRecipeData planRecipeData = GetPlanRecipeData(planLog.LastPlanID, String.Empty);
        //        if (planRecipeData != null)
        //        {
        //            planRecipeData.RecipeHeadData.ShiftID = (short)planLog.LastShiftID;
        //            planRecipeData.RecipeHeadData.ClassID = (short)planLog.LastClassID;
        //            return planRecipeData;
        //        }
        //    }
        //    return null;
        //}

        #endregion

        #region 根据计划编号获取计划及配方数据

        /// <summary>
        /// 根据计划编号获取计划及配方数据
        /// </summary>
        /// <param name="planID">计划编号</param>
        /// <param name="recipeVersion">重传配方信息[新的配方版本]</param>
        /// <returns>返回对应的计划配方数据</returns>
        //public static Entity.PlanRecipeData GetPlanRecipeData(string planID, string recipeVersion)
        //{
        //    if (!String.IsNullOrEmpty(planID))
        //    {
        //        if (Product.PptPlan.PlanHelper.PlanExists(planID))
        //        {
        //            #region 获取计划配方基础数据

        //            Entity.PlanRecipeData planRecipeData = new Entity.PlanRecipeData();
        //            //1、计划数据
        //            planRecipeData.PlanData = Product.PptPlan.PlanHelper.GetPlanDataEntity(planID);

        //            //针对重传配方时选择了与原计划配方不同版本时,通过新配方版本获取配方数据
        //            if (!String.IsNullOrEmpty(recipeVersion))
        //            {
        //                planRecipeData.PlanData.RecipeVersion = recipeVersion;
        //                Entity.SimplePmtRecipe simpleRecipe = Technical.TechnicalHelper.GetRecipeMaterial(planRecipeData.PlanData.RecipeMaterialCode, recipeVersion);
        //                planRecipeData.PlanData.RecipeGUID = simpleRecipe.GUID;
        //                planRecipeData.PlanData.RecipeCode = Technical.PmtRecipe.RecipeHelper.GenerateNextRecipeCode(planRecipeData.PlanData.RecipeMaterialCode, recipeVersion);
        //            }

        //            //2、配方主数据
        //            planRecipeData.RecipeData = Technical.PmtRecipe.RecipeHelper.GetRecipeEntityByGUID(planRecipeData.PlanData.RecipeGUID);

        //            if (Global.PublicVar.Instance.IsContainMix)
        //            {
        //                //3、上辅机称量头及称量物料数据
        //                planRecipeData.DicMixWeightHeadList = Technical.PmtRecipe.RecipeHelper.GetMixWeightHeadDicByRecipeGUID(planRecipeData.PlanData.RecipeGUID);
        //                //4、密炼机头参数及密炼步骤数据
        //                planRecipeData.DicMixHeadList = Technical.PmtRecipe.RecipeHelper.GetMixHeadDicByRecipeGUID(planRecipeData.PlanData.RecipeGUID);
        //            }
        //            if (Global.PublicVar.Instance.IsContainMill)
        //            {
        //                //5、下辅机称量头及称量物料数据
        //                planRecipeData.DicMillWeightHeadList = Technical.PmtRecipe.RecipeHelper.GetMillWeightHeadDicByRecipeGUID(planRecipeData.PlanData.RecipeGUID);
        //                //6、开炼机头参数及开炼步骤数据
        //                planRecipeData.DicMillHeadList = Technical.PmtRecipe.RecipeHelper.GetMillHeadDicByRecipeGUID(planRecipeData.PlanData.RecipeGUID);
        //            }                   

        //            #endregion

        //            #region 数据整理

        //            planRecipeData.RecipeHeadData.DownloadFlag = (Int16)Entity.DownLoadFlag.DownLoad;
        //            planRecipeData.RecipeHeadData.UnitNum = 1;
        //            planRecipeData.RecipeHeadData.RecipeName = planRecipeData.PlanData.RecipeMaterialName;
        //            planRecipeData.RecipeHeadData.RecipeVersion = planRecipeData.PlanData.RecipeVersion;
        //            planRecipeData.RecipeHeadData.PlanID = planRecipeData.PlanData.PlanID;
        //            planRecipeData.RecipeHeadData.PlanLotNumber = planRecipeData.PlanData.PlanID;       //批次号默认设置为计划号
        //            planRecipeData.RecipeHeadData.Operator = Mesnac.Basic.UserInfo.Instance.UserName;
        //            planRecipeData.RecipeHeadData.EquipCode = Basic.BasicHelper.BasEquip.EquipCode;
        //            planRecipeData.RecipeHeadData.PlanNum = (Int16)planRecipeData.PlanData.PlanNum;
        //            planRecipeData.RecipeHeadData.ShiftID = (Int16)planRecipeData.PlanData.ShiftID;
        //            planRecipeData.RecipeHeadData.ClassID = (Int16)planRecipeData.PlanData.ClassID;
        //            Int16 serialNum = 0;        //计划流水号
        //            Int16.TryParse(planRecipeData.PlanData.PlanID.Substring(10), out serialNum);
        //            planRecipeData.RecipeHeadData.SerialNumber = serialNum;

        //            #endregion

        //            return planRecipeData;
        //        }
        //    }
        //    return null;
        //}

        #endregion

        //#region 获取称量物料数据表

        ///// <summary>
        ///// 获取称量物料数据表
        ///// </summary>
        ///// <param name="planRecipeData">计划配方数据</param>
        ///// <returns>返回称量物料数据表</returns>
        //public static DataTable GetWeightListTable(Entity.PlanRecipeData planRecipeData)
        //{
        //    DataTable weightListTable = new DataTable();
        //    weightListTable.TableName = "WeightListTable_" + Guid.NewGuid().ToString();
        //    weightListTable.Columns.Add("UnitNum", typeof(string));
        //    weightListTable.Columns.Add("WeightID", typeof(int));
        //    weightListTable.Columns.Add("JarNum", typeof(int));
        //    weightListTable.Columns.Add("MaterialName", typeof(string));
        //    weightListTable.Columns.Add("SetWeight", typeof(double));
        //    weightListTable.Columns.Add("RealWeight", typeof(double));
        //    weightListTable.Columns.Add("SetUpTolerance", typeof(double));
        //    weightListTable.Columns.Add("SetLowTolerance", typeof(double));
        //    weightListTable.Columns.Add("RealTolerance", typeof(double));

        //    if (Global.PublicVar.Instance.IsContainMix && planRecipeData.DicMixWeightHeadList != null && planRecipeData.DicMixWeightHeadList.Count > 0)
        //    {
        //        //添加上辅机称量至称量列表
        //        foreach (string unitNum in planRecipeData.DicMixWeightHeadList.Keys)
        //        {
        //            Entity.PmtMixWeightHead mixWeightHead = planRecipeData.DicMixWeightHeadList[unitNum];
        //            foreach (Entity.PmtMixWeight mixWeight in mixWeightHead.WeightList)
        //            {
        //                if (mixWeight.ActCode == 1)
        //                {
        //                    DataRow row = weightListTable.NewRow();
        //                    row["UnitNum"] = unitNum;
        //                    row["WeightID"] = mixWeight.WeightID;
        //                    row["JarNum"] = mixWeight.JarSerial;
        //                    row["MaterialName"] = mixWeight.MaterialName;
        //                    row["SetWeight"] = mixWeight.SetWeight;
        //                    row["RealWeight"] = 0.00;
        //                    row["SetUpTolerance"] = mixWeight.SetUpTolerance;
        //                    row["SetLowTolerance"] = mixWeight.SetLowTolerance;
        //                    row["RealTolerance"] = 0.00;
        //                    weightListTable.Rows.Add(row);
        //                }
        //            }
        //        }
        //    }
            
        //    if (Global.PublicVar.Instance.IsContainMill && planRecipeData.DicMillWeightHeadList != null && planRecipeData.DicMillWeightHeadList.Count > 0)
        //    {
        //        //添加下辅机称量至称量列表
        //        foreach (string unitNum in planRecipeData.DicMillWeightHeadList.Keys)
        //        {
        //            Entity.PmtMillWeightHead millWeightHead = Cache.PlanRecipeCache.Instance.Data.DicMillWeightHeadList[unitNum];
        //            foreach (Entity.PmtMillWeight millWeight in millWeightHead.WeightList)
        //            {
        //                if (millWeight.ActCode == 1)
        //                {
        //                    DataRow row = weightListTable.NewRow();
        //                    row["UnitNum"] = unitNum;
        //                    row["WeightID"] = millWeight.WeightID;
        //                    row["JarNum"] = millWeight.JarSerial;
        //                    row["MaterialName"] = millWeight.MaterialName;
        //                    row["SetWeight"] = millWeight.SetWeight;
        //                    row["RealWeight"] = 0.00;
        //                    row["SetUpTolerance"] = millWeight.SetUpTolerance;
        //                    row["SetLowTolerance"] = millWeight.SetLowTolerance;
        //                    row["RealTolerance"] = 0.00;
        //                    weightListTable.Rows.Add(row);
        //                }
        //            }
        //        }
        //    }
            
        //    weightListTable = Mesnac.Basic.DataProcessor.FormatDataTable(weightListTable, null, 2);
        //    return weightListTable;
        //}

        //#endregion

        //#region 获取密炼步骤数据表

        ///// <summary>
        ///// 获取密炼步骤数据表
        ///// </summary>
        ///// <param name="planRecipeData">计划配方数据</param>
        ///// <returns>返回密炼步骤数据表</returns>
        //public static DataTable GetMixStepListTable(Entity.PlanRecipeData planRecipeData)
        //{
        //    DataTable mixStepListTable = new DataTable();
        //    mixStepListTable.TableName = "MixStepListTable_" + Guid.NewGuid().ToString();
        //    mixStepListTable.Columns.Add("UnitNum", typeof(string));
        //    mixStepListTable.Columns.Add("MixStep", typeof(int));
        //    mixStepListTable.Columns.Add("TermCode", typeof(string));
        //    mixStepListTable.Columns.Add("TermName", typeof(string));
        //    mixStepListTable.Columns.Add("MixTime", typeof(int));
        //    mixStepListTable.Columns.Add("MixTimeLimit", typeof(int));
        //    mixStepListTable.Columns.Add("MixTemp", typeof(double));
        //    mixStepListTable.Columns.Add("MixTempLimit", typeof(double));
        //    mixStepListTable.Columns.Add("MixEnergy", typeof(double));
        //    mixStepListTable.Columns.Add("MixEnergyLimit", typeof(double));
        //    mixStepListTable.Columns.Add("MixPower", typeof(int));
        //    mixStepListTable.Columns.Add("MixPowerLimit", typeof(int));
        //    mixStepListTable.Columns.Add("ActionCode", typeof(string));
        //    mixStepListTable.Columns.Add("ActionName", typeof(string));
        //    mixStepListTable.Columns.Add("MixPress", typeof(double));
        //    mixStepListTable.Columns.Add("MixSpeed", typeof(double));
        //    mixStepListTable.Columns.Add("MixRollerGap", typeof(double));
        //    mixStepListTable.Columns.Add("MixRamPosition", typeof(double));

        //    if (Global.PublicVar.Instance.IsContainMix && planRecipeData.DicMixHeadList != null && planRecipeData.DicMixHeadList.Count > 0)
        //    {
        //        //添加密炼步骤至密炼步骤列表
        //        foreach (string unitNum in planRecipeData.DicMixHeadList.Keys)
        //        {
        //            Entity.PmtMixHead mixHead = planRecipeData.DicMixHeadList[unitNum];
        //            foreach (Entity.PmtMixStep mixStep in mixHead.MixStepList)
        //            {
        //                DataRow row = mixStepListTable.NewRow();
        //                row["UnitNum"] = unitNum;
        //                row["MixStep"] = mixStep.MixStep;
        //                row["TermCode"] = mixStep.TermCode;
        //                row["TermName"] = Technical.TechnicalHelper.GetMixTermShowNameByTermCode(mixStep.TermCode);
        //                row["MixTime"] = mixStep.MixTime;
        //                row["MixTimeLimit"] = mixStep.MixTimeLimit;
        //                row["MixTemp"] = mixStep.MixTemp;
        //                row["MixTempLimit"] = mixStep.MixTempLimit;
        //                row["MixEnergy"] = mixStep.MixEnergy;
        //                row["MixEnergyLimit"] = mixStep.MixEnergyLimit;
        //                row["MixPower"] = mixStep.MixPower;
        //                row["MixPowerLimit"] = mixStep.MixPowerLimit;
        //                row["ActionCode"] = mixStep.ActionCode;
        //                row["ActionName"] = Technical.TechnicalHelper.GetMixActionShowNameByActionCode(mixStep.ActionCode);
        //                row["MixPress"] = mixStep.MixPress;
        //                row["MixSpeed"] = mixStep.MixSpeed;
        //                row["MixRollerGap"] = mixStep.MixRollerGap;
        //                row["MixRamPosition"] = mixStep.MixRamPosition;
        //                mixStepListTable.Rows.Add(row);
        //            }
        //        }
        //    }

        //    return mixStepListTable;
        //}

        //#endregion

        //#region 获取开炼步骤数据表

        ///// <summary>
        ///// 获取开炼步骤数据表
        ///// </summary>
        ///// <param name="planRecipeData">计划配方数据</param>
        ///// <returns>返回开炼步骤数据表</returns>
        //public static DataTable GetMillStepListTable(Entity.PlanRecipeData planRecipeData)
        //{
        //    DataTable millStepListTable = new DataTable();
        //    millStepListTable.TableName = "MillStepListTable_" + Guid.NewGuid().ToString();
        //    millStepListTable.Columns.Add("UnitNum", typeof(string));
        //    millStepListTable.Columns.Add("MillStep", typeof(int));
        //    millStepListTable.Columns.Add("ActionCode", typeof(string));
        //    millStepListTable.Columns.Add("ActionName", typeof(string));
        //    millStepListTable.Columns.Add("MillTime", typeof(int));
        //    millStepListTable.Columns.Add("MillSpeed", typeof(double));
        //    millStepListTable.Columns.Add("MillCoolDeviceSpeed", typeof(double));
        //    millStepListTable.Columns.Add("MillRollerGap", typeof(double));
        //    millStepListTable.Columns.Add("MillWaterTemp", typeof(double));
        //    millStepListTable.Columns.Add("MillRubberTemp", typeof(double));
        //    millStepListTable.Columns.Add("MillSpeedRatio", typeof(double));

        //    if (Global.PublicVar.Instance.IsContainMill && planRecipeData.DicMillHeadList != null && planRecipeData.DicMillHeadList.Count > 0)
        //    {
        //        //添加开炼步骤至开炼步骤列表
        //        foreach (string unitNum in planRecipeData.DicMillHeadList.Keys)
        //        {
        //            Entity.PmtMillHead millHead = planRecipeData.DicMillHeadList[unitNum];
        //            foreach (Entity.PmtMillStep millStep in millHead.MillStepList)
        //            {
        //                DataRow row = millStepListTable.NewRow();
        //                row["UnitNum"] = unitNum;
        //                row["MillStep"] = millStep.MillStep;
        //                row["ActionCode"] = millStep.ActionCode;
        //                row["ActionName"] = Technical.TechnicalHelper.GetMillActionShowNameByActionCode(millStep.ActionCode);
        //                row["MillTime"] = millStep.MillTime;
        //                row["MillSpeed"] = millStep.MillSpeed;
        //                row["MillCoolDeviceSpeed"] = millStep.MillCoolDeviceSpeed;
        //                row["MillRollerGap"] = millStep.MillRollerGap;
        //                row["MillWaterTemp"] = millStep.MillWaterTemp;
        //                row["MillRubberTemp"] = millStep.MillRubberTemp;
        //                row["MillSpeedRatio"] = millStep.MillSpeedRatio;
        //                millStepListTable.Rows.Add(row);
        //            }
        //        }
        //    }
            
        //    return millStepListTable;
        //}

        //#endregion

        #region 更新计划配方信息

        /// <summary>
        /// 更新计划配方信息
        /// </summary>
        /// <param name="planID">计划编号</param>
        /// <param name="newRecipeGUID">新的配方GUID</param>
        /// <param name="newRecipeVersion">新的配方版本</param>
        /// <param name="newRecipeCode">新的配方编码</param>
        public static void UpdatePlanRecipe(string planID, string newRecipeGUID, string newRecipeVersion, string newRecipeCode)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            dbHelper.CommandType = CommandType.Text;
            string sqlstr = "update PptPlan set RecipeGUID = @RecipeGUID, RecipeVersion = @RecipeVersion, @RecipeCode = @RecipeCode where PlanID = @PlanID";
            dbHelper.CommandText = sqlstr;
            dbHelper.ClearParameter();
            dbHelper.AddParameter("@RecipeGUID", newRecipeGUID);
            dbHelper.AddParameter("@RecipeVersion", newRecipeVersion);
            dbHelper.AddParameter("@RecipeCode", newRecipeCode);
            dbHelper.AddParameter("@PlanID", planID);
            dbHelper.ExecuteNonQuery();
        }

        #endregion

        #endregion

        #region 批次业务

        #region 在本地库中添加批报表数据

        /// <summary>
        /// 在本地库中添加批报表数据
        /// </summary>
        /// <param name="planId">对应的计划编号</param>
        /// <returns>成功返回true,失败返回false</returns>
        //public static bool AddPptGroupLot(string planId)
        //{
        //    string strSql = String.Empty;
        //    DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
        //    if (dbHelper == null)
        //    {
        //        throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
        //    }
        //    dbHelper.CommandType = CommandType.Text;
        //    dbHelper.ClearParameter();
        //    strSql = "Update PptGroupLot set FinishTag = 1 where FinishTag = 0";
        //    dbHelper.CommandText = strSql;
        //    dbHelper.ExecuteNonQuery();

        //    Entity.RT_Plan planData = PptPlan.PlanHelper.GetPlanDataEntity(planId);
        //    if (planData != null)
        //    {
        //        dbHelper.ClearParameter();
        //        strSql = "insert into PptGroupLot(GUID,ShiftID,ShiftClass,RecipeMaterialCode,RecipeMaterialName,SetNumber,StartDatetime,FinishTag,FinishNum)";
        //        strSql += " values(NEWID(),@ShiftID,@ShiftClass,@RecipeCode,@RecipeName,@SetNumber,@StartDatetime,@FinishTag,@FinishNum)";
        //        dbHelper.CommandText = strSql;
        //        dbHelper.AddParameter("@ShiftID", planData.ShiftID);
        //        dbHelper.AddParameter("@ShiftClass", planData.ClassID);
        //        dbHelper.AddParameter("@RecipeCode", planData.RecipeMaterialCode);
        //        dbHelper.AddParameter("@RecipeName", planData.RecipeMaterialName);
        //        dbHelper.AddParameter("@SetNumber", planData.PlanNum);
        //        dbHelper.AddParameter("@StartDatetime", DateTime.Now);
        //        dbHelper.AddParameter("@FinishTag", 0);
        //        dbHelper.AddParameter("@FinishNum", 0);
        //        dbHelper.ExecuteNonQuery();
        //        ICSharpCode.Core.LoggingService<ProductHelper>.Debug("添加批报表成功!");
        //    }
        //    else
        //    {
        //        ICSharpCode.Core.LoggingService<ProductHelper>.Debug(String.Format("添加批报表失败,未找到对应计划号[{0}]的计划数据!", planId));
        //    }
            
        //    return true;
        //}

        #endregion

        #region 更新本地库批次信息(PptGroupLot)

        /// <summary>
        /// 更新本地库批次信息(PptGroupLot)
        /// </summary>
        /// <param name="newPlanNum">新设定的计划数</param>
        public static void UpdateGroupLot(int newPlanNum)
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
            }
            dbHelper.ClearParameter();
            dbHelper.CommandType = CommandType.Text;
            string strSql = "Update PptGroupLot Set SetNumber= @SetNumber where FinishTag=0";
            dbHelper.CommandText = strSql;
            dbHelper.AddParameter("@SetNumber", newPlanNum);
            dbHelper.ExecuteNonQuery();
        }

        #endregion

        #endregion

        #region 条码业务

        #region 清除扫描条码数据

        /// <summary>
        /// 清除扫描条码数据,清空本地条码表(PptShelfBar)数据
        /// </summary>
        public static void TruncatePptShelfBar()
        {
            try
            {
                DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
                if (dbHelper == null)
                {
                    throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
                }
                dbHelper.CommandType = CommandType.Text;
                dbHelper.ClearParameter();
                dbHelper.CommandType = CommandType.Text;
                string strSql1 = "if exists(select * from sysobjects where xtype='U' and name='PptShelfBar') truncate table PptShelfBar";
                dbHelper.CommandText = strSql1;
                dbHelper.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                ICSharpCode.Core.LoggingService<ProductHelper>.Error("清除扫描条码数据异常:" + ex.Message, ex);
            }
        }
        #endregion

        #endregion

        #region 掺用业务

        #region 为掺用配方增加下传计划标志

        /// <summary>
        /// 为掺用配方增加下传计划标志
        /// </summary>
        /// <param name="recipeMaterialCode">配方物料编码</param>
        public static void SetExePlan(string recipeMaterialCode)
        {
            try
            {
                DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
                if (dbHelper == null)
                {
                    throw new Exception(Mesnac.Basic.LanguageHelper.DataBaseConnectError);
                }
                dbHelper.CommandType = CommandType.Text;
                dbHelper.ClearParameter();
                string strSql = "truncate table PmtExecPlan;truncate table PmtChanYong;";
                strSql += "insert into PmtExecPlan(MaterCode, PlanFlag) values(@MaterCode,@PlanFlag)";
                dbHelper.CommandText = strSql;
                dbHelper.AddParameter("@MaterCode", recipeMaterialCode);
                dbHelper.AddParameter("@PlanFlag", "1");
                dbHelper.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                ICSharpCode.Core.LoggingService<ProductHelper>.Error("为掺用配方增加下传计划标志异常:" + ex.Message, ex);
            }
        }

        #endregion

        #endregion
    }
}